1 /* $NetBSD: file.c,v 1.4 2014/06/13 02:08:06 christos Exp $ */ 2 /* 3 * Copyright (c) Ian F. Darwin 1986-1995. 4 * Software written by Ian F. Darwin and others; 5 * maintained 1995-present by Christos Zoulas and others. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice immediately at the beginning of the file, without modification, 12 * this list of conditions, and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR 21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 /* 30 * file - find type of a file or files - main program. 31 */ 32 33 #include "file.h" 34 35 #ifndef lint 36 #if 0 37 FILE_RCSID("@(#)$File: file.c,v 1.153 2014/02/11 15:41:04 christos Exp $") 38 #else 39 __RCSID("$NetBSD: file.c,v 1.4 2014/06/13 02:08:06 christos Exp $"); 40 #endif 41 #endif /* lint */ 42 43 #include "magic.h" 44 45 #include <stdlib.h> 46 #include <unistd.h> 47 #include <string.h> 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 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION) 70 #include <getopt.h> 71 #ifndef HAVE_GETOPT_LONG 72 int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex); 73 #endif 74 #else 75 #include "mygetopt.h" 76 #endif 77 78 #ifdef S_IFLNK 79 #define FILE_FLAGS "-bcEhikLlNnprsvz0" 80 #else 81 #define FILE_FLAGS "-bcEiklNnprsvz0" 82 #endif 83 84 # define USAGE \ 85 "Usage: %s [" FILE_FLAGS \ 86 "] [--apple] [--mime-encoding] [--mime-type]\n" \ 87 " [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \ 88 "file ...\n" \ 89 " %s -C [-m magicfiles]\n" \ 90 " %s [--help]\n" 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:Ef:F:hiklLm: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 { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */ 124 { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */ 125 }; 126 127 private char *progname; /* used throughout */ 128 129 #ifdef __dead 130 __dead 131 #endif 132 private void usage(void); 133 private void docprint(const char *); 134 #ifdef __dead 135 __dead 136 #endif 137 private void help(void); 138 139 private int unwrap(struct magic_set *, const char *); 140 private int process(struct magic_set *ms, const char *, int); 141 private struct magic_set *load(const char *, int); 142 143 144 /* 145 * main - parse arguments and handle options 146 */ 147 int 148 main(int argc, char *argv[]) 149 { 150 int c; 151 size_t i; 152 int action = 0, didsomefiles = 0, errflg = 0; 153 int flags = 0, e = 0; 154 struct magic_set *magic = NULL; 155 int longindex; 156 const char *magicfile = NULL; /* where the magic is */ 157 158 /* makes islower etc work for other langs */ 159 (void)setlocale(LC_CTYPE, ""); 160 161 #ifdef __EMX__ 162 /* sh-like wildcard expansion! Shouldn't hurt at least ... */ 163 _wildcard(&argc, &argv); 164 #endif 165 166 if ((progname = strrchr(argv[0], '/')) != NULL) 167 progname++; 168 else 169 progname = argv[0]; 170 171 #ifdef S_IFLNK 172 flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0; 173 #endif 174 while ((c = getopt_long(argc, argv, OPTSTRING, long_options, 175 &longindex)) != -1) 176 switch (c) { 177 case 0 : 178 switch (longindex) { 179 case 0: 180 help(); 181 break; 182 case 10: 183 flags |= MAGIC_APPLE; 184 break; 185 case 11: 186 flags |= MAGIC_MIME_TYPE; 187 break; 188 case 12: 189 flags |= MAGIC_MIME_ENCODING; 190 break; 191 } 192 break; 193 case '0': 194 nulsep = 1; 195 break; 196 case 'b': 197 bflag++; 198 break; 199 case 'c': 200 action = FILE_CHECK; 201 break; 202 case 'C': 203 action = FILE_COMPILE; 204 break; 205 case 'd': 206 flags |= MAGIC_DEBUG|MAGIC_CHECK; 207 break; 208 case 'E': 209 flags |= MAGIC_ERROR; 210 break; 211 case 'e': 212 for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) 213 if (strcmp(nv[i].name, optarg) == 0) 214 break; 215 216 if (i == sizeof(nv) / sizeof(nv[0])) 217 errflg++; 218 else 219 flags |= nv[i].value; 220 break; 221 222 case 'f': 223 if(action) 224 usage(); 225 if (magic == NULL) 226 if ((magic = load(magicfile, flags)) == NULL) 227 return 1; 228 e |= unwrap(magic, optarg); 229 ++didsomefiles; 230 break; 231 case 'F': 232 separator = optarg; 233 break; 234 case 'i': 235 flags |= MAGIC_MIME; 236 break; 237 case 'k': 238 flags |= MAGIC_CONTINUE; 239 break; 240 case 'l': 241 action = FILE_LIST; 242 break; 243 case 'm': 244 magicfile = optarg; 245 break; 246 case 'n': 247 ++nobuffer; 248 break; 249 case 'N': 250 ++nopad; 251 break; 252 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES) 253 case 'p': 254 flags |= MAGIC_PRESERVE_ATIME; 255 break; 256 #endif 257 case 'r': 258 flags |= MAGIC_RAW; 259 break; 260 case 's': 261 flags |= MAGIC_DEVICES; 262 break; 263 case 'v': 264 if (magicfile == NULL) 265 magicfile = magic_getpath(magicfile, action); 266 (void)fprintf(stdout, "%s-%s\n", progname, VERSION); 267 (void)fprintf(stdout, "magic file from %s\n", 268 magicfile); 269 return 0; 270 case 'z': 271 flags |= MAGIC_COMPRESS; 272 break; 273 #ifdef S_IFLNK 274 case 'L': 275 flags |= MAGIC_SYMLINK; 276 break; 277 case 'h': 278 flags &= ~MAGIC_SYMLINK; 279 break; 280 #endif 281 case '?': 282 default: 283 errflg++; 284 break; 285 } 286 287 if (errflg) { 288 usage(); 289 } 290 if (e) 291 return e; 292 293 if (MAGIC_VERSION != magic_version()) 294 (void)fprintf(stderr, "%s: compiled magic version [%d] " 295 "does not match with shared library magic version [%d]\n", 296 progname, MAGIC_VERSION, magic_version()); 297 298 switch(action) { 299 case FILE_CHECK: 300 case FILE_COMPILE: 301 case FILE_LIST: 302 /* 303 * Don't try to check/compile ~/.magic unless we explicitly 304 * ask for it. 305 */ 306 magic = magic_open(flags|MAGIC_CHECK); 307 if (magic == NULL) { 308 (void)fprintf(stderr, "%s: %s\n", progname, 309 strerror(errno)); 310 return 1; 311 } 312 switch(action) { 313 case FILE_CHECK: 314 c = magic_check(magic, magicfile); 315 break; 316 case FILE_COMPILE: 317 c = magic_compile(magic, magicfile); 318 break; 319 case FILE_LIST: 320 c = magic_list(magic, magicfile); 321 break; 322 default: 323 abort(); 324 } 325 if (c == -1) { 326 (void)fprintf(stderr, "%s: %s\n", progname, 327 magic_error(magic)); 328 return 1; 329 } 330 return 0; 331 default: 332 if (magic == NULL) 333 if ((magic = load(magicfile, flags)) == NULL) 334 return 1; 335 break; 336 } 337 338 if (optind == argc) { 339 if (!didsomefiles) 340 usage(); 341 } 342 else { 343 size_t j, wid, nw; 344 for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) { 345 nw = file_mbswidth(argv[j]); 346 if (nw > wid) 347 wid = nw; 348 } 349 /* 350 * If bflag is only set twice, set it depending on 351 * number of files [this is undocumented, and subject to change] 352 */ 353 if (bflag == 2) { 354 bflag = optind >= argc - 1; 355 } 356 for (; optind < argc; optind++) 357 e |= process(magic, argv[optind], wid); 358 } 359 360 if (magic) 361 magic_close(magic); 362 return e; 363 } 364 365 366 private struct magic_set * 367 /*ARGSUSED*/ 368 load(const char *magicfile, int flags) 369 { 370 struct magic_set *magic = magic_open(flags); 371 if (magic == NULL) { 372 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno)); 373 return NULL; 374 } 375 if (magic_load(magic, magicfile) == -1) { 376 (void)fprintf(stderr, "%s: %s\n", 377 progname, magic_error(magic)); 378 magic_close(magic); 379 return NULL; 380 } 381 return magic; 382 } 383 384 /* 385 * unwrap -- read a file of filenames, do each one. 386 */ 387 private int 388 unwrap(struct magic_set *ms, const char *fn) 389 { 390 FILE *f; 391 ssize_t len; 392 char *line = NULL; 393 size_t llen = 0; 394 int wid = 0, cwid; 395 int e = 0; 396 397 if (strcmp("-", fn) == 0) { 398 f = stdin; 399 wid = 1; 400 } else { 401 if ((f = fopen(fn, "r")) == NULL) { 402 (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n", 403 progname, fn, strerror(errno)); 404 return 1; 405 } 406 407 while ((len = getline(&line, &llen, f)) > 0) { 408 if (line[len - 1] == '\n') 409 line[len - 1] = '\0'; 410 cwid = file_mbswidth(line); 411 if (cwid > wid) 412 wid = cwid; 413 } 414 415 rewind(f); 416 } 417 418 while ((len = getline(&line, &llen, f)) > 0) { 419 if (line[len - 1] == '\n') 420 line[len - 1] = '\0'; 421 e |= process(ms, line, wid); 422 if(nobuffer) 423 (void)fflush(stdout); 424 } 425 426 free(line); 427 (void)fclose(f); 428 return e; 429 } 430 431 /* 432 * Called for each input file on the command line (or in a list of files) 433 */ 434 private int 435 process(struct magic_set *ms, const char *inname, int wid) 436 { 437 const char *type; 438 int std_in = strcmp(inname, "-") == 0; 439 440 if (wid > 0 && !bflag) { 441 (void)printf("%s", std_in ? "/dev/stdin" : inname); 442 if (nulsep) 443 (void)putc('\0', stdout); 444 (void)printf("%s", separator); 445 (void)printf("%*s ", 446 (int) (nopad ? 0 : (wid - file_mbswidth(inname))), ""); 447 } 448 449 type = magic_file(ms, std_in ? NULL : inname); 450 if (type == NULL) { 451 (void)printf("ERROR: %s\n", magic_error(ms)); 452 return 1; 453 } else { 454 (void)printf("%s\n", type); 455 return 0; 456 } 457 } 458 459 protected size_t 460 file_mbswidth(const char *s) 461 { 462 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) 463 size_t bytesconsumed, old_n, n, width = 0; 464 mbstate_t state; 465 wchar_t nextchar; 466 (void)memset(&state, 0, sizeof(mbstate_t)); 467 old_n = n = strlen(s); 468 469 while (n > 0) { 470 bytesconsumed = mbrtowc(&nextchar, s, n, &state); 471 if (bytesconsumed == (size_t)(-1) || 472 bytesconsumed == (size_t)(-2)) { 473 /* Something went wrong, return something reasonable */ 474 return old_n; 475 } 476 if (s[0] == '\n') { 477 /* 478 * do what strlen() would do, so that caller 479 * is always right 480 */ 481 width++; 482 } else { 483 int w = wcwidth(nextchar); 484 if (w > 0) 485 width += w; 486 } 487 488 s += bytesconsumed, n -= bytesconsumed; 489 } 490 return width; 491 #else 492 return strlen(s); 493 #endif 494 } 495 496 private void 497 usage(void) 498 { 499 (void)fprintf(stderr, USAGE, progname, progname, progname); 500 exit(1); 501 } 502 503 private void 504 docprint(const char *opts) 505 { 506 size_t i; 507 int comma; 508 char *sp, *p; 509 510 p = strstr(opts, "%o"); 511 if (p == NULL) { 512 fprintf(stdout, "%s", opts); 513 return; 514 } 515 516 for (sp = p - 1; sp > opts && *sp == ' '; sp--) 517 continue; 518 519 fprintf(stdout, "%.*s", (int)(p - opts), opts); 520 521 comma = 0; 522 for (i = 0; i < __arraycount(nv); i++) { 523 fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name); 524 if (i && i % 5 == 0) { 525 fprintf(stdout, ",\n%*s", (int)(p - sp - 1), ""); 526 comma = 0; 527 } 528 } 529 530 fprintf(stdout, "%s", opts + (p - opts) + 2); 531 } 532 533 private void 534 help(void) 535 { 536 (void)fputs( 537 "Usage: file [OPTION...] [FILE...]\n" 538 "Determine type of FILEs.\n" 539 "\n", stdout); 540 #define OPT(shortname, longname, opt, doc) \ 541 fprintf(stdout, " -%c, --" longname, shortname), \ 542 docprint(doc); 543 #define OPT_LONGONLY(longname, opt, doc) \ 544 fprintf(stdout, " --" longname), \ 545 docprint(doc); 546 #include "file_opts.h" 547 #undef OPT 548 #undef OPT_LONGONLY 549 fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n"); 550 exit(0); 551 } 552