1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
/* Find how deeply inside an .RPM the real data is */
/* kept, and report the offset in bytes */
/* Wouldn't it be a lot more sane if we could just untar these things? */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif
#ifndef BUFSIZ
# define BUFSIZ 8192
#endif
typedef struct {
const char *type;
const unsigned char *magic;
const size_t len;
} magic_t;
static const unsigned char magic_gzip[] = { '\037', '\213', '\010' };
static const unsigned char magic_bzip2[] = { 'B', 'Z', 'h' };
static const unsigned char magic_xz[] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
static const magic_t magics[] = {
#define DECLARE_MAGIC_T(t) { .type = #t, .magic = magic_##t, .len = sizeof(magic_##t), },
DECLARE_MAGIC_T(gzip)
DECLARE_MAGIC_T(bzip2)
DECLARE_MAGIC_T(xz)
#undef DECLARE_MAGIC_T
};
#define MAGIC_SIZE_MIN 3
#define MAGIC_SIZE_MAX 6
int main(int argc, char *argv[])
{
int show_magic = 0;
size_t i, read_cnt, offset, left;
FILE *fp = stdin;
char p[BUFSIZ];
if (argc == 2 && !strcmp(argv[1], "-v")) {
show_magic = 1;
--argc;
}
if (argc != 1) {
puts("Usage: rpmoffset < rpmfile");
return 1;
}
/* fp = fopen(argv[1], "r"); */
offset = left = 0;
while (1) {
read_cnt = fread(p + left, 1, sizeof(p) - left, fp);
if (read_cnt + left < MAGIC_SIZE_MIN)
break;
for (i = 0; i < ARRAY_SIZE(magics); ++i) {
const char *needle;
if (read_cnt + left < magics[i].len)
continue;
needle = memmem(p, sizeof(p), magics[i].magic, magics[i].len);
if (needle) {
if (show_magic)
printf("%s ", magics[i].type);
printf("%zu\n", offset + (needle - p));
return 0;
}
}
memmove(p, p + left + read_cnt - MAGIC_SIZE_MIN + 1, MAGIC_SIZE_MIN - 1);
offset += read_cnt;
if (left == 0) {
offset -= MAGIC_SIZE_MIN - 1;
left = MAGIC_SIZE_MIN - 1;
}
}
if (ferror(stdin))
perror(argv[0]);
return 1;
}
|