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