file.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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. #include "file.h"
  32. #ifndef lint
  33. FILE_RCSID("@(#)$File: file.c,v 1.217 2024/09/29 16:49:25 christos Exp $")
  34. #endif /* lint */
  35. #include "magic.h"
  36. #include <stdlib.h>
  37. #include <unistd.h>
  38. #include <string.h>
  39. #ifdef RESTORE_TIME
  40. # if (__COHERENT__ >= 0x420)
  41. # include <sys/utime.h>
  42. # else
  43. # ifdef USE_UTIMES
  44. # include <sys/time.h>
  45. # else
  46. # include <utime.h>
  47. # endif
  48. # endif
  49. #endif
  50. #ifdef HAVE_UNISTD_H
  51. #include <unistd.h> /* for read() */
  52. #endif
  53. #ifdef HAVE_WCHAR_H
  54. #include <wchar.h>
  55. #endif
  56. #ifdef HAVE_WCTYPE_H
  57. #include <wctype.h>
  58. #endif
  59. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) && \
  60. defined(HAVE_WCTYPE_H)
  61. #define FILE_WIDE_SUPPORT
  62. #else
  63. #include <ctype.h>
  64. #endif
  65. #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
  66. # include <getopt.h>
  67. # ifndef HAVE_GETOPT_LONG
  68. int getopt_long(int, char * const *, const char *,
  69. const struct option *, int *);
  70. # endif
  71. # else
  72. # include "mygetopt.h"
  73. #endif
  74. #ifdef S_IFLNK
  75. # define IFLNK_h "h"
  76. # define IFLNK_L "L"
  77. #else
  78. # define IFLNK_h ""
  79. # define IFLNK_L ""
  80. #endif
  81. #define FILE_FLAGS "bcCdE" IFLNK_h "ik" IFLNK_L "lNnprsSvzZ0"
  82. #define OPTSTRING "bcCde:Ef:F:hiklLm:nNpP:rsSvzZ0"
  83. # define USAGE \
  84. "Usage: %s [-" FILE_FLAGS "] [--apple] [--extension] [--mime-encoding]\n" \
  85. " [--mime-type] [-e <testname>] [-F <separator>] " \
  86. " [-f <namefile>]\n" \
  87. " [-m <magicfiles>] [-P <parameter=value>] [--exclude-quiet]\n" \
  88. " <file> ...\n" \
  89. " %s -C [-m <magicfiles>]\n" \
  90. " %s [--help]\n"
  91. file_private int /* Global command-line options */
  92. bflag = 0, /* brief output format */
  93. nopad = 0, /* Don't pad output */
  94. nobuffer = 0, /* Do not buffer stdout */
  95. nulsep = 0; /* Append '\0' to the separator */
  96. file_private const char *separator = ":"; /* Default field separator */
  97. file_private const struct option long_options[] = {
  98. #define OPT_HELP 1
  99. #define OPT_APPLE 2
  100. #define OPT_EXTENSIONS 3
  101. #define OPT_MIME_TYPE 4
  102. #define OPT_MIME_ENCODING 5
  103. #define OPT_EXCLUDE_QUIET 6
  104. #define OPT(shortname, longname, opt, def, doc) \
  105. {longname, opt, NULL, shortname},
  106. #define OPT_LONGONLY(longname, opt, def, doc, id) \
  107. {longname, opt, NULL, id},
  108. #include "file_opts.h"
  109. #undef OPT
  110. #undef OPT_LONGONLY
  111. {0, 0, NULL, 0}
  112. };
  113. file_private const struct {
  114. const char *name;
  115. int value;
  116. } nv[] = {
  117. { "apptype", MAGIC_NO_CHECK_APPTYPE },
  118. { "ascii", MAGIC_NO_CHECK_ASCII },
  119. { "cdf", MAGIC_NO_CHECK_CDF },
  120. { "compress", MAGIC_NO_CHECK_COMPRESS },
  121. { "csv", MAGIC_NO_CHECK_CSV },
  122. { "elf", MAGIC_NO_CHECK_ELF },
  123. { "encoding", MAGIC_NO_CHECK_ENCODING },
  124. { "soft", MAGIC_NO_CHECK_SOFT },
  125. { "tar", MAGIC_NO_CHECK_TAR },
  126. { "json", MAGIC_NO_CHECK_JSON },
  127. { "simh", MAGIC_NO_CHECK_SIMH },
  128. { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */
  129. { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
  130. };
  131. file_private struct {
  132. const char *name;
  133. size_t value;
  134. size_t def;
  135. const char *desc;
  136. int tag;
  137. int set;
  138. } pm[] = {
  139. { "bytes", 0, FILE_BYTES_MAX, "max bytes to look inside file",
  140. MAGIC_PARAM_BYTES_MAX, 0 },
  141. { "elf_notes", 0, FILE_ELF_NOTES_MAX, "max ELF notes processed",
  142. MAGIC_PARAM_ELF_NOTES_MAX, 0 },
  143. { "elf_phnum", 0, FILE_ELF_PHNUM_MAX, "max ELF prog sections processed",
  144. MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
  145. { "elf_shnum", 0, FILE_ELF_SHNUM_MAX, "max ELF sections processed",
  146. MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
  147. { "elf_shsize", 0, FILE_ELF_SHSIZE_MAX, "max ELF section size",
  148. MAGIC_PARAM_ELF_SHSIZE_MAX, 0 },
  149. { "encoding", 0, FILE_ENCODING_MAX, "max bytes to scan for encoding",
  150. MAGIC_PARAM_ENCODING_MAX, 0 },
  151. { "indir", 0, FILE_INDIR_MAX, "recursion limit for indirection",
  152. MAGIC_PARAM_INDIR_MAX, 0 },
  153. { "name", 0, FILE_NAME_MAX, "use limit for name/use magic",
  154. MAGIC_PARAM_NAME_MAX, 0 },
  155. { "regex", 0, FILE_REGEX_MAX, "length limit for REGEX searches",
  156. MAGIC_PARAM_REGEX_MAX, 0 },
  157. { "magwarn", 0, FILE_MAGWARN_MAX, "maximum number of magic warnings",
  158. MAGIC_PARAM_MAGWARN_MAX, 0 },
  159. };
  160. file_private int posixly;
  161. #ifdef __dead
  162. __dead
  163. #endif
  164. file_private void usage(void);
  165. file_private void docprint(const char *, int);
  166. #ifdef __dead
  167. __dead
  168. #endif
  169. file_private void help(void);
  170. file_private int unwrap(struct magic_set *, const char *);
  171. file_private int process(struct magic_set *ms, const char *, int);
  172. file_private struct magic_set *load(const char *, int);
  173. file_private void setparam(const char *);
  174. file_private void applyparam(magic_t);
  175. /*
  176. * main - parse arguments and handle options
  177. */
  178. int
  179. main(int argc, char *argv[])
  180. {
  181. int c;
  182. size_t i, j, wid, nw;
  183. int action = 0, didsomefiles = 0, errflg = 0;
  184. int flags = 0, e = 0;
  185. #ifdef HAVE_LIBSECCOMP
  186. int sandbox = 1;
  187. #endif
  188. struct magic_set *magic = NULL;
  189. int longindex;
  190. const char *magicfile = NULL; /* where the magic is */
  191. char *progname;
  192. /* makes islower etc work for other langs */
  193. (void)setlocale(LC_CTYPE, "");
  194. #ifdef __EMX__
  195. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  196. _wildcard(&argc, &argv);
  197. #endif
  198. if ((progname = strrchr(argv[0], '/')) != NULL)
  199. progname++;
  200. else
  201. progname = argv[0];
  202. file_setprogname(progname);
  203. #ifdef S_IFLNK
  204. posixly = getenv("POSIXLY_CORRECT") != NULL;
  205. flags |= posixly ? MAGIC_SYMLINK : 0;
  206. #endif
  207. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  208. &longindex)) != -1)
  209. switch (c) {
  210. case OPT_HELP:
  211. help();
  212. break;
  213. case OPT_APPLE:
  214. flags |= MAGIC_APPLE;
  215. break;
  216. case OPT_EXTENSIONS:
  217. flags |= MAGIC_EXTENSION;
  218. break;
  219. case OPT_MIME_TYPE:
  220. flags |= MAGIC_MIME_TYPE;
  221. break;
  222. case OPT_MIME_ENCODING:
  223. flags |= MAGIC_MIME_ENCODING;
  224. break;
  225. case '0':
  226. nulsep++;
  227. break;
  228. case 'b':
  229. bflag++;
  230. break;
  231. case 'c':
  232. action = FILE_CHECK;
  233. break;
  234. case 'C':
  235. action = FILE_COMPILE;
  236. break;
  237. case 'd':
  238. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  239. break;
  240. case 'E':
  241. flags |= MAGIC_ERROR;
  242. break;
  243. case 'e':
  244. case OPT_EXCLUDE_QUIET:
  245. for (i = 0; i < __arraycount(nv); i++)
  246. if (strcmp(nv[i].name, optarg) == 0)
  247. break;
  248. if (i == __arraycount(nv)) {
  249. if (c != OPT_EXCLUDE_QUIET)
  250. errflg++;
  251. } else
  252. flags |= nv[i].value;
  253. break;
  254. case 'f':
  255. if(action)
  256. usage();
  257. if (magic == NULL)
  258. if ((magic = load(magicfile, flags)) == NULL)
  259. return 1;
  260. applyparam(magic);
  261. e |= unwrap(magic, optarg);
  262. ++didsomefiles;
  263. break;
  264. case 'F':
  265. separator = optarg;
  266. break;
  267. case 'i':
  268. flags |= MAGIC_MIME;
  269. break;
  270. case 'k':
  271. flags |= MAGIC_CONTINUE;
  272. break;
  273. case 'l':
  274. action = FILE_LIST;
  275. break;
  276. case 'm':
  277. magicfile = optarg;
  278. break;
  279. case 'n':
  280. ++nobuffer;
  281. break;
  282. case 'N':
  283. ++nopad;
  284. break;
  285. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  286. case 'p':
  287. flags |= MAGIC_PRESERVE_ATIME;
  288. break;
  289. #endif
  290. case 'P':
  291. setparam(optarg);
  292. break;
  293. case 'r':
  294. flags |= MAGIC_RAW;
  295. break;
  296. case 's':
  297. flags |= MAGIC_DEVICES;
  298. break;
  299. case 'S':
  300. #ifdef HAVE_LIBSECCOMP
  301. sandbox = 0;
  302. #endif
  303. break;
  304. case 'v':
  305. if (magicfile == NULL)
  306. magicfile = magic_getpath(magicfile, action);
  307. (void)fprintf(stdout, "%s-%s\n", file_getprogname(),
  308. VERSION);
  309. (void)fprintf(stdout, "magic file from %s\n",
  310. magicfile);
  311. #ifdef HAVE_LIBSECCOMP
  312. (void)fprintf(stdout, "seccomp support included\n");
  313. #endif
  314. return 0;
  315. case 'z':
  316. flags |= MAGIC_COMPRESS;
  317. break;
  318. case 'Z':
  319. flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
  320. break;
  321. #ifdef S_IFLNK
  322. case 'L':
  323. flags |= MAGIC_SYMLINK;
  324. break;
  325. case 'h':
  326. flags &= ~MAGIC_SYMLINK;
  327. break;
  328. #endif
  329. case '?':
  330. default:
  331. errflg++;
  332. break;
  333. }
  334. if (errflg) {
  335. usage();
  336. }
  337. if (e)
  338. return e;
  339. #ifdef HAVE_LIBSECCOMP
  340. if (sandbox && enable_sandbox() == -1)
  341. file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
  342. if (sandbox)
  343. flags |= MAGIC_NO_COMPRESS_FORK;
  344. #endif /* HAVE_LIBSECCOMP */
  345. if (MAGIC_VERSION != magic_version())
  346. file_warnx("Compiled magic version [%d] "
  347. "does not match with shared library magic version [%d]\n",
  348. MAGIC_VERSION, magic_version());
  349. switch(action) {
  350. case FILE_CHECK:
  351. case FILE_COMPILE:
  352. case FILE_LIST:
  353. /*
  354. * Don't try to check/compile ~/.magic unless we explicitly
  355. * ask for it.
  356. */
  357. magic = magic_open(flags|MAGIC_CHECK);
  358. if (magic == NULL) {
  359. file_warn("Can't create magic");
  360. return 1;
  361. }
  362. switch(action) {
  363. case FILE_CHECK:
  364. c = magic_check(magic, magicfile);
  365. break;
  366. case FILE_COMPILE:
  367. c = magic_compile(magic, magicfile);
  368. break;
  369. case FILE_LIST:
  370. c = magic_list(magic, magicfile);
  371. break;
  372. default:
  373. abort();
  374. }
  375. if (c == -1) {
  376. file_warnx("%s", magic_error(magic));
  377. e = 1;
  378. goto out;
  379. }
  380. goto out;
  381. default:
  382. if (magic == NULL)
  383. if ((magic = load(magicfile, flags)) == NULL)
  384. return 1;
  385. applyparam(magic);
  386. }
  387. if (optind == argc) {
  388. if (!didsomefiles)
  389. usage();
  390. goto out;
  391. }
  392. for (wid = 0, j = CAST(size_t, optind); j < CAST(size_t, argc);
  393. j++) {
  394. nw = file_mbswidth(magic, argv[j]);
  395. if (nw > wid)
  396. wid = nw;
  397. }
  398. /*
  399. * If bflag is only set twice, set it depending on
  400. * number of files [this is undocumented, and subject to change]
  401. */
  402. if (bflag == 2) {
  403. bflag = optind >= argc - 1;
  404. }
  405. for (; optind < argc; optind++)
  406. e |= process(magic, argv[optind], wid);
  407. out:
  408. if (!nobuffer)
  409. e |= fflush(stdout) != 0;
  410. if (magic)
  411. magic_close(magic);
  412. return e;
  413. }
  414. file_private void
  415. applyparam(magic_t magic)
  416. {
  417. size_t i;
  418. for (i = 0; i < __arraycount(pm); i++) {
  419. if (!pm[i].set)
  420. continue;
  421. if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
  422. file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
  423. }
  424. }
  425. file_private void
  426. setparam(const char *p)
  427. {
  428. size_t i;
  429. char *s;
  430. if ((s = CCAST(char *, strchr(p, '='))) == NULL)
  431. goto badparm;
  432. for (i = 0; i < __arraycount(pm); i++) {
  433. if (strncmp(p, pm[i].name, s - p) != 0)
  434. continue;
  435. pm[i].value = atoi(s + 1);
  436. pm[i].set = 1;
  437. return;
  438. }
  439. badparm:
  440. file_errx(EXIT_FAILURE, "Unknown param %s", p);
  441. }
  442. file_private struct magic_set *
  443. /*ARGSUSED*/
  444. load(const char *magicfile, int flags)
  445. {
  446. struct magic_set *magic = magic_open(flags);
  447. const char *e;
  448. if (magic == NULL) {
  449. file_warn("Can't create magic");
  450. return NULL;
  451. }
  452. if (magic_load(magic, magicfile) == -1) {
  453. file_warn("%s", magic_error(magic));
  454. magic_close(magic);
  455. return NULL;
  456. }
  457. if ((e = magic_error(magic)) != NULL)
  458. file_warn("%s", e);
  459. return magic;
  460. }
  461. /*
  462. * unwrap -- read a file of filenames, do each one.
  463. */
  464. file_private int
  465. unwrap(struct magic_set *ms, const char *fn)
  466. {
  467. FILE *f;
  468. ssize_t len;
  469. char *line = NULL;
  470. size_t llen = 0;
  471. int wid = 0, cwid;
  472. int e = 0;
  473. size_t fi = 0, fimax = 0;
  474. char **flist = NULL;
  475. if (strcmp("-", fn) == 0)
  476. f = stdin;
  477. else {
  478. if ((f = fopen(fn, "r")) == NULL) {
  479. file_warn("Cannot open `%s'", fn);
  480. return 1;
  481. }
  482. }
  483. while ((len = getline(&line, &llen, f)) > 0) {
  484. if (line[len - 1] == '\n')
  485. line[len - 1] = '\0';
  486. cwid = file_mbswidth(ms, line);
  487. if (nobuffer) {
  488. e |= process(ms, line, cwid);
  489. free(line);
  490. line = NULL;
  491. llen = 0;
  492. continue;
  493. }
  494. if (cwid > wid)
  495. wid = cwid;
  496. if (fi >= fimax) {
  497. fimax += 100;
  498. char **nf = CAST(char **,
  499. realloc(flist, fimax * sizeof(*flist)));
  500. if (nf == NULL) {
  501. file_err(EXIT_FAILURE,
  502. "Cannot allocate memory for file list");
  503. }
  504. flist = nf;
  505. }
  506. flist[fi++] = line;
  507. line = NULL;
  508. llen = 0;
  509. }
  510. if (!nobuffer) {
  511. fimax = fi;
  512. for (fi = 0; fi < fimax; fi++) {
  513. e |= process(ms, flist[fi], wid);
  514. free(flist[fi]);
  515. }
  516. }
  517. free(flist);
  518. if (f != stdin)
  519. (void)fclose(f);
  520. return e;
  521. }
  522. file_private void
  523. file_octal(unsigned char c)
  524. {
  525. (void)putc('\\', stdout);
  526. (void)putc(((c >> 6) & 7) + '0', stdout);
  527. (void)putc(((c >> 3) & 7) + '0', stdout);
  528. (void)putc(((c >> 0) & 7) + '0', stdout);
  529. }
  530. file_private void
  531. fname_print(const char *inname)
  532. {
  533. size_t n = strlen(inname);
  534. #ifdef FILE_WIDE_SUPPORT
  535. mbstate_t state;
  536. wchar_t nextchar;
  537. size_t bytesconsumed;
  538. (void)memset(&state, 0, sizeof(state));
  539. while (n > 0) {
  540. bytesconsumed = mbrtowc(&nextchar, inname, n, &state);
  541. if (bytesconsumed == CAST(size_t, -1) ||
  542. bytesconsumed == CAST(size_t, -2)) {
  543. nextchar = *inname++;
  544. n--;
  545. (void)memset(&state, 0, sizeof(state));
  546. file_octal(CAST(unsigned char, nextchar));
  547. continue;
  548. }
  549. inname += bytesconsumed;
  550. n -= bytesconsumed;
  551. if (iswprint(nextchar)) {
  552. printf("%lc", (wint_t)nextchar);
  553. continue;
  554. }
  555. /* XXX: What if it is > 255? */
  556. file_octal(CAST(unsigned char, nextchar));
  557. }
  558. #else
  559. size_t i;
  560. for (i = 0; i < n; i++) {
  561. unsigned char c = CAST(unsigned char, inname[i]);
  562. if (isprint(c)) {
  563. (void)putc(c, stdout);
  564. continue;
  565. }
  566. file_octal(c);
  567. }
  568. #endif
  569. }
  570. /*
  571. * Called for each input file on the command line (or in a list of files)
  572. */
  573. file_private int
  574. process(struct magic_set *ms, const char *inname, int wid)
  575. {
  576. const char *type, c = nulsep > 1 ? '\0' : '\n';
  577. int std_in = strcmp(inname, "-") == 0;
  578. int haderror = 0;
  579. if (wid > 0 && !bflag) {
  580. const char *pname = std_in ? "/dev/stdin" : inname;
  581. if ((ms->flags & MAGIC_RAW) == 0)
  582. fname_print(pname);
  583. else
  584. (void)printf("%s", pname);
  585. if (nulsep)
  586. (void)putc('\0', stdout);
  587. if (nulsep < 2) {
  588. (void)printf("%s", separator);
  589. (void)printf("%*s ", CAST(int, nopad ? 0
  590. : (wid - file_mbswidth(ms, inname))), "");
  591. }
  592. }
  593. type = magic_file(ms, std_in ? NULL : inname);
  594. if (type == NULL) {
  595. haderror |= printf("ERROR: %s%c", magic_error(ms), c);
  596. } else {
  597. haderror |= printf("%s%c", type, c) < 0;
  598. }
  599. if (nobuffer)
  600. haderror |= fflush(stdout) != 0;
  601. return haderror || type == NULL;
  602. }
  603. file_protected size_t
  604. file_mbswidth(struct magic_set *ms, const char *s)
  605. {
  606. size_t width = 0;
  607. #ifdef FILE_WIDE_SUPPORT
  608. size_t bytesconsumed, n;
  609. mbstate_t state;
  610. wchar_t nextchar;
  611. (void)memset(&state, 0, sizeof(state));
  612. n = strlen(s);
  613. while (n > 0) {
  614. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  615. if (bytesconsumed == CAST(size_t, -1) ||
  616. bytesconsumed == CAST(size_t, -2)) {
  617. nextchar = *s;
  618. bytesconsumed = 1;
  619. (void)memset(&state, 0, sizeof(state));
  620. width += 4;
  621. } else {
  622. int w = wcwidth(nextchar);
  623. width += ((ms->flags & MAGIC_RAW) != 0
  624. || iswprint(nextchar)) ? (w > 0 ? w : 1) : 4;
  625. }
  626. s += bytesconsumed, n -= bytesconsumed;
  627. }
  628. #else
  629. for (; *s; s++) {
  630. width += (ms->flags & MAGIC_RAW) != 0
  631. || isprint(CAST(unsigned char, *s)) ? 1 : 4;
  632. }
  633. #endif
  634. return width;
  635. }
  636. file_private void
  637. usage(void)
  638. {
  639. const char *pn = file_getprogname();
  640. (void)fprintf(stderr, USAGE, pn, pn, pn);
  641. exit(EXIT_FAILURE);
  642. }
  643. file_private void
  644. defprint(int def)
  645. {
  646. if (!def)
  647. return;
  648. if (((def & 1) && posixly) || ((def & 2) && !posixly))
  649. (void)fprintf(stdout, " (default)");
  650. (void)putc('\n', stdout);
  651. }
  652. file_private void
  653. docprint(const char *opts, int def)
  654. {
  655. size_t i;
  656. int comma, pad;
  657. char *sp, *p;
  658. p = CCAST(char *, strchr(opts, '%'));
  659. if (p == NULL) {
  660. (void)fprintf(stdout, "%s", opts);
  661. defprint(def);
  662. return;
  663. }
  664. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  665. continue;
  666. (void)printf("%.*s", CAST(int, p - opts), opts);
  667. pad = (int)CAST(int, p - sp - 1);
  668. switch (*++p) {
  669. case 'e':
  670. comma = 0;
  671. for (i = 0; i < __arraycount(nv); i++) {
  672. (void)printf("%s%s", comma++ ? ", " : "", nv[i].name);
  673. if (i && i % 5 == 0 && i != __arraycount(nv) - 1) {
  674. (void)printf(",\n%*s", pad, "");
  675. comma = 0;
  676. }
  677. }
  678. break;
  679. case 'P':
  680. for (i = 0; i < __arraycount(pm); i++) {
  681. (void)printf("%9s %7zu %s", pm[i].name, pm[i].def,
  682. pm[i].desc);
  683. if (i != __arraycount(pm) - 1)
  684. (void)printf("\n%*s", pad, "");
  685. }
  686. break;
  687. default:
  688. file_errx(EXIT_FAILURE, "Unknown escape `%c' in long options",
  689. *p);
  690. break;
  691. }
  692. (void)printf("%s", opts + (p - opts) + 1);
  693. }
  694. file_private void
  695. help(void)
  696. {
  697. (void)fputs(
  698. "Usage: file [OPTION...] [FILE...]\n"
  699. "Determine type of FILEs.\n"
  700. "\n", stdout);
  701. #define OPT(shortname, longname, opt, def, doc) \
  702. (void)printf(" -%c, --" longname, shortname), \
  703. docprint(doc, def);
  704. #define OPT_LONGONLY(longname, opt, def, doc, id) \
  705. (void)printf(" --" longname), \
  706. docprint(doc, def);
  707. #include "file_opts.h"
  708. #undef OPT
  709. #undef OPT_LONGONLY
  710. (void)printf("\nReport bugs to https://bugs.astron.com/\n");
  711. exit(EXIT_SUCCESS);
  712. }
  713. file_private const char *file_progname;
  714. file_protected void
  715. file_setprogname(const char *progname)
  716. {
  717. file_progname = progname;
  718. }
  719. file_protected const char *
  720. file_getprogname(void)
  721. {
  722. return file_progname;
  723. }
  724. file_protected void
  725. file_err(int e, const char *fmt, ...)
  726. {
  727. va_list ap;
  728. int se = errno;
  729. va_start(ap, fmt);
  730. (void)fprintf(stderr, "%s: ", file_progname);
  731. (void)vfprintf(stderr, fmt, ap);
  732. va_end(ap);
  733. if (se)
  734. (void)fprintf(stderr, " (%s)\n", strerror(se));
  735. else
  736. fputc('\n', stderr);
  737. exit(e);
  738. }
  739. file_protected void
  740. file_errx(int e, const char *fmt, ...)
  741. {
  742. va_list ap;
  743. va_start(ap, fmt);
  744. (void)fprintf(stderr, "%s: ", file_progname);
  745. (void)vfprintf(stderr, fmt, ap);
  746. va_end(ap);
  747. (void)fprintf(stderr, "\n");
  748. exit(e);
  749. }
  750. file_protected void
  751. file_warn(const char *fmt, ...)
  752. {
  753. va_list ap;
  754. int se = errno;
  755. va_start(ap, fmt);
  756. (void)fprintf(stderr, "%s: ", file_progname);
  757. (void)vfprintf(stderr, fmt, ap);
  758. va_end(ap);
  759. if (se)
  760. (void)fprintf(stderr, " (%s)\n", strerror(se));
  761. else
  762. fputc('\n', stderr);
  763. errno = se;
  764. }
  765. file_protected void
  766. file_warnx(const char *fmt, ...)
  767. {
  768. va_list ap;
  769. int se = errno;
  770. va_start(ap, fmt);
  771. (void)fprintf(stderr, "%s: ", file_progname);
  772. (void)vfprintf(stderr, fmt, ap);
  773. va_end(ap);
  774. (void)fprintf(stderr, "\n");
  775. errno = se;
  776. }