Merge from vendor branch NTPD:
[dragonfly.git] / contrib / file / file.c
1 /*
2  * file - find type of a file or files - main program.
3  *
4  * Copyright (c) Ian F. Darwin, 1987.
5  * Written by Ian F. Darwin.
6  *
7  * This software is not subject to any license of the American Telephone
8  * and Telegraph Company or of the Regents of the University of California.
9  *
10  * Permission is granted to anyone to use this software for any purpose on
11  * any computer system, and to alter it and redistribute it freely, subject
12  * to the following restrictions:
13  *
14  * 1. The author is not responsible for the consequences of use of this
15  *    software, no matter how awful, even if they arise from flaws in it.
16  *
17  * 2. The origin of this software must not be misrepresented, either by
18  *    explicit claim or by omission.  Since few users ever read sources,
19  *    credits must appear in the documentation.
20  *
21  * 3. Altered versions must be plainly marked as such, and must not be
22  *    misrepresented as being the original software.  Since few users
23  *    ever read sources, credits must appear in the documentation.
24  *
25  * 4. This notice may not be removed or altered.
26  */
27
28 #include "file.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <string.h>
32 #include <sys/param.h>  /* for MAXPATHLEN */
33 #include <fcntl.h>      /* for open() */
34 #ifdef RESTORE_TIME
35 # if (__COHERENT__ >= 0x420)
36 #  include <sys/utime.h>
37 # else
38 #  ifdef USE_UTIMES
39 #   include <sys/time.h>
40 #  else
41 #   include <utime.h>
42 #  endif
43 # endif
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>     /* for read() */
47 #endif
48 #ifdef HAVE_LOCALE_H
49 #include <locale.h>
50 #endif
51
52 #ifdef HAVE_GETOPT_H
53 #include <getopt.h>     /* for long options (is this portable?)*/
54 #endif
55
56 #include <netinet/in.h>         /* for byte swapping */
57
58 #include "patchlevel.h"
59
60 #ifndef lint
61 FILE_RCSID("@(#)$Id: file.c,v 1.69 2003/02/27 20:47:46 christos Exp $")
62 #endif  /* lint */
63
64
65 #ifdef S_IFLNK
66 # define USAGE  "Usage: %s [-bciknsvzL] [-f namefile] [-m magicfiles] file...\n"
67 #else
68 # define USAGE  "Usage: %s [-bciknsvz] [-f namefile] [-m magicfiles] file...\n"
69 #endif
70
71 #ifdef __EMX__
72 static char *apptypeName = NULL;
73 int os2_apptype (const char *fn, char *buf, int nb);
74 #endif /* __EMX__ */
75
76 #ifndef MAGIC
77 # define MAGIC "/etc/magic"
78 #endif
79
80 #ifndef MAXPATHLEN
81 #define MAXPATHLEN      512
82 #endif
83
84 int                     /* Global command-line options          */
85         debug = 0,      /* debugging                            */
86         lflag = 0,      /* follow Symlinks (BSD only)           */
87         bflag = 0,      /* brief output format                  */
88         zflag = 0,      /* follow (uncompress) compressed files */
89         sflag = 0,      /* read block special files             */
90         iflag = 0,
91         nopad = 0,      /* Don't pad output                     */
92         nobuffer = 0,   /* Do not buffer stdout                 */
93         kflag = 0;      /* Keep going after the first match     */
94
95 int                     /* Misc globals                         */
96         nmagic = 0;     /* number of valid magic[]s             */
97
98 struct  magic *magic;   /* array of magic entries               */
99
100 const char *magicfile = 0;      /* where the magic is           */
101 const char *default_magicfile = MAGIC;
102
103 char separator = ':';   /* Default field separator              */
104
105 char *progname;         /* used throughout                      */
106 int lineno;             /* line number in the magic file        */
107
108
109 static void     unwrap(char *fn);
110 static void     usage(void);
111 #ifdef HAVE_GETOPT_LONG
112 static void     help(void);
113 #endif
114 #if 0
115 static int      byteconv4(int, int, int);
116 static short    byteconv2(int, int, int);
117 #endif
118
119 int main(int, char *[]);
120
121 /*
122  * main - parse arguments and handle options
123  */
124 int
125 main(int argc, char **argv)
126 {
127         int c;
128         int action = 0, didsomefiles = 0, errflg = 0, ret = 0, app = 0;
129         char *mime, *home, *usermagic;
130         struct stat sb;
131 #define OPTSTRING       "bcdf:F:ikm:nNsvzCL"
132 #ifdef HAVE_GETOPT_LONG
133         int longindex;
134         static struct option long_options[] =
135         {
136                 {"version", 0, 0, 'v'},
137                 {"help", 0, 0, 0},
138                 {"brief", 0, 0, 'b'},
139                 {"checking-printout", 0, 0, 'c'},
140                 {"debug", 0, 0, 'd'},
141                 {"files-from", 1, 0, 'f'},
142                 {"separator", 1, 0, 'F'},
143                 {"mime", 0, 0, 'i'},
144                 {"keep-going", 0, 0, 'k'},
145 #ifdef S_IFLNK
146                 {"dereference", 0, 0, 'L'},
147 #endif
148                 {"magic-file", 1, 0, 'm'},
149                 {"uncompress", 0, 0, 'z'},
150                 {"no-buffer", 0, 0, 'n'},
151                 {"no-pad", 0, 0, 'N'},
152                 {"special-files", 0, 0, 's'},
153                 {"compile", 0, 0, 'C'},
154                 {0, 0, 0, 0},
155         };
156 #endif
157
158 #ifdef LC_CTYPE
159         setlocale(LC_CTYPE, ""); /* makes islower etc work for other langs */
160 #endif
161
162 #ifdef __EMX__
163         /* sh-like wildcard expansion! Shouldn't hurt at least ... */
164         _wildcard(&argc, &argv);
165 #endif
166
167         if ((progname = strrchr(argv[0], '/')) != NULL)
168                 progname++;
169         else
170                 progname = argv[0];
171
172         magicfile = default_magicfile;
173         if ((usermagic = getenv("MAGIC")) != NULL)
174                 magicfile = usermagic;
175         else
176                 if ((home = getenv("HOME")) != NULL) {
177                         if ((usermagic = malloc(strlen(home) + 8)) != NULL) {
178                                 (void)strcpy(usermagic, home);
179                                 (void)strcat(usermagic, "/.magic");
180                                 if (stat(usermagic, &sb)<0) 
181                                         free(usermagic);
182                                 else
183                                         magicfile = usermagic;
184                         }
185                 }
186
187 #ifndef HAVE_GETOPT_LONG
188         while ((c = getopt(argc, argv, OPTSTRING)) != -1)
189 #else
190         while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
191             &longindex)) != -1)
192 #endif
193                 switch (c) {
194 #ifdef HAVE_GETOPT_LONG
195                 case 0 :
196                         if (longindex == 1)
197                                 help();
198                         break;
199 #endif
200                 case 'b':
201                         ++bflag;
202                         break;
203                 case 'c':
204                         action = CHECK;
205                         break;
206                 case 'C':
207                         action = COMPILE;
208                         break;
209                 case 'd':
210                         ++debug;
211                         break;
212                 case 'f':
213                         if (!app) {
214                                 ret = apprentice(magicfile, action);
215                                 if (action)
216                                         exit(ret);
217                                 app = 1;
218                         }
219                         unwrap(optarg);
220                         ++didsomefiles;
221                         break;
222                 case 'F':
223                         separator = *optarg;
224                         break;
225                 case 'i':
226                         iflag++;
227                         if ((mime = malloc(strlen(magicfile) + 6)) != NULL) {
228                                 (void)strcpy(mime, magicfile);
229                                 (void)strcat(mime, ".mime");
230                                 magicfile = mime;
231                         }
232                         break;
233                 case 'k':
234                         kflag = 1;
235                         break;
236                 case 'm':
237                         magicfile = optarg;
238                         break;
239                 case 'n':
240                         ++nobuffer;
241                         break;
242                 case 'N':
243                         ++nopad;
244                         break;
245                 case 's':
246                         sflag++;
247                         break;
248                 case 'v':
249                         (void) fprintf(stdout, "%s-%d.%d\n", progname,
250                                        FILE_VERSION_MAJOR, patchlevel);
251                         (void) fprintf(stdout, "magic file from %s\n",
252                                        magicfile);
253                         return 1;
254                 case 'z':
255                         zflag++;
256                         break;
257 #ifdef S_IFLNK
258                 case 'L':
259                         ++lflag;
260                         break;
261 #endif
262                 case '?':
263                 default:
264                         errflg++;
265                         break;
266                 }
267
268         if (errflg) {
269                 usage();
270         }
271
272         if (!app) {
273                 ret = apprentice(magicfile, action);
274                 if (action)
275                         exit(ret);
276                 app = 1;
277         }
278
279         if (optind == argc) {
280                 if (!didsomefiles) {
281                         usage();
282                 }
283         }
284         else {
285                 int i, wid, nw;
286                 for (wid = 0, i = optind; i < argc; i++) {
287                         nw = strlen(argv[i]);
288                         if (nw > wid)
289                                 wid = nw;
290                 }
291                 for (; optind < argc; optind++)
292                         process(argv[optind], wid);
293         }
294
295         return 0;
296 }
297
298
299 /*
300  * unwrap -- read a file of filenames, do each one.
301  */
302 static void
303 unwrap(char *fn)
304 {
305         char buf[MAXPATHLEN];
306         FILE *f;
307         int wid = 0, cwid;
308
309         if (strcmp("-", fn) == 0) {
310                 f = stdin;
311                 wid = 1;
312         } else {
313                 if ((f = fopen(fn, "r")) == NULL) {
314                         error("Cannot open `%s' (%s).\n", fn, strerror(errno));
315                         /*NOTREACHED*/
316                 }
317
318                 while (fgets(buf, MAXPATHLEN, f) != NULL) {
319                         cwid = strlen(buf) - 1;
320                         if (cwid > wid)
321                                 wid = cwid;
322                 }
323
324                 rewind(f);
325         }
326
327         while (fgets(buf, MAXPATHLEN, f) != NULL) {
328                 buf[strlen(buf)-1] = '\0';
329                 process(buf, wid);
330                 if(nobuffer)
331                         (void) fflush(stdout);
332         }
333
334         (void) fclose(f);
335 }
336
337
338 #if 0
339 /*
340  * byteconv4
341  * Input:
342  *      from            4 byte quantity to convert
343  *      same            whether to perform byte swapping
344  *      big_endian      whether we are a big endian host
345  */
346 static int
347 byteconv4(int from, int same, int big_endian)
348 {
349         if (same)
350                 return from;
351         else if (big_endian) {          /* lsb -> msb conversion on msb */
352                 union {
353                         int i;
354                         char c[4];
355                 } retval, tmpval;
356
357                 tmpval.i = from;
358                 retval.c[0] = tmpval.c[3];
359                 retval.c[1] = tmpval.c[2];
360                 retval.c[2] = tmpval.c[1];
361                 retval.c[3] = tmpval.c[0];
362
363                 return retval.i;
364         }
365         else
366                 return ntohl(from);     /* msb -> lsb conversion on lsb */
367 }
368
369 /*
370  * byteconv2
371  * Same as byteconv4, but for shorts
372  */
373 static short
374 byteconv2(int from, int same, int big_endian)
375 {
376         if (same)
377                 return from;
378         else if (big_endian) {          /* lsb -> msb conversion on msb */
379                 union {
380                         short s;
381                         char c[2];
382                 } retval, tmpval;
383
384                 tmpval.s = (short) from;
385                 retval.c[0] = tmpval.c[1];
386                 retval.c[1] = tmpval.c[0];
387
388                 return retval.s;
389         }
390         else
391                 return ntohs(from);     /* msb -> lsb conversion on lsb */
392 }
393 #endif
394
395 /*
396  * process - process input file
397  */
398 void
399 process(const char *inname, int wid)
400 {
401         int     fd = 0;
402         static  const char stdname[] = "standard input";
403         unsigned char   buf[HOWMANY+1]; /* one extra for terminating '\0' */
404         struct stat     sb;
405         int nbytes = 0; /* number of bytes read from a datafile */
406         char match = '\0';
407
408         if (strcmp("-", inname) == 0) {
409                 if (fstat(0, &sb)<0) {
410                         error("cannot fstat `%s' (%s).\n", stdname,
411                               strerror(errno));
412                         /*NOTREACHED*/
413                 }
414                 inname = stdname;
415         }
416
417         if (wid > 0 && !bflag)
418              (void) printf("%s%c%*s", inname, separator,
419                            (int) (nopad ? 0 : 1 + (wid - strlen(inname))), "");
420
421         if (inname != stdname) {
422                 /*
423                  * first try judging the file based on its filesystem status
424                  */
425                 if (fsmagic(inname, &sb) != 0) {
426                         putchar('\n');
427                         return;
428                 }
429
430                 if ((fd = open(inname, O_RDONLY)) < 0) {
431                         /* We can't open it, but we were able to stat it. */
432                         if (sb.st_mode & 0002) ckfputs("writable, ", stdout);
433                         if (sb.st_mode & 0111) ckfputs("executable, ", stdout);
434                         ckfprintf(stdout, "can't read `%s' (%s).\n",
435                             inname, strerror(errno));
436                         return;
437                 }
438         }
439
440
441         /*
442          * try looking at the first HOWMANY bytes
443          */
444         if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) {
445                 error("read failed (%s).\n", strerror(errno));
446                 /*NOTREACHED*/
447         }
448
449         if (nbytes == 0)
450                 ckfputs(iflag ? "application/x-empty" : "empty", stdout);
451         else {
452                 buf[nbytes++] = '\0';   /* null-terminate it */
453                 match = tryit(inname, buf, nbytes, zflag);
454         }
455
456 #ifdef BUILTIN_ELF
457         if (match == 's' && nbytes > 5) {
458                 /*
459                  * We matched something in the file, so this *might*
460                  * be an ELF file, and the file is at least 5 bytes long,
461                  * so if it's an ELF file it has at least one byte
462                  * past the ELF magic number - try extracting information
463                  * from the ELF headers that can't easily be extracted
464                  * with rules in the magic file.
465                  */
466                 tryelf(fd, buf, nbytes);
467         }
468 #endif
469
470         if (inname != stdname) {
471 #ifdef RESTORE_TIME
472                 /*
473                  * Try to restore access, modification times if read it.
474                  * This is really *bad* because it will modify the status
475                  * time of the file... And of course this will affect
476                  * backup programs
477                  */
478 # ifdef USE_UTIMES
479                 struct timeval  utsbuf[2];
480                 utsbuf[0].tv_sec = sb.st_atime;
481                 utsbuf[1].tv_sec = sb.st_mtime;
482
483                 (void) utimes(inname, utsbuf); /* don't care if loses */
484 # else
485                 struct utimbuf  utbuf;
486
487                 utbuf.actime = sb.st_atime;
488                 utbuf.modtime = sb.st_mtime;
489                 (void) utime(inname, &utbuf); /* don't care if loses */
490 # endif
491 #endif
492                 (void) close(fd);
493         }
494         (void) putchar('\n');
495 }
496
497
498 int
499 tryit(const char *fn, unsigned char *buf, int nb, int zfl)
500 {
501
502         /*
503          * The main work is done here!
504          * We have the file name and/or the data buffer to be identified. 
505          */
506
507 #ifdef __EMX__
508         /*
509          * Ok, here's the right place to add a call to some os-specific
510          * routine, e.g.
511          */
512         if (os2_apptype(fn, buf, nb) == 1)
513                return 'o';
514 #endif
515         /* try compression stuff */
516         if (zfl && zmagic(fn, buf, nb))
517                 return 'z';
518
519         /* try tests in /etc/magic (or surrogate magic file) */
520         if (softmagic(buf, nb))
521                 return 's';
522
523         /* try known keywords, check whether it is ASCII */
524         if (ascmagic(buf, nb))
525                 return 'a';
526
527         /* abandon hope, all ye who remain here */
528         ckfputs(iflag ? "application/octet-stream" : "data", stdout);
529                 return '\0';
530 }
531
532 static void
533 usage(void)
534 {
535         (void)fprintf(stderr, USAGE, progname);
536         (void)fprintf(stderr, "Usage: %s -C [-m magic]\n", progname);
537 #ifdef HAVE_GETOPT_LONG
538         (void)fputs("Try `file --help' for more information.\n", stderr);
539 #endif
540         exit(1);
541 }
542
543 #ifdef HAVE_GETOPT_LONG
544 static void
545 help(void)
546 {
547         puts(
548 "Usage: file [OPTION]... [FILE]...\n"
549 "Determine file type of FILEs.\n"
550 "\n"
551 "  -m, --magic-file LIST      use LIST as a colon-separated list of magic\n"
552 "                               number files\n"
553 "  -z, --uncompress           try to look inside compressed files\n"
554 "  -b, --brief                do not prepend filenames to output lines\n"
555 "  -c, --checking-printout    print the parsed form of the magic file, use in\n"
556 "                               conjunction with -m to debug a new magic file\n"
557 "                               before installing it\n"
558 "  -f, --files-from FILE      read the filenames to be examined from FILE\n"
559 "  -i, --mime                 output mime type strings\n"
560 "  -k, --keep-going           don't stop at the first match\n"
561 "  -L, --dereference          causes symlinks to be followed\n"
562 "  -n, --no-buffer            do not buffer output\n"
563 "  -s, --special-files        treat special (block/char devices) files as\n"
564 "                             ordinary ones\n"
565 "      --help                 display this help and exit\n"
566 "      --version              output version information and exit\n"
567 );
568         exit(0);
569 }
570 #endif