summaryrefslogtreecommitdiff
path: root/2003/firmware-reveng-ccc2003/magic_ofs.c
blob: a83f5931d5309d7a3eacb14ded0e634451ae2f77 (plain)
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
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>

#include <magic.h>

/* magic_ofs - check for 'file' magic at any possible offset within a file
 *
 * (C) 2003 by Harald Welte <laforge@gnumonks.org>
 *
 * This code is subject to the GNU GPL v2
 */

int main(int argc, char **argv)
{
	struct stat st;
	magic_t cookie;
	int fd;
	off_t i;
	void *mem;

	if (argc < 2) {
		fprintf(stderr, "you have to name a file\n");
		exit(2);
	}

	if (!strlen(argv[1])) {
		fprintf(stderr, "empty argument\n");
		exit(2);
	}

	fd = open(argv[1], 0);
	if (fd < 0) {
		fprintf(stderr, "unable to open file\n");
		exit(1);
	}

	if (fstat(fd, &st)) {
		fprintf(stderr, "unable to stat file\n");
		exit(1);
	}

	mem = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, (off_t ) 0);
	if (!mem) {
		fprintf(stderr, "unable to mmap file\n");
		exit(1);
	}
	
	cookie = magic_open(MAGIC_CONTINUE);
	if (!cookie) {
		fprintf(stderr, "error opening libmagic\n");
		exit(1);
	}

	if (magic_load(cookie, NULL)) {
		fprintf(stderr, "error during magic_load\n");
		magic_close(cookie);
		exit(1);
	}

	for (i = 0; i < st.st_size; i++) {
		const char *desc;
		desc = magic_buffer(cookie, mem+i, st.st_size - i);
		if (!desc) {
			break;
		}
		if (!strcmp(desc, "data")) {
			continue;
		}
		printf("%8.8u: %s\n", i, desc);
	}

	magic_close(cookie);
	exit(0);
}
personal git repositories of Harald Welte. Your mileage may vary