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