]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/file/file.c
This commit was generated by cvs2svn to compensate for changes in r98841,
[FreeBSD/FreeBSD.git] / contrib / file / file.c
1 /*
2  * file - find type of a file or files - main program.
3  *
4  * Copyright (c) Ian F. Darwin, 1987.
5  * Written by Ian F. Darwin.
6  *
7  * This software is not subject to any license of the American Telephone
8  * and Telegraph Company or of the Regents of the University of California.
9  *
10  * Permission is granted to anyone to use this software for any purpose on
11  * any computer system, and to alter it and redistribute it freely, subject
12  * to the following restrictions:
13  *
14  * 1. The author is not responsible for the consequences of use of this
15  *    software, no matter how awful, even if they arise from flaws in it.
16  *
17  * 2. The origin of this software must not be misrepresented, either by
18  *    explicit claim or by omission.  Since few users ever read sources,
19  *    credits must appear in the documentation.
20  *
21  * 3. Altered versions must be plainly marked as such, and must not be
22  *    misrepresented as being the original software.  Since few users
23  *    ever read sources, credits must appear in the documentation.
24  *
25  * 4. This notice may not be removed or altered.
26  */
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <sys/param.h>  /* for MAXPATHLEN */
33 #include <sys/stat.h>
34 #include <fcntl.h>      /* for open() */
35 #ifdef RESTORE_TIME
36 # if (__COHERENT__ >= 0x420)
37 #  include <sys/utime.h>
38 # else
39 #  ifdef USE_UTIMES
40 #   include <sys/time.h>
41 #  else
42 #   include <utime.h>
43 #  endif
44 # endif
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>     /* for read() */
48 #endif
49 #ifdef HAVE_LOCALE_H
50 #include <locale.h>
51 #endif
52
53 #include <netinet/in.h>         /* for byte swapping */
54
55 #include "file.h"
56 #include "patchlevel.h"
57
58 #ifndef lint
59 FILE_RCSID("@(#)$Id: file.c,v 1.59 2001/07/23 00:02:32 christos Exp $")
60 #endif  /* lint */
61
62
63 #ifdef S_IFLNK
64 # define USAGE  "Usage: %s [-bciknsvzL] [-f namefile] [-m magicfiles] file...\n"
65 #else
66 # define USAGE  "Usage: %s [-bciknsvz] [-f namefile] [-m magicfiles] file...\n"
67 #endif
68
69 #ifndef MAGIC
70 # define MAGIC "/etc/magic"
71 #endif
72
73 #ifndef MAXPATHLEN
74 #define MAXPATHLEN      512
75 #endif
76
77 int                     /* Global command-line options          */
78         debug = 0,      /* debugging                            */
79         lflag = 0,      /* follow Symlinks (BSD only)           */
80         bflag = 0,      /* brief output format                  */
81         zflag = 0,      /* follow (uncompress) compressed files */
82         sflag = 0,      /* read block special files             */
83         iflag = 0,
84         nobuffer = 0,   /* Do not buffer stdout */
85         kflag = 0;      /* Keep going after the first match     */
86
87 int                     /* Misc globals                         */
88         nmagic = 0;     /* number of valid magic[]s             */
89
90 struct  magic *magic;   /* array of magic entries               */
91
92 const char *magicfile = 0;      /* where the magic is           */
93 const char *default_magicfile = MAGIC;
94
95 char *progname;         /* used throughout                      */
96 int lineno;             /* line number in the magic file        */
97
98
99 static void     unwrap          __P((char *fn));
100 static void     usage           __P((void));
101 #if 0
102 static int      byteconv4       __P((int, int, int));
103 static short    byteconv2       __P((int, int, int));
104 #endif
105
106 int main __P((int, char *[]));
107
108 /*
109  * main - parse arguments and handle options
110  */
111 int
112 main(argc, argv)
113         int argc;
114         char *argv[];
115 {
116         int c;
117         int action = 0, didsomefiles = 0, errflg = 0, ret = 0, app = 0;
118         char *mime, *home, *usermagic;
119         struct stat sb;
120
121 #ifdef LC_CTYPE
122         setlocale(LC_CTYPE, ""); /* makes islower etc work for other langs */
123 #endif
124
125         if ((progname = strrchr(argv[0], '/')) != NULL)
126                 progname++;
127         else
128                 progname = argv[0];
129
130         magicfile = default_magicfile;
131         if ((usermagic = getenv("MAGIC")) != NULL)
132                 magicfile = usermagic;
133         else
134                 if ((home = getenv("HOME")) != NULL) {
135                         if ((usermagic = malloc(strlen(home) + 8)) != NULL) {
136                                 (void)strcpy(usermagic, home);
137                                 (void)strcat(usermagic, "/.magic");
138                                 if (stat(usermagic, &sb)<0) 
139                                         free(usermagic);
140                                 else
141                                         magicfile = usermagic;
142                         }
143                 }
144
145         while ((c = getopt(argc, argv, "bcdf:ikm:nsvzCL")) != EOF)
146                 switch (c) {
147                 case 'b':
148                         ++bflag;
149                         break;
150                 case 'c':
151                         action = CHECK;
152                         break;
153                 case 'C':
154                         action = COMPILE;
155                         break;
156                 case 'd':
157                         ++debug;
158                         break;
159                 case 'f':
160                         if (!app) {
161                                 ret = apprentice(magicfile, action);
162                                 if (action)
163                                         exit(ret);
164                                 app = 1;
165                         }
166                         unwrap(optarg);
167                         ++didsomefiles;
168                         break;
169                 case 'i':
170                         iflag++;
171                         if ((mime = malloc(strlen(magicfile) + 6)) != NULL) {
172                                 (void)strcpy(mime, magicfile);
173                                 (void)strcat(mime, ".mime");
174                                 magicfile = mime;
175                         }
176                         break;
177                 case 'k':
178                         kflag = 1;
179                         break;
180                 case 'm':
181                         magicfile = optarg;
182                         break;
183                 case 'n':
184                         ++nobuffer;
185                         break;
186                 case 's':
187                         sflag++;
188                         break;
189                 case 'v':
190                         (void) fprintf(stdout, "%s-%d.%d\n", progname,
191                                        FILE_VERSION_MAJOR, patchlevel);
192                         (void) fprintf(stdout, "magic file from %s\n",
193                                        magicfile);
194                         return 1;
195                 case 'z':
196                         zflag++;
197                         break;
198 #ifdef S_IFLNK
199                 case 'L':
200                         ++lflag;
201                         break;
202 #endif
203                 case '?':
204                 default:
205                         errflg++;
206                         break;
207                 }
208
209         if (errflg) {
210                 usage();
211         }
212
213         if (!app) {
214                 ret = apprentice(magicfile, action);
215                 if (action)
216                         exit(ret);
217                 app = 1;
218         }
219
220         if (optind == argc) {
221                 if (!didsomefiles) {
222                         usage();
223                 }
224         }
225         else {
226                 int i, wid, nw;
227                 for (wid = 0, i = optind; i < argc; i++) {
228                         nw = strlen(argv[i]);
229                         if (nw > wid)
230                                 wid = nw;
231                 }
232                 for (; optind < argc; optind++)
233                         process(argv[optind], wid);
234         }
235
236         return 0;
237 }
238
239
240 /*
241  * unwrap -- read a file of filenames, do each one.
242  */
243 static void
244 unwrap(fn)
245         char *fn;
246 {
247         char buf[MAXPATHLEN];
248         FILE *f;
249         int wid = 0, cwid;
250
251         if (strcmp("-", fn) == 0) {
252                 f = stdin;
253                 wid = 1;
254         } else {
255                 if ((f = fopen(fn, "r")) == NULL) {
256                         error("Cannot open `%s' (%s).\n", fn, strerror(errno));
257                         /*NOTREACHED*/
258                 }
259
260                 while (fgets(buf, MAXPATHLEN, f) != NULL) {
261                         cwid = strlen(buf) - 1;
262                         if (cwid > wid)
263                                 wid = cwid;
264                 }
265
266                 rewind(f);
267         }
268
269         while (fgets(buf, MAXPATHLEN, f) != NULL) {
270                 buf[strlen(buf)-1] = '\0';
271                 process(buf, wid);
272                 if(nobuffer)
273                         (void) fflush(stdout);
274         }
275
276         (void) fclose(f);
277 }
278
279
280 #if 0
281 /*
282  * byteconv4
283  * Input:
284  *      from            4 byte quantity to convert
285  *      same            whether to perform byte swapping
286  *      big_endian      whether we are a big endian host
287  */
288 static int
289 byteconv4(from, same, big_endian)
290         int from;
291         int same;
292         int big_endian;
293 {
294         if (same)
295                 return from;
296         else if (big_endian) {          /* lsb -> msb conversion on msb */
297                 union {
298                         int i;
299                         char c[4];
300                 } retval, tmpval;
301
302                 tmpval.i = from;
303                 retval.c[0] = tmpval.c[3];
304                 retval.c[1] = tmpval.c[2];
305                 retval.c[2] = tmpval.c[1];
306                 retval.c[3] = tmpval.c[0];
307
308                 return retval.i;
309         }
310         else
311                 return ntohl(from);     /* msb -> lsb conversion on lsb */
312 }
313
314 /*
315  * byteconv2
316  * Same as byteconv4, but for shorts
317  */
318 static short
319 byteconv2(from, same, big_endian)
320         int from;
321         int same;
322         int big_endian;
323 {
324         if (same)
325                 return from;
326         else if (big_endian) {          /* lsb -> msb conversion on msb */
327                 union {
328                         short s;
329                         char c[2];
330                 } retval, tmpval;
331
332                 tmpval.s = (short) from;
333                 retval.c[0] = tmpval.c[1];
334                 retval.c[1] = tmpval.c[0];
335
336                 return retval.s;
337         }
338         else
339                 return ntohs(from);     /* msb -> lsb conversion on lsb */
340 }
341 #endif
342
343 /*
344  * process - process input file
345  */
346 void
347 process(inname, wid)
348         const char      *inname;
349         int wid;
350 {
351         int     fd = 0;
352         static  const char stdname[] = "standard input";
353         unsigned char   buf[HOWMANY+1]; /* one extra for terminating '\0' */
354         struct stat     sb;
355         int nbytes = 0; /* number of bytes read from a datafile */
356         char match = '\0';
357
358         if (strcmp("-", inname) == 0) {
359                 if (fstat(0, &sb)<0) {
360                         error("cannot fstat `%s' (%s).\n", stdname,
361                               strerror(errno));
362                         /*NOTREACHED*/
363                 }
364                 inname = stdname;
365         }
366
367         if (wid > 0 && !bflag)
368              (void) printf("%s:%*s ", inname, 
369                            (int) (wid - strlen(inname)), "");
370
371         if (inname != stdname) {
372                 /*
373                  * first try judging the file based on its filesystem status
374                  */
375                 if (fsmagic(inname, &sb) != 0) {
376                         putchar('\n');
377                         return;
378                 }
379
380                 if ((fd = open(inname, O_RDONLY)) < 0) {
381                         /* We can't open it, but we were able to stat it. */
382                         if (sb.st_mode & 0002) ckfputs("writeable, ", stdout);
383                         if (sb.st_mode & 0111) ckfputs("executable, ", stdout);
384                         ckfprintf(stdout, "can't read `%s' (%s).\n",
385                             inname, strerror(errno));
386                         return;
387                 }
388         }
389
390
391         /*
392          * try looking at the first HOWMANY bytes
393          */
394         if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) {
395                 error("read failed (%s).\n", strerror(errno));
396                 /*NOTREACHED*/
397         }
398
399         if (nbytes == 0)
400                 ckfputs(iflag ? "application/x-empty" : "empty", stdout);
401         else {
402                 buf[nbytes++] = '\0';   /* null-terminate it */
403                 match = tryit(buf, nbytes, zflag);
404         }
405
406 #ifdef BUILTIN_ELF
407         if (match == 's' && nbytes > 5) {
408                 /*
409                  * We matched something in the file, so this *might*
410                  * be an ELF file, and the file is at least 5 bytes long,
411                  * so if it's an ELF file it has at least one byte
412                  * past the ELF magic number - try extracting information
413                  * from the ELF headers that can't easily be extracted
414                  * with rules in the magic file.
415                  */
416                 tryelf(fd, buf, nbytes);
417         }
418 #endif
419
420         if (inname != stdname) {
421 #ifdef RESTORE_TIME
422                 /*
423                  * Try to restore access, modification times if read it.
424                  * This is really *bad* because it will modify the status
425                  * time of the file... And of course this will affect
426                  * backup programs
427                  */
428 # ifdef USE_UTIMES
429                 struct timeval  utsbuf[2];
430                 utsbuf[0].tv_sec = sb.st_atime;
431                 utsbuf[1].tv_sec = sb.st_mtime;
432
433                 (void) utimes(inname, utsbuf); /* don't care if loses */
434 # else
435                 struct utimbuf  utbuf;
436
437                 utbuf.actime = sb.st_atime;
438                 utbuf.modtime = sb.st_mtime;
439                 (void) utime(inname, &utbuf); /* don't care if loses */
440 # endif
441 #endif
442                 (void) close(fd);
443         }
444         (void) putchar('\n');
445 }
446
447
448 int
449 tryit(buf, nb, zflag)
450         unsigned char *buf;
451         int nb, zflag;
452 {
453         /* try compression stuff */
454         if (zflag && zmagic(buf, nb))
455                 return 'z';
456
457         /* try tests in /etc/magic (or surrogate magic file) */
458         if (softmagic(buf, nb))
459                 return 's';
460
461         /* try known keywords, check whether it is ASCII */
462         if (ascmagic(buf, nb))
463                 return 'a';
464
465         /* abandon hope, all ye who remain here */
466         ckfputs("data", stdout);
467                 return '\0';
468 }
469
470 static void
471 usage()
472 {
473         (void)fprintf(stderr, USAGE, progname);
474         (void)fprintf(stderr, "Usage: %s -C [-m magic]\n", progname);
475         exit(1);
476 }