Import file-5.06.
[dragonfly.git] / contrib / file / 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
34 #ifndef lint
35 FILE_RCSID("@(#)$File: file.c,v 1.143 2011/03/20 20:36:52 christos Exp $")
36 #endif  /* lint */
37
38 #include "magic.h"
39
40 #include <stdlib.h>
41 #include <unistd.h>
42 #include <string.h>
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 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
65 #include <getopt.h>
66 #ifndef HAVE_GETOPT_LONG
67 int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
68 #endif
69 #else
70 #include "mygetopt.h"
71 #endif
72
73 #include "patchlevel.h"
74
75 #ifdef S_IFLNK
76 #define FILE_FLAGS "-bchikLlNnprsvz0"
77 #else
78 #define FILE_FLAGS "-bciklNnprsvz0"
79 #endif
80
81 # define USAGE  \
82     "Usage: %s [" FILE_FLAGS \
83         "] [--apple] [--mime-encoding] [--mime-type]\n" \
84     "            [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
85     "file ...\n" \
86     "       %s -C [-m magicfiles]\n" \
87     "       %s [--help]\n"
88
89 private int             /* Global command-line options          */
90         bflag = 0,      /* brief output format                  */
91         nopad = 0,      /* Don't pad output                     */
92         nobuffer = 0,   /* Do not buffer stdout                 */
93         nulsep = 0;     /* Append '\0' to the separator         */
94
95 private const char *separator = ":";    /* Default field separator      */
96 private const struct option long_options[] = {
97 #define OPT(shortname, longname, opt, doc)      \
98     {longname, opt, NULL, shortname},
99 #define OPT_LONGONLY(longname, opt, doc)        \
100     {longname, opt, NULL, 0},
101 #include "file_opts.h"
102 #undef OPT
103 #undef OPT_LONGONLY
104     {0, 0, NULL, 0}
105 };
106 #define OPTSTRING       "bcCde:f:F:hiklLm:nNprsvz0"
107
108 private const struct {
109         const char *name;
110         int value;
111 } nv[] = {
112         { "apptype",    MAGIC_NO_CHECK_APPTYPE },
113         { "ascii",      MAGIC_NO_CHECK_ASCII },
114         { "cdf",        MAGIC_NO_CHECK_CDF },
115         { "compress",   MAGIC_NO_CHECK_COMPRESS },
116         { "elf",        MAGIC_NO_CHECK_ELF },
117         { "encoding",   MAGIC_NO_CHECK_ENCODING },
118         { "soft",       MAGIC_NO_CHECK_SOFT },
119         { "tar",        MAGIC_NO_CHECK_TAR },
120         { "text",       MAGIC_NO_CHECK_TEXT },  /* synonym for ascii */
121         { "tokens",     MAGIC_NO_CHECK_TOKENS },
122 };
123
124 private char *progname;         /* used throughout              */
125
126 private void usage(void);
127 private void help(void);
128 int main(int, char *[]);
129
130 private int unwrap(struct magic_set *, const char *);
131 private int process(struct magic_set *ms, const char *, int);
132 private struct magic_set *load(const char *, int);
133
134
135 /*
136  * main - parse arguments and handle options
137  */
138 int
139 main(int argc, char *argv[])
140 {
141         int c;
142         size_t i;
143         int action = 0, didsomefiles = 0, errflg = 0;
144         int flags = 0, e = 0;
145         struct magic_set *magic = NULL;
146         int longindex;
147         const char *magicfile = NULL;           /* where the magic is   */
148
149         /* makes islower etc work for other langs */
150         (void)setlocale(LC_CTYPE, "");
151
152 #ifdef __EMX__
153         /* sh-like wildcard expansion! Shouldn't hurt at least ... */
154         _wildcard(&argc, &argv);
155 #endif
156
157         if ((progname = strrchr(argv[0], '/')) != NULL)
158                 progname++;
159         else
160                 progname = argv[0];
161
162 #ifdef S_IFLNK
163         flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
164 #endif
165         while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
166             &longindex)) != -1)
167                 switch (c) {
168                 case 0 :
169                         switch (longindex) {
170                         case 0:
171                                 help();
172                                 break;
173                         case 10:
174                                 flags |= MAGIC_APPLE;
175                                 break;
176                         case 11:
177                                 flags |= MAGIC_MIME_TYPE;
178                                 break;
179                         case 12:
180                                 flags |= MAGIC_MIME_ENCODING;
181                                 break;
182                         }
183                         break;
184                 case '0':
185                         nulsep = 1;
186                         break;
187                 case 'b':
188                         bflag++;
189                         break;
190                 case 'c':
191                         action = FILE_CHECK;
192                         break;
193                 case 'C':
194                         action = FILE_COMPILE;
195                         break;
196                 case 'd':
197                         flags |= MAGIC_DEBUG|MAGIC_CHECK;
198                         break;
199                 case 'e':
200                         for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
201                                 if (strcmp(nv[i].name, optarg) == 0)
202                                         break;
203
204                         if (i == sizeof(nv) / sizeof(nv[0]))
205                                 errflg++;
206                         else
207                                 flags |= nv[i].value;
208                         break;
209
210                 case 'f':
211                         if(action)
212                                 usage();
213                         if (magic == NULL)
214                                 if ((magic = load(magicfile, flags)) == NULL)
215                                         return 1;
216                         e |= unwrap(magic, optarg);
217                         ++didsomefiles;
218                         break;
219                 case 'F':
220                         separator = optarg;
221                         break;
222                 case 'i':
223                         flags |= MAGIC_MIME;
224                         break;
225                 case 'k':
226                         flags |= MAGIC_CONTINUE;
227                         break;
228                 case 'l':
229                         action = FILE_LIST;
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                         if (magicfile == NULL)
253                                 magicfile = magic_getpath(magicfile, action);
254                         (void)fprintf(stdout, "%s-%d.%.2d\n", progname,
255                                        FILE_VERSION_MAJOR, patchlevel);
256                         (void)fprintf(stdout, "magic file from %s\n",
257                                        magicfile);
258                         return 1;
259                 case 'z':
260                         flags |= MAGIC_COMPRESS;
261                         break;
262 #ifdef S_IFLNK
263                 case 'L':
264                         flags |= MAGIC_SYMLINK;
265                         break;
266                 case 'h':
267                         flags &= ~MAGIC_SYMLINK;
268                         break;
269 #endif
270                 case '?':
271                 default:
272                         errflg++;
273                         break;
274                 }
275
276         if (errflg) {
277                 usage();
278         }
279         if (e)
280                 return e;
281
282         switch(action) {
283         case FILE_CHECK:
284         case FILE_COMPILE:
285         case FILE_LIST:
286                 /*
287                  * Don't try to check/compile ~/.magic unless we explicitly
288                  * ask for it.
289                  */
290                 magic = magic_open(flags|MAGIC_CHECK);
291                 if (magic == NULL) {
292                         (void)fprintf(stderr, "%s: %s\n", progname,
293                             strerror(errno));
294                         return 1;
295                 }
296                 switch(action) {
297                 case FILE_CHECK:
298                         c = magic_check(magic, magicfile);
299                         break;
300                 case FILE_COMPILE:
301                         c = magic_compile(magic, magicfile);
302                         break;
303                 case FILE_LIST:
304                         c = magic_list(magic, magicfile);
305                         break;
306                 default:
307                         abort();
308                 }
309                 if (c == -1) {
310                         (void)fprintf(stderr, "%s: %s\n", progname,
311                             magic_error(magic));
312                         return 1;
313                 }
314                 return 0;
315         default:
316                 if (magic == NULL)
317                         if ((magic = load(magicfile, flags)) == NULL)
318                                 return 1;
319                 break;
320         }
321
322         if (optind == argc) {
323                 if (!didsomefiles)
324                         usage();
325         }
326         else {
327                 size_t j, wid, nw;
328                 for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
329                         nw = file_mbswidth(argv[j]);
330                         if (nw > wid)
331                                 wid = nw;
332                 }
333                 /*
334                  * If bflag is only set twice, set it depending on
335                  * number of files [this is undocumented, and subject to change]
336                  */
337                 if (bflag == 2) {
338                         bflag = optind >= argc - 1;
339                 }
340                 for (; optind < argc; optind++)
341                         e |= process(magic, argv[optind], wid);
342         }
343
344         if (magic)
345                 magic_close(magic);
346         return e;
347 }
348
349
350 private struct magic_set *
351 /*ARGSUSED*/
352 load(const char *magicfile, int flags)
353 {
354         struct magic_set *magic = magic_open(flags);
355         if (magic == NULL) {
356                 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
357                 return NULL;
358         }
359         if (magic_load(magic, magicfile) == -1) {
360                 (void)fprintf(stderr, "%s: %s\n",
361                     progname, magic_error(magic));
362                 magic_close(magic);
363                 return NULL;
364         }
365         return magic;
366 }
367
368 /*
369  * unwrap -- read a file of filenames, do each one.
370  */
371 private int
372 unwrap(struct magic_set *ms, const char *fn)
373 {
374         FILE *f;
375         ssize_t len;
376         char *line = NULL;
377         size_t llen = 0;
378         int wid = 0, cwid;
379         int e = 0;
380
381         if (strcmp("-", fn) == 0) {
382                 f = stdin;
383                 wid = 1;
384         } else {
385                 if ((f = fopen(fn, "r")) == NULL) {
386                         (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
387                             progname, fn, strerror(errno));
388                         return 1;
389                 }
390
391                 while ((len = getline(&line, &llen, f)) > 0) {
392                         if (line[len - 1] == '\n')
393                                 line[len - 1] = '\0';
394                         cwid = file_mbswidth(line);
395                         if (cwid > wid)
396                                 wid = cwid;
397                 }
398
399                 rewind(f);
400         }
401
402         while ((len = getline(&line, &llen, f)) > 0) {
403                 if (line[len - 1] == '\n')
404                         line[len - 1] = '\0';
405                 e |= process(ms, line, wid);
406                 if(nobuffer)
407                         (void)fflush(stdout);
408         }
409
410         free(line);
411         (void)fclose(f);
412         return e;
413 }
414
415 /*
416  * Called for each input file on the command line (or in a list of files)
417  */
418 private int
419 process(struct magic_set *ms, const char *inname, int wid)
420 {
421         const char *type;
422         int std_in = strcmp(inname, "-") == 0;
423
424         if (wid > 0 && !bflag) {
425                 (void)printf("%s", std_in ? "/dev/stdin" : inname);
426                 if (nulsep)
427                         (void)putc('\0', stdout);
428                 (void)printf("%s", separator);
429                 (void)printf("%*s ",
430                     (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
431         }
432
433         type = magic_file(ms, std_in ? NULL : inname);
434         if (type == NULL) {
435                 (void)printf("ERROR: %s\n", magic_error(ms));
436                 return 1;
437         } else {
438                 (void)printf("%s\n", type);
439                 return 0;
440         }
441 }
442
443 size_t
444 file_mbswidth(const char *s)
445 {
446 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
447         size_t bytesconsumed, old_n, n, width = 0;
448         mbstate_t state;
449         wchar_t nextchar;
450         (void)memset(&state, 0, sizeof(mbstate_t));
451         old_n = n = strlen(s);
452
453         while (n > 0) {
454                 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
455                 if (bytesconsumed == (size_t)(-1) ||
456                     bytesconsumed == (size_t)(-2)) {
457                         /* Something went wrong, return something reasonable */
458                         return old_n;
459                 }
460                 if (s[0] == '\n') {
461                         /*
462                          * do what strlen() would do, so that caller
463                          * is always right
464                          */
465                         width++;
466                 } else
467                         width += wcwidth(nextchar);
468
469                 s += bytesconsumed, n -= bytesconsumed;
470         }
471         return width;
472 #else
473         return strlen(s);
474 #endif
475 }
476
477 private void
478 usage(void)
479 {
480         (void)fprintf(stderr, USAGE, progname, progname, progname);
481         exit(1);
482 }
483
484 private void
485 help(void)
486 {
487         (void)fputs(
488 "Usage: file [OPTION...] [FILE...]\n"
489 "Determine type of FILEs.\n"
490 "\n", stdout);
491 #define OPT(shortname, longname, opt, doc)      \
492         fprintf(stdout, "  -%c, --" longname doc, shortname);
493 #define OPT_LONGONLY(longname, opt, doc)        \
494         fprintf(stdout, "      --" longname doc);
495 #include "file_opts.h"
496 #undef OPT
497 #undef OPT_LONGONLY
498         fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
499         exit(0);
500 }