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