80f5c4108fe34af173ec9cefdac0455dea8605c6
[dragonfly.git] / contrib / file-4 / src / file.c
1 /*
2  * Copyright (c) Ian F. Darwin 1986-1995.
3  * Software written by Ian F. Darwin and others;
4  * maintained 1995-present by Christos Zoulas and others.
5  * 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *  
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*
29  * file - find type of a file or files - main program.
30  */
31
32 #include "file.h"
33 #include "magic.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include <sys/param.h>  /* for MAXPATHLEN */
41 #include <sys/stat.h>
42 #include <fcntl.h>      /* for open() */
43 #ifdef RESTORE_TIME
44 # if (__COHERENT__ >= 0x420)
45 #  include <sys/utime.h>
46 # else
47 #  ifdef USE_UTIMES
48 #   include <sys/time.h>
49 #  else
50 #   include <utime.h>
51 #  endif
52 # endif
53 #endif
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>     /* for read() */
56 #endif
57 #ifdef HAVE_LOCALE_H
58 #include <locale.h>
59 #endif
60 #ifdef HAVE_WCHAR_H
61 #include <wchar.h>
62 #endif
63
64 #ifdef HAVE_GETOPT_H
65 #include <getopt.h>     /* for long options (is this portable?)*/
66 #else
67 #undef HAVE_GETOPT_LONG
68 #endif
69
70 #include <netinet/in.h>         /* for byte swapping */
71
72 #include "patchlevel.h"
73
74 #ifndef lint
75 FILE_RCSID("@(#)$Id: file.c,v 1.95 2004/09/27 15:28:37 christos Exp $")
76 #endif  /* lint */
77
78
79 #ifdef S_IFLNK
80 #define SYMLINKFLAG "L"
81 #else
82 #define SYMLINKFLAG ""
83 #endif
84
85 # define USAGE  "Usage: %s [-bcik" SYMLINKFLAG "nNsvz] [-f namefile] [-F separator] [-m magicfiles] file...\n       %s -C -m magicfiles\n"
86
87 #ifndef MAXPATHLEN
88 #define MAXPATHLEN      512
89 #endif
90
91 private int             /* Global command-line options          */
92         bflag = 0,      /* brief output format                  */
93         nopad = 0,      /* Don't pad output                     */
94         nobuffer = 0;   /* Do not buffer stdout                 */
95
96 private const char *magicfile = 0;      /* where the magic is   */
97 private const char *default_magicfile = MAGIC;
98 private char *separator = ":";  /* Default field separator      */
99
100 private char *progname;         /* used throughout              */
101
102 private struct magic_set *magic;
103
104 private void unwrap(char *);
105 private void usage(void);
106 #ifdef HAVE_GETOPT_LONG
107 private void help(void);
108 #endif
109 #if 0
110 private int byteconv4(int, int, int);
111 private short byteconv2(int, int, int);
112 #endif
113
114 int main(int, char *[]);
115 private void process(const char *, int);
116 private void load(const char *, int);
117
118
119 /*
120  * main - parse arguments and handle options
121  */
122 int
123 main(int argc, char *argv[])
124 {
125         int c;
126         int action = 0, didsomefiles = 0, errflg = 0;
127         int flags = 0;
128         char *home, *usermagic;
129         struct stat sb;
130 #define OPTSTRING       "bcCdf:F:ikLm:nNprsvz"
131 #ifdef HAVE_GETOPT_LONG
132         int longindex;
133         private struct option long_options[] =
134         {
135                 {"version", 0, 0, 'v'},
136                 {"help", 0, 0, 0},
137                 {"brief", 0, 0, 'b'},
138                 {"checking-printout", 0, 0, 'c'},
139                 {"debug", 0, 0, 'd'},
140                 {"files-from", 1, 0, 'f'},
141                 {"separator", 1, 0, 'F'},
142                 {"mime", 0, 0, 'i'},
143                 {"keep-going", 0, 0, 'k'},
144 #ifdef S_IFLNK
145                 {"dereference", 0, 0, 'L'},
146 #endif
147                 {"magic-file", 1, 0, 'm'},
148 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
149                 {"preserve-date", 0, 0, 'p'},
150 #endif
151                 {"uncompress", 0, 0, 'z'},
152                 {"raw", 0, 0, 'r'},
153                 {"no-buffer", 0, 0, 'n'},
154                 {"no-pad", 0, 0, 'N'},
155                 {"special-files", 0, 0, 's'},
156                 {"compile", 0, 0, 'C'},
157                 {0, 0, 0, 0},
158         };
159 #endif
160
161 #ifdef LC_CTYPE
162         setlocale(LC_CTYPE, ""); /* makes islower etc work for other langs */
163 #endif
164
165 #ifdef __EMX__
166         /* sh-like wildcard expansion! Shouldn't hurt at least ... */
167         _wildcard(&argc, &argv);
168 #endif
169
170         if ((progname = strrchr(argv[0], '/')) != NULL)
171                 progname++;
172         else
173                 progname = argv[0];
174
175         magicfile = default_magicfile;
176         if ((usermagic = getenv("MAGIC")) != NULL)
177                 magicfile = usermagic;
178         else
179                 if ((home = getenv("HOME")) != NULL) {
180                         if ((usermagic = malloc(strlen(home) + 8)) != NULL) {
181                                 (void)strcpy(usermagic, home);
182                                 (void)strcat(usermagic, "/.magic");
183                                 if (stat(usermagic, &sb)<0) 
184                                         free(usermagic);
185                                 else
186                                         magicfile = usermagic;
187                         }
188                 }
189
190 #ifndef HAVE_GETOPT_LONG
191         while ((c = getopt(argc, argv, OPTSTRING)) != -1)
192 #else
193         while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
194             &longindex)) != -1)
195 #endif
196                 switch (c) {
197 #ifdef HAVE_GETOPT_LONG
198                 case 0 :
199                         if (longindex == 1)
200                                 help();
201                         break;
202 #endif
203                 case 'b':
204                         ++bflag;
205                         break;
206                 case 'c':
207                         action = FILE_CHECK;
208                         break;
209                 case 'C':
210                         action = FILE_COMPILE;
211                         break;
212                 case 'd':
213                         flags |= MAGIC_DEBUG|MAGIC_CHECK;
214                         break;
215                 case 'f':
216                         if(action)
217                                 usage();
218                         load(magicfile, flags);
219                         unwrap(optarg);
220                         ++didsomefiles;
221                         break;
222                 case 'F':
223                         separator = optarg;
224                         break;
225                 case 'i':
226                         flags |= MAGIC_MIME;
227                         break;
228                 case 'k':
229                         flags |= MAGIC_CONTINUE;
230                         break;
231                 case 'm':
232                         magicfile = optarg;
233                         break;
234                 case 'n':
235                         ++nobuffer;
236                         break;
237                 case 'N':
238                         ++nopad;
239                         break;
240 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
241                 case 'p':
242                         flags |= MAGIC_PRESERVE_ATIME;
243                         break;
244 #endif
245                 case 'r':
246                         flags |= MAGIC_RAW;
247                         break;
248                 case 's':
249                         flags |= MAGIC_DEVICES;
250                         break;
251                 case 'v':
252                         (void) fprintf(stdout, "%s-%d.%.2d\n", progname,
253                                        FILE_VERSION_MAJOR, patchlevel);
254                         (void) fprintf(stdout, "magic file from %s\n",
255                                        magicfile);
256                         return 1;
257                 case 'z':
258                         flags |= MAGIC_COMPRESS;
259                         break;
260 #ifdef S_IFLNK
261                 case 'L':
262                         flags |= MAGIC_SYMLINK;
263                         break;
264 #endif
265                 case '?':
266                 default:
267                         errflg++;
268                         break;
269                 }
270
271         if (errflg) {
272                 usage();
273         }
274
275         switch(action) {
276         case FILE_CHECK:
277         case FILE_COMPILE:
278                 magic = magic_open(flags|MAGIC_CHECK);
279                 if (magic == NULL) {
280                         (void)fprintf(stderr, "%s: %s\n", progname,
281                             strerror(errno));
282                         return 1;
283                 }
284                 c = action == FILE_CHECK ? magic_check(magic, magicfile) :
285                     magic_compile(magic, magicfile);
286                 if (c == -1) {
287                         (void)fprintf(stderr, "%s: %s\n", progname,
288                             magic_error(magic));
289                         return -1;
290                 }
291                 return 0;
292         default:
293                 load(magicfile, flags);
294                 break;
295         }
296
297         if (optind == argc) {
298                 if (!didsomefiles) {
299                         usage();
300                 }
301         }
302         else {
303                 int i, wid, nw;
304                 for (wid = 0, i = optind; i < argc; i++) {
305                         nw = file_mbswidth(argv[i]);
306                         if (nw > wid)
307                                 wid = nw;
308                 }
309                 for (; optind < argc; optind++)
310                         process(argv[optind], wid);
311         }
312
313         magic_close(magic);
314         return 0;
315 }
316
317
318 private void
319 load(const char *m, int flags)
320 {
321         if (magic)
322                 return;
323         magic = magic_open(flags);
324         if (magic == NULL) {
325                 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
326                 exit(1);
327         }
328         if (magic_load(magic, magicfile) == -1) {
329                 (void)fprintf(stderr, "%s: %s\n",
330                     progname, magic_error(magic));
331                 exit(1);
332         }
333 }
334
335 /*
336  * unwrap -- read a file of filenames, do each one.
337  */
338 private void
339 unwrap(char *fn)
340 {
341         char buf[MAXPATHLEN];
342         FILE *f;
343         int wid = 0, cwid;
344
345         if (strcmp("-", fn) == 0) {
346                 f = stdin;
347                 wid = 1;
348         } else {
349                 if ((f = fopen(fn, "r")) == NULL) {
350                         (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
351                             progname, fn, strerror(errno));
352                         exit(1);
353                 }
354
355                 while (fgets(buf, MAXPATHLEN, f) != NULL) {
356                         cwid = file_mbswidth(buf) - 1;
357                         if (cwid > wid)
358                                 wid = cwid;
359                 }
360
361                 rewind(f);
362         }
363
364         while (fgets(buf, MAXPATHLEN, f) != NULL) {
365                 buf[file_mbswidth(buf)-1] = '\0';
366                 process(buf, wid);
367                 if(nobuffer)
368                         (void) fflush(stdout);
369         }
370
371         (void) fclose(f);
372 }
373
374 private void
375 process(const char *inname, int wid)
376 {
377         const char *type;
378         int std_in = strcmp(inname, "-") == 0;
379
380         if (wid > 0 && !bflag)
381                 (void) printf("%s%s%*s ", std_in ? "/dev/stdin" : inname,
382                     separator, (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
383
384         type = magic_file(magic, std_in ? NULL : inname);
385         if (type == NULL)
386                 printf("ERROR: %s\n", magic_error(magic));
387         else
388                 printf("%s\n", type);
389 }
390
391
392 #if 0
393 /*
394  * byteconv4
395  * Input:
396  *      from            4 byte quantity to convert
397  *      same            whether to perform byte swapping
398  *      big_endian      whether we are a big endian host
399  */
400 private int
401 byteconv4(int from, int same, int big_endian)
402 {
403         if (same)
404                 return from;
405         else if (big_endian) {          /* lsb -> msb conversion on msb */
406                 union {
407                         int i;
408                         char c[4];
409                 } retval, tmpval;
410
411                 tmpval.i = from;
412                 retval.c[0] = tmpval.c[3];
413                 retval.c[1] = tmpval.c[2];
414                 retval.c[2] = tmpval.c[1];
415                 retval.c[3] = tmpval.c[0];
416
417                 return retval.i;
418         }
419         else
420                 return ntohl(from);     /* msb -> lsb conversion on lsb */
421 }
422
423 /*
424  * byteconv2
425  * Same as byteconv4, but for shorts
426  */
427 private short
428 byteconv2(int from, int same, int big_endian)
429 {
430         if (same)
431                 return from;
432         else if (big_endian) {          /* lsb -> msb conversion on msb */
433                 union {
434                         short s;
435                         char c[2];
436                 } retval, tmpval;
437
438                 tmpval.s = (short) from;
439                 retval.c[0] = tmpval.c[1];
440                 retval.c[1] = tmpval.c[0];
441
442                 return retval.s;
443         }
444         else
445                 return ntohs(from);     /* msb -> lsb conversion on lsb */
446 }
447 #endif
448
449 size_t
450 file_mbswidth(const char *s)
451 {
452 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
453         size_t bytesconsumed, old_n, n, width = 0;
454         mbstate_t state;
455         wchar_t nextchar;
456         (void)memset(&state, 0, sizeof(mbstate_t));
457         old_n = n = strlen(s);
458
459         while (n > 0) {
460                 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
461                 if (bytesconsumed == (size_t)(-1) ||
462                     bytesconsumed == (size_t)(-2)) {
463                         /* Something went wrong, return something reasonable */
464                         return old_n;
465                 }
466                 if (s[0] == '\n') {
467                         /*
468                          * do what strlen() would do, so that caller
469                          * is always right
470                          */
471                         width++;
472                 } else
473                         width += wcwidth(nextchar);
474
475                 s += bytesconsumed, n -= bytesconsumed;
476         }
477         return width;
478 #else
479         return strlen(s);
480 #endif
481 }
482
483 private void
484 usage(void)
485 {
486         (void)fprintf(stderr, USAGE, progname, progname);
487 #ifdef HAVE_GETOPT_LONG
488         (void)fputs("Try `file --help' for more information.\n", stderr);
489 #endif
490         exit(1);
491 }
492
493 #ifdef HAVE_GETOPT_LONG
494 private void
495 help(void)
496 {
497         puts(
498 "Usage: file [OPTION]... [FILE]...\n"
499 "Determine file type of FILEs.\n"
500 "\n"
501 "  -m, --magic-file LIST      use LIST as a colon-separated list of magic\n"
502 "                               number files\n"
503 "  -z, --uncompress           try to look inside compressed files\n"
504 "  -b, --brief                do not prepend filenames to output lines\n"
505 "  -c, --checking-printout    print the parsed form of the magic file, use in\n"
506 "                               conjunction with -m to debug a new magic file\n"
507 "                               before installing it\n"
508 "  -f, --files-from FILE      read the filenames to be examined from FILE\n"
509 "  -F, --separator string     use string as separator instead of `:'\n"
510 "  -i, --mime                 output mime type strings\n"
511 "  -k, --keep-going           don't stop at the first match\n"
512 "  -L, --dereference          causes symlinks to be followed\n"
513 "  -n, --no-buffer            do not buffer output\n"
514 "  -N, --no-pad               do not pad output\n"
515 "  -p, --preserve-date        preserve access times on files\n"
516 "  -r, --raw                  don't translate unprintable chars to \\ooo\n"
517 "  -s, --special-files        treat special (block/char devices) files as\n"
518 "                             ordinary ones\n"
519 "      --help                 display this help and exit\n"
520 "      --version              output version information and exit\n"
521 );
522         exit(0);
523 }
524 #endif