1 /* file.c - describe file type
2  *
3  * Copyright 2016 The Android Open Source Project
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/file.html
6 
7 USE_FILE(NEWTOY(file, "<1bhLs[!hL]", TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config FILE
10   bool "file"
11   default y
12   help
13     usage: file [-bhLs] [FILE...]
14 
15     Examine the given files and describe their content types.
16 
17     -b	Brief (no filename)
18     -h	Don't follow symlinks (default)
19     -L	Follow symlinks
20     -s	Show block/char device contents
21 */
22 
23 #define FOR_file
24 #include "toys.h"
25 
GLOBALS(int max_name_len;off_t len;)26 GLOBALS(
27   int max_name_len;
28 
29   off_t len;
30 )
31 
32 // We don't trust elf.h to be there, and two codepaths for 32/64 is awkward
33 // anyway, so calculate struct offsets manually. (It's a fixed ABI.)
34 static void do_elf_file(int fd)
35 {
36   int endian = toybuf[5], bits = toybuf[4], i, j, dynamic = 0, stripped = 1,
37       phentsize, phnum, shsize, shnum;
38   int64_t (*elf_int)(void *ptr, unsigned size);
39   char *map = 0;
40   long phoff, shoff;
41 
42   printf("ELF ");
43   elf_int = (endian==2) ? peek_be : peek_le;
44 
45   // executable type
46   i = elf_int(toybuf+16, 2);
47   if (i == 1) printf("relocatable");
48   else if (i == 2) printf("executable");
49   else if (i == 3) printf("shared object");
50   else if (i == 4) printf("core dump");
51   else printf("(bad type %d)", i);
52   if (elf_int(toybuf+36+12*(bits==2), 4) & 0x8000) printf(" (fdpic)");
53   printf(", ");
54 
55   // "64-bit"
56   if (bits == 1) printf("32-bit ");
57   else if (bits == 2) printf("64-bit ");
58   else {
59     printf("(bad class %d) ", bits);
60     bits = 0;
61   }
62 
63   // "LSB"
64   if (endian == 1) printf("LSB ");
65   else if (endian == 2) printf("MSB ");
66   else {
67     printf("(bad endian %d) \n", endian);
68     endian = 0;
69   }
70 
71   // "x86".
72   printf("%s", elf_arch_name(elf_int(toybuf+18, 2)));
73 
74   bits--;
75   // If what we've seen so far doesn't seem consistent, bail.
76   if (!((bits&1)==bits && endian)) {
77     printf(", corrupt?\n");
78     return;
79   }
80 
81   // Parsing ELF means following tables that may point to data earlier in
82   // the file, so sequential reading involves buffering unknown amounts of
83   // data. Just skip it if we can't mmap.
84   if (MAP_FAILED == (map = mmap(0, TT.len, PROT_READ, MAP_SHARED, fd, 0)))
85     goto bad;
86 
87   // Stash what we need from the header; it's okay to reuse toybuf after this.
88   phentsize = elf_int(toybuf+42+12*bits, 2);
89   phnum = elf_int(toybuf+44+12*bits, 2);
90   phoff = elf_int(toybuf+28+4*bits, 4+4*bits);
91   shsize = elf_int(toybuf+46+12*bits, 2);
92   shnum = elf_int(toybuf+48+12*bits, 2);
93   shoff = elf_int(toybuf+32+8*bits, 4+4*bits);
94 
95   // With binutils, phentsize seems to only be non-zero if phnum is non-zero.
96   // Such ELF files are rare, but do exist. (Android's crtbegin files, say.)
97   if (phnum && (phentsize != 32+24*bits)) {
98     printf(", corrupt phentsize %d?", phentsize);
99     goto bad;
100   }
101 
102   // Parsing ELF means following tables that may point to data earlier in
103   // the file, so sequential reading involves buffering unknown amounts of
104   // data. Just skip it if we can't mmap.
105   if (MAP_FAILED == (map = mmap(0, TT.len, PROT_READ, MAP_SHARED, fd, 0)))
106     goto bad;
107 
108   // We need to read the phdrs for dynamic vs static.
109   // (Note: fields got reordered for 64 bit)
110   if (phoff<0 || phoff>TT.len || phnum*phentsize>TT.len-phoff) goto bad;
111   for (i = 0; i<phnum; i++) {
112     char *phdr = map+phoff+i*phentsize;
113     int p_type = elf_int(phdr, 4);
114     unsigned long long p_offset, p_filesz;
115 
116     if (p_type==2 /*PT_DYNAMIC*/) dynamic = 1;
117     if (p_type!=3 /*PT_INTERP*/ && p_type!=4 /*PT_NOTE*/) continue;
118 
119     j = bits+1;
120     p_offset = elf_int(phdr+4*j, 4*j);
121     p_filesz = elf_int(phdr+16*j, 4*j);
122 
123     if (p_type==3 /*PT_INTERP*/) {
124       if (p_filesz>TT.len || p_offset>TT.len-p_filesz) goto bad;
125       printf(", dynamic (%.*s)", (int)p_filesz, map+p_offset);
126     }
127   }
128   if (!dynamic) printf(", static");
129 
130   // We need to read the shdrs for stripped/unstripped and any notes.
131   // Notes are in program headers *and* section headers, but some files don't
132   // contain program headers, so we prefer to check here.
133   // (Note: fields got reordered for 64 bit)
134   if (shoff<0 || shoff>TT.len || shnum*shsize>TT.len-shoff) goto bad;
135   for (i = 0; i<shnum; i++) {
136     char *shdr = map+shoff+i*shsize;
137     unsigned long sh_offset;
138     int sh_type, sh_size;
139 
140     if (shdr>map+TT.len-(8+4*(bits+1))) goto bad;
141     sh_type = elf_int(shdr+4, 4);
142     sh_offset = elf_int(shdr+8+8*(bits+1), 4*(bits+1));
143     sh_size = elf_int(shdr+8+12*(bits+1), 4);
144     if (sh_offset>TT.len || sh_size>TT.len-sh_offset) goto bad;
145 
146     if (sh_type == 2 /*SHT_SYMTAB*/) {
147       stripped = 0;
148       break;
149     } else if (sh_type == 7 /*SHT_NOTE*/) {
150       char *note = map+sh_offset;
151 
152       // An ELF note is a sequence of entries, each consisting of an
153       // ndhr followed by n_namesz+n_descsz bytes of data (each of those
154       // rounded up to the next 4 bytes, without this being reflected in
155       // the header byte counts themselves).
156       while (sh_size >= 3*4) { // Don't try to read a truncated entry.
157         unsigned n_namesz, n_descsz, n_type, notesz;
158 
159         if (note>map+TT.len-3*4) goto bad;
160 
161         n_namesz = elf_int(note, 4);
162         n_descsz = elf_int(note+4, 4);
163         n_type = elf_int(note+8, 4);
164         notesz = 3*4 + ((n_namesz+3)&~3) + ((n_descsz+3)&~3);
165         if (notesz<n_namesz || notesz<n_descsz) goto bad;
166 
167         // Does the claimed size of this note actually fit in the section?
168         if (notesz > sh_size) goto bad;
169 
170         if (n_namesz==4 && !memcmp(note+12, "GNU", 4)) {
171           if (n_type==3 /*NT_GNU_BUILD_ID*/) {
172             printf(", BuildID=");
173             for (j = 0; j < n_descsz; ++j) printf("%02x", note[16 + j]);
174           }
175         } else if (n_namesz==8 && !memcmp(note+12, "Android", 8)) {
176           if (n_type==1 /*.android.note.ident*/ && n_descsz >= 4) {
177             printf(", for Android %d", (int)elf_int(note+20, 4));
178             // NDK r14 and later also include NDK version info. OS binaries
179             // and binaries built by older NDKs don't have this.
180             if (n_descsz >= 4+64+64)
181               printf(", built by NDK %.64s (%.64s)", note+24, note+24+64);
182           }
183         }
184 
185         note += notesz;
186         sh_size -= notesz;
187       }
188     }
189   }
190   printf(", %sstripped", stripped ? "" : "not ");
191 bad:
192   xputc('\n');
193 
194   if (map && map != MAP_FAILED) munmap(map, TT.len);
195 }
196 
do_regular_file(int fd,char * name)197 static void do_regular_file(int fd, char *name)
198 {
199   char *s;
200   unsigned len, magic;
201 
202   // zero through elf shnum, just in case
203   memset(toybuf, 0, 80);
204   if ((len = readall(fd, s = toybuf, sizeof(toybuf)))<0) perror_msg("%s", name);
205 
206   if (!len) xputs("empty");
207   // 45 bytes: https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
208   else if (len>=45 && strstart(&s, "\177ELF")) do_elf_file(fd);
209   else if (len>=8 && strstart(&s, "!<arch>\n")) xputs("ar archive");
210   else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
211     // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
212     int chunk_length = peek_be(s, 4);
213 
214     xprintf("PNG image data");
215 
216     // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
217     s += 4;
218     if (chunk_length == 13 && strstart(&s, "IHDR")) {
219       // https://www.w3.org/TR/PNG/#6Colour-values
220       char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
221                                 "grayscale with alpha", 0, "color RGBA"};
222 
223       if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
224       if (!c) c = "unknown";
225 
226       xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
227         (int)peek_be(s+4, 4), s[8], c, s[12] ? "" : "non-");
228     }
229 
230     xputc('\n');
231 
232   // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
233   } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
234     xprintf("GIF image data, version %3.3s, %d x %d\n",
235       s-3, (int)peek_le(s, 2), (int)peek_le(s+2, 2));
236 
237   // TODO: parsing JPEG for width/height is harder than GIF or PNG.
238   else if (len>32 && !memcmp(toybuf, "\xff\xd8", 2)) xputs("JPEG image data");
239 
240   // https://en.wikipedia.org/wiki/Java_class_file#General_layout
241   else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe"))
242     xprintf("Java class file, version %d.%d (Java 1.%d)\n",
243       (int)peek_be(s+2, 2), (int)peek_be(s, 2), (int)peek_be(s+2, 2)-44);
244 
245   // https://source.android.com/devices/tech/dalvik/dex-format#dex-file-magic
246   else if (len>8 && strstart(&s, "dex\n") && s[3] == 0)
247     xprintf("Android dex file, version %s\n", s);
248 
249   // https://people.freebsd.org/~kientzle/libarchive/man/cpio.5.txt
250   // the lengths for cpio are size of header + 9 bytes, since any valid
251   // cpio archive ends with a record for "TARGET!!!"
252   else if (len>85 && strstart(&s, "07070")) {
253     char *cpioformat = "unknown type";
254 
255     if (toybuf[5] == '7') cpioformat = "pre-SVR4 or odc";
256     else if (toybuf[5] == '1') cpioformat = "SVR4 with no CRC";
257     else if (toybuf[5] == '2') cpioformat = "SVR4 with CRC";
258     xprintf("ASCII cpio archive (%s)\n", cpioformat);
259   } else if (len>33 && (magic=peek(&s,2), magic==0143561 || magic==070707)) {
260     if (magic == 0143561) printf("byte-swapped ");
261     xputs("cpio archive");
262   // tar archive (old, ustar/pax, or gnu)
263   } else if (len>500 && is_tar_header(s))
264     xprintf("%s tar archive%s\n", s[257] ? "POSIX" : "old",
265       strncmp(s+262,"  ",2)?"":" (GNU)");
266   // zip/jar/apk archive, ODF/OOXML document, or such
267   else if (len>5 && strstart(&s, "PK\03\04")) {
268     int ver = toybuf[4];
269 
270     xprintf("Zip archive data");
271     if (ver) xprintf(", requires at least v%d.%d to extract", ver/10, ver%10);
272     xputc('\n');
273   } else if (len>9 && strstart(&s, "7z\xbc\xaf\x27\x1c")) {
274     int ver = toybuf[6]*10+toybuf[7];
275 
276     xprintf("7-zip archive data");
277     if (ver) xprintf(", version %d.%d", ver/10, ver%10);
278     xputc('\n');
279   } else if (len>4 && strstart(&s, "BZh") && isdigit(*s))
280     xprintf("bzip2 compressed data, block size = %c00k\n", *s);
281   else if (len > 31 && peek_be(s, 7) == 0xfd377a585a0000UL)
282     xputs("xz compressed data");
283   else if (len>10 && strstart(&s, "\x1f\x8b")) xputs("gzip compressed data");
284   else if (len>32 && !memcmp(s+1, "\xfa\xed\xfe", 3)) {
285     int bit = s[0]=='\xce'?32:64;
286     char *what;
287 
288     xprintf("Mach-O %d-bit ", bit);
289 
290     if (s[4] == 7) what = (bit==32)?"x86":"x86-";
291     else if (s[4] == 12) what = "arm";
292     else if (s[4] == 18) what = "ppc";
293     else what = NULL;
294     if (what) xprintf("%s%s ", what, (bit==32)?"":"64");
295     else xprintf("(bad arch %d) ", s[4]);
296 
297     if (s[12] == 1) what = "object";
298     else if (s[12] == 2) what = "executable";
299     else if (s[12] == 6) what = "shared library";
300     else what = NULL;
301     if (what) xprintf("%s\n", what);
302     else xprintf("(bad type %d)\n", s[9]);
303   } else if (len>36 && !memcmp(s, "OggS\x00\x02", 6)) {
304     xprintf("Ogg data");
305     // https://wiki.xiph.org/MIMETypesCodecs
306     if (!memcmp(s+28, "CELT    ", 8)) xprintf(", celt audio");
307     else if (!memcmp(s+28, "CMML    ", 8)) xprintf(", cmml text");
308     else if (!memcmp(s+28, "BBCD\0", 5)) xprintf(", dirac video");
309     else if (!memcmp(s+28, "\177FLAC", 5)) xprintf(", flac audio");
310     else if (!memcmp(s+28, "\x8bJNG\r\n\x1a\n", 8)) xprintf(", jng video");
311     else if (!memcmp(s+28, "\x80kate\0\0\0", 8)) xprintf(", kate text");
312     else if (!memcmp(s+28, "OggMIDI\0", 8)) xprintf(", midi text");
313     else if (!memcmp(s+28, "\x8aMNG\r\n\x1a\n", 8)) xprintf(", mng video");
314     else if (!memcmp(s+28, "OpusHead", 8)) xprintf(", opus audio");
315     else if (!memcmp(s+28, "PCM     ", 8)) xprintf(", pcm audio");
316     else if (!memcmp(s+28, "\x89PNG\r\n\x1a\n", 8)) xprintf(", png video");
317     else if (!memcmp(s+28, "Speex   ", 8)) xprintf(", speex audio");
318     else if (!memcmp(s+28, "\x80theora", 7)) xprintf(", theora video");
319     else if (!memcmp(s+28, "\x01vorbis", 7)) xprintf(", vorbis audio");
320     else if (!memcmp(s+28, "YUV4MPEG", 8)) xprintf(", yuv4mpeg video");
321     xputc('\n');
322   } else if (len>32 && !memcmp(s, "RIF", 3) && !memcmp(s+8, "WAVEfmt ", 8)) {
323     // https://en.wikipedia.org/wiki/WAV
324     int le = (s[3] == 'F');
325     int format = le ? peek_le(s+20,2) : peek_be(s+20,2);
326     int channels = le ? peek_le(s+22,2) : peek_be(s+22,2);
327     int hz = le ? peek_le(s+24,4) : peek_be(s+24,4);
328     int bits = le ? peek_le(s+34,2) : peek_be(s+34,2);
329 
330     xprintf("WAV audio, %s, ", le ? "LE" : "BE");
331     if (bits != 0) xprintf("%d-bit, ", bits);
332     if (channels==1||channels==2) xprintf("%s, ", channels==1?"mono":"stereo");
333     else xprintf("%d-channel, ", channels);
334     xprintf("%d Hz, ", hz);
335     // See https://tools.ietf.org/html/rfc2361, though there appear to be bugs
336     // in the RFC. This assumes wikipedia's example files are more correct.
337     if (format == 0x01) xprintf("PCM");
338     else if (format == 0x03) xprintf("IEEE float");
339     else if (format == 0x06) xprintf("A-law");
340     else if (format == 0x07) xprintf("µ-law");
341     else if (format == 0x11) xprintf("ADPCM");
342     else if (format == 0x22) xprintf("Truespeech");
343     else if (format == 0x31) xprintf("GSM");
344     else if (format == 0x55) xprintf("MP3");
345     else if (format == 0x70) xprintf("CELP");
346     else if (format == 0xfffe) xprintf("extensible");
347     else xprintf("unknown format %d", format);
348     xputc('\n');
349   } else if (len>12 && !memcmp(s, "\x00\x01\x00\x00", 4)) {
350     xputs("TrueType font");
351   } else if (len>12 && !memcmp(s, "ttcf\x00", 5)) {
352     xprintf("TrueType font collection, version %d, %d fonts\n",
353             (int)peek_be(s+4, 2), (int)peek_be(s+8, 4));
354 
355   // https://docs.microsoft.com/en-us/typography/opentype/spec/otff
356   } else if (len>12 && !memcmp(s, "OTTO", 4)) {
357     xputs("OpenType font");
358   } else if (len>4 && !memcmp(s, "BC\xc0\xde", 4)) {
359     xputs("LLVM IR bitcode");
360   } else if (strstart(&s, "-----BEGIN CERTIFICATE-----")) {
361     xputs("PEM certificate");
362 
363   // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx
364   } else if (len>0x70 && !memcmp(s, "MZ", 2) &&
365       (magic=peek_le(s+0x3c,4))<len-4 && !memcmp(s+magic, "\x50\x45\0\0", 4)) {
366     xprintf("MS PE32%s executable %s", (peek_le(s+magic+24, 2)==0x20b)?"+":"",
367         (peek_le(s+magic+22, 2)&0x2000)?"(DLL) ":"");
368     if (peek_le(s+magic+20, 2)>70) {
369       char *types[] = {0, "native", "GUI", "console", "OS/2", "driver", "CE",
370           "EFI", "EFI boot", "EFI runtime", "EFI ROM", "XBOX", 0, "boot"};
371       int type = peek_le(s+magic+92, 2);
372       char *name = (type>0 && type<ARRAY_LEN(types))?types[type]:0;
373 
374       xprintf("(%s) ", name?name:"unknown");
375     }
376     xprintf("%s\n", (peek_le(s+magic+4, 2)==0x14c)?"x86":"x86-64");
377 
378     // https://en.wikipedia.org/wiki/BMP_file_format
379   } else if (len > 0x32 && !memcmp(s, "BM", 2) && !memcmp(s+6, "\0\0\0\0", 4)) {
380     int w = peek_le(s+0x12,4), h = peek_le(s+0x16,4), bpp = peek_le(s+0x1c,2);
381 
382     xprintf("BMP image, %d x %d, %d bpp\n", w, h, bpp);
383 
384     // https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/perf.data-file-format.txt
385   } else if (len>=104 && !memcmp(s, "PERFILE2", 8)) {
386     xputs("Linux perf data");
387 
388     // https://android.googlesource.com/platform/system/core/+/master/libsparse/sparse_format.h
389   } else if (len>28 && peek_le(s, 4) == 0xed26ff3a) {
390     xprintf("Android sparse image v%d.%d, %d %d-byte blocks (%d chunks)\n",
391         (int) peek_le(s+4, 2), (int) peek_le(s+6, 2), (int) peek_le(s+16, 4),
392         (int) peek_le(s+12, 4), (int) peek_le(s+20, 4));
393 
394     // https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h
395   } else if (len>1632 && !memcmp(s, "ANDROID!", 8)) {
396     xprintf("Android boot image v%d\n", (int) peek_le(s+40, 4));
397 
398     // https://source.android.com/devices/architecture/dto/partitions
399   } else if (len>32 && peek_be(s, 4) == 0xd7b7ab1e) {
400     xprintf("Android DTB/DTBO v%d, %d entries\n", (int) peek_be(s+28, 4),
401         (int) peek_be(s+16, 4));
402 
403     // frameworks/base/core/java/com/android/internal/util/BinaryXmlSerializer.java
404   } else if (len>4 && !memcmp(s, "ABX", 3)) {
405     xprintf("Android Binary XML v%d\n", s[3]);
406 
407     // Text files, including shell scripts.
408   } else {
409     char *what = 0;
410     int i, bytes;
411 
412     // If shell script, report which interpreter
413     if (len>3 && strstart(&s, "#!")) {
414       // Whitespace is allowed between the #! and the interpreter
415       while (isspace(*s)) s++;
416       if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
417       for (what = s; (s-toybuf)<len && !isspace(*s); s++);
418       strcpy(s, " script");
419 
420     // Distinguish ASCII text, UTF-8 text, or data
421     } else for (i = 0; i<len; ++i) {
422       if (!(isprint(toybuf[i]) || isspace(toybuf[i]))) {
423         wchar_t wc;
424         if ((bytes = utf8towc(&wc, s+i, len-i))>0 && wcwidth(wc)>=0) {
425           i += bytes-1;
426           if (!what) what = "UTF-8 text";
427         } else {
428           what = "data";
429           break;
430         }
431       }
432     }
433     xputs(what ? what : "ASCII text");
434   }
435 }
436 
file_main(void)437 void file_main(void)
438 {
439   char **arg;
440 
441   for (arg = toys.optargs; *arg; ++arg) {
442     int name_len = strlen(*arg);
443 
444     if (name_len > TT.max_name_len) TT.max_name_len = name_len;
445   }
446 
447   // Can't use loopfiles here because it doesn't call function when can't open
448   for (arg = toys.optargs; *arg; arg++) {
449     char *name = *arg, *what = "unknown";
450     struct stat sb;
451     int fd = !strcmp(name, "-");
452 
453     if (!FLAG(b))
454       xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
455 
456     sb.st_size = 0;
457     if (fd || !(FLAG(L) ? stat : lstat)(name, &sb)) {
458       if (!fd && !FLAG(s) && (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode))) {
459         sprintf(what = toybuf, "%s special (%u/%u)",
460             S_ISBLK(sb.st_mode) ? "block" : "character",
461             dev_major(sb.st_rdev), dev_minor(sb.st_rdev));
462       } else if (fd || S_ISREG(sb.st_mode)) {
463         TT.len = sb.st_size;
464         // This test identifies an empty file we don't have permission to read
465         if (!fd && !sb.st_size) what = "empty";
466         else if ((fd = openro(name, O_RDONLY)) != -1) {
467           do_regular_file(fd, name);
468           if (fd) close(fd);
469           continue;
470         }
471       } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
472       else if (S_ISDIR(sb.st_mode)) what = "directory";
473       else if (S_ISSOCK(sb.st_mode)) what = "socket";
474       else if (S_ISLNK(sb.st_mode)) {
475         char *lnk = xreadlink(name);
476 
477         sprintf(what = toybuf, "%ssymbolic link to %s",
478             stat(name, &sb) ? "broken " : "", lnk);
479         free(lnk);
480       }
481       xputs(what);
482     } else xprintf("cannot open: %s\n", strerror(errno));
483   }
484 }
485