file.c 19 KB

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