file.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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.204 2022/09/13 18:46:07 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. 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. private const char *separator = ":"; /* Default field separator */
  97. 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. 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. 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. private int posixly;
  156. #ifdef __dead
  157. __dead
  158. #endif
  159. private void usage(void);
  160. private void docprint(const char *, int);
  161. #ifdef __dead
  162. __dead
  163. #endif
  164. private void help(void);
  165. private int unwrap(struct magic_set *, const char *);
  166. private int process(struct magic_set *ms, const char *, int);
  167. private struct magic_set *load(const char *, int);
  168. private void setparam(const char *);
  169. 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. #endif /* HAVE_LIBSECCOMP */
  342. if (MAGIC_VERSION != magic_version())
  343. file_warnx("Compiled magic version [%d] "
  344. "does not match with shared library magic version [%d]\n",
  345. MAGIC_VERSION, magic_version());
  346. switch(action) {
  347. case FILE_CHECK:
  348. case FILE_COMPILE:
  349. case FILE_LIST:
  350. /*
  351. * Don't try to check/compile ~/.magic unless we explicitly
  352. * ask for it.
  353. */
  354. magic = magic_open(flags|MAGIC_CHECK);
  355. if (magic == NULL) {
  356. file_warn("Can't create magic");
  357. return 1;
  358. }
  359. switch(action) {
  360. case FILE_CHECK:
  361. c = magic_check(magic, magicfile);
  362. break;
  363. case FILE_COMPILE:
  364. c = magic_compile(magic, magicfile);
  365. break;
  366. case FILE_LIST:
  367. c = magic_list(magic, magicfile);
  368. break;
  369. default:
  370. abort();
  371. }
  372. if (c == -1) {
  373. file_warnx("%s", magic_error(magic));
  374. e = 1;
  375. goto out;
  376. }
  377. goto out;
  378. default:
  379. if (magic == NULL)
  380. if ((magic = load(magicfile, flags)) == NULL)
  381. return 1;
  382. applyparam(magic);
  383. }
  384. if (optind == argc) {
  385. if (!didsomefiles)
  386. usage();
  387. goto out;
  388. }
  389. for (wid = 0, j = CAST(size_t, optind); j < CAST(size_t, argc);
  390. j++) {
  391. nw = file_mbswidth(magic, argv[j]);
  392. if (nw > wid)
  393. wid = nw;
  394. }
  395. /*
  396. * If bflag is only set twice, set it depending on
  397. * number of files [this is undocumented, and subject to change]
  398. */
  399. if (bflag == 2) {
  400. bflag = optind >= argc - 1;
  401. }
  402. for (; optind < argc; optind++)
  403. e |= process(magic, argv[optind], wid);
  404. out:
  405. if (!nobuffer)
  406. e |= fflush(stdout) != 0;
  407. if (magic)
  408. magic_close(magic);
  409. return e;
  410. }
  411. private void
  412. applyparam(magic_t magic)
  413. {
  414. size_t i;
  415. for (i = 0; i < __arraycount(pm); i++) {
  416. if (!pm[i].set)
  417. continue;
  418. if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
  419. file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
  420. }
  421. }
  422. private void
  423. setparam(const char *p)
  424. {
  425. size_t i;
  426. char *s;
  427. if ((s = CCAST(char *, strchr(p, '='))) == NULL)
  428. goto badparm;
  429. for (i = 0; i < __arraycount(pm); i++) {
  430. if (strncmp(p, pm[i].name, s - p) != 0)
  431. continue;
  432. pm[i].value = atoi(s + 1);
  433. pm[i].set = 1;
  434. return;
  435. }
  436. badparm:
  437. file_errx(EXIT_FAILURE, "Unknown param %s", p);
  438. }
  439. private struct magic_set *
  440. /*ARGSUSED*/
  441. load(const char *magicfile, int flags)
  442. {
  443. struct magic_set *magic = magic_open(flags);
  444. const char *e;
  445. if (magic == NULL) {
  446. file_warn("Can't create magic");
  447. return NULL;
  448. }
  449. if (magic_load(magic, magicfile) == -1) {
  450. file_warn("%s", magic_error(magic));
  451. magic_close(magic);
  452. return NULL;
  453. }
  454. if ((e = magic_error(magic)) != NULL)
  455. file_warn("%s", e);
  456. return magic;
  457. }
  458. /*
  459. * unwrap -- read a file of filenames, do each one.
  460. */
  461. private int
  462. unwrap(struct magic_set *ms, const char *fn)
  463. {
  464. FILE *f;
  465. ssize_t len;
  466. char *line = NULL;
  467. size_t llen = 0;
  468. int wid = 0, cwid;
  469. int e = 0;
  470. size_t fi = 0, fimax = 100;
  471. char **flist = CAST(char **, malloc(sizeof(*flist) * fimax));
  472. if (flist == NULL)
  473. out: file_err(EXIT_FAILURE, "Cannot allocate memory for file list");
  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. if (fi >= fimax) {
  486. fimax += 100;
  487. char **nf = CAST(char **,
  488. realloc(flist, fimax * sizeof(*flist)));
  489. if (nf == NULL)
  490. goto out;
  491. flist = nf;
  492. }
  493. flist[fi++] = line;
  494. cwid = file_mbswidth(ms, line);
  495. if (cwid > wid)
  496. wid = cwid;
  497. line = NULL;
  498. llen = 0;
  499. }
  500. fimax = fi;
  501. for (fi = 0; fi < fimax; fi++) {
  502. e |= process(ms, flist[fi], wid);
  503. free(flist[fi]);
  504. }
  505. free(flist);
  506. if (f != stdin)
  507. (void)fclose(f);
  508. return e;
  509. }
  510. private void
  511. file_octal(unsigned char c)
  512. {
  513. putc('\\', stdout);
  514. putc(((c >> 6) & 7) + '0', stdout);
  515. putc(((c >> 3) & 7) + '0', stdout);
  516. putc(((c >> 0) & 7) + '0', stdout);
  517. }
  518. private void
  519. fname_print(const char *inname)
  520. {
  521. size_t n = strlen(inname);
  522. #ifdef FILE_WIDE_SUPPORT
  523. mbstate_t state;
  524. wchar_t nextchar;
  525. size_t bytesconsumed;
  526. (void)memset(&state, 0, sizeof(state));
  527. while (n > 0) {
  528. bytesconsumed = mbrtowc(&nextchar, inname, n, &state);
  529. if (bytesconsumed == CAST(size_t, -1) ||
  530. bytesconsumed == CAST(size_t, -2)) {
  531. nextchar = *inname++;
  532. n--;
  533. (void)memset(&state, 0, sizeof(state));
  534. file_octal(CAST(unsigned char, nextchar));
  535. continue;
  536. }
  537. inname += bytesconsumed;
  538. n -= bytesconsumed;
  539. if (iswprint(nextchar)) {
  540. printf("%lc", nextchar);
  541. continue;
  542. }
  543. /* XXX: What if it is > 255? */
  544. file_octal(CAST(unsigned char, nextchar));
  545. }
  546. #else
  547. size_t i;
  548. for (i = 0; i < n; i++) {
  549. unsigned char c = CAST(unsigned char, inname[i]);
  550. if (isprint(c)) {
  551. putc(c);
  552. continue;
  553. }
  554. file_octal(c);
  555. }
  556. #endif
  557. }
  558. /*
  559. * Called for each input file on the command line (or in a list of files)
  560. */
  561. private int
  562. process(struct magic_set *ms, const char *inname, int wid)
  563. {
  564. const char *type, c = nulsep > 1 ? '\0' : '\n';
  565. int std_in = strcmp(inname, "-") == 0;
  566. int haderror = 0;
  567. if (wid > 0 && !bflag) {
  568. const char *pname = std_in ? "/dev/stdin" : inname;
  569. if ((ms->flags & MAGIC_RAW) == 0)
  570. fname_print(pname);
  571. else
  572. (void)printf("%s", pname);
  573. if (nulsep)
  574. (void)putc('\0', stdout);
  575. if (nulsep < 2) {
  576. (void)printf("%s", separator);
  577. (void)printf("%*s ", CAST(int, nopad ? 0
  578. : (wid - file_mbswidth(ms, inname))), "");
  579. }
  580. }
  581. type = magic_file(ms, std_in ? NULL : inname);
  582. if (type == NULL) {
  583. haderror |= printf("ERROR: %s%c", magic_error(ms), c);
  584. } else {
  585. haderror |= printf("%s%c", type, c) < 0;
  586. }
  587. if (nobuffer)
  588. haderror |= fflush(stdout) != 0;
  589. return haderror || type == NULL;
  590. }
  591. protected size_t
  592. file_mbswidth(struct magic_set *ms, const char *s)
  593. {
  594. size_t width = 0;
  595. #ifdef FILE_WIDE_SUPPORT
  596. size_t bytesconsumed, n;
  597. mbstate_t state;
  598. wchar_t nextchar;
  599. (void)memset(&state, 0, sizeof(state));
  600. n = strlen(s);
  601. while (n > 0) {
  602. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  603. if (bytesconsumed == CAST(size_t, -1) ||
  604. bytesconsumed == CAST(size_t, -2)) {
  605. nextchar = *s;
  606. bytesconsumed = 1;
  607. (void)memset(&state, 0, sizeof(state));
  608. width += 4;
  609. } else {
  610. int w = wcwidth(nextchar);
  611. width += ((ms->flags & MAGIC_RAW) != 0
  612. || iswprint(nextchar)) ? (w > 0 ? w : 1) : 4;
  613. }
  614. s += bytesconsumed, n -= bytesconsumed;
  615. }
  616. #else
  617. for (; *s; s++) {
  618. width += (ms->flags & MAGIC_RAW) != 0
  619. || isprint(CAST(unsigned char, *s)) ? 1 : 4;
  620. }
  621. #endif
  622. return width;
  623. }
  624. private void
  625. usage(void)
  626. {
  627. const char *pn = file_getprogname();
  628. (void)fprintf(stderr, USAGE, pn, pn, pn);
  629. exit(EXIT_FAILURE);
  630. }
  631. private void
  632. defprint(int def)
  633. {
  634. if (!def)
  635. return;
  636. if (((def & 1) && posixly) || ((def & 2) && !posixly))
  637. fprintf(stdout, " (default)");
  638. fputc('\n', stdout);
  639. }
  640. private void
  641. docprint(const char *opts, int def)
  642. {
  643. size_t i;
  644. int comma, pad;
  645. char *sp, *p;
  646. p = CCAST(char *, strchr(opts, '%'));
  647. if (p == NULL) {
  648. fprintf(stdout, "%s", opts);
  649. defprint(def);
  650. return;
  651. }
  652. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  653. continue;
  654. fprintf(stdout, "%.*s", CAST(int, p - opts), opts);
  655. pad = (int)CAST(int, p - sp - 1);
  656. switch (*++p) {
  657. case 'e':
  658. comma = 0;
  659. for (i = 0; i < __arraycount(nv); i++) {
  660. fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
  661. if (i && i % 5 == 0 && i != __arraycount(nv) - 1) {
  662. fprintf(stdout, ",\n%*s", pad, "");
  663. comma = 0;
  664. }
  665. }
  666. break;
  667. case 'P':
  668. for (i = 0; i < __arraycount(pm); i++) {
  669. fprintf(stdout, "%9s %7zu %s", pm[i].name, pm[i].def,
  670. pm[i].desc);
  671. if (i != __arraycount(pm) - 1)
  672. fprintf(stdout, "\n%*s", pad, "");
  673. }
  674. break;
  675. default:
  676. file_errx(EXIT_FAILURE, "Unknown escape `%c' in long options",
  677. *p);
  678. break;
  679. }
  680. fprintf(stdout, "%s", opts + (p - opts) + 1);
  681. }
  682. private void
  683. help(void)
  684. {
  685. (void)fputs(
  686. "Usage: file [OPTION...] [FILE...]\n"
  687. "Determine type of FILEs.\n"
  688. "\n", stdout);
  689. #define OPT(shortname, longname, opt, def, doc) \
  690. fprintf(stdout, " -%c, --" longname, shortname), \
  691. docprint(doc, def);
  692. #define OPT_LONGONLY(longname, opt, def, doc, id) \
  693. fprintf(stdout, " --" longname), \
  694. docprint(doc, def);
  695. #include "file_opts.h"
  696. #undef OPT
  697. #undef OPT_LONGONLY
  698. fprintf(stdout, "\nReport bugs to https://bugs.astron.com/\n");
  699. exit(EXIT_SUCCESS);
  700. }
  701. private const char *file_progname;
  702. protected void
  703. file_setprogname(const char *progname)
  704. {
  705. file_progname = progname;
  706. }
  707. protected const char *
  708. file_getprogname(void)
  709. {
  710. return file_progname;
  711. }
  712. protected void
  713. file_err(int e, const char *fmt, ...)
  714. {
  715. va_list ap;
  716. int se = errno;
  717. va_start(ap, fmt);
  718. fprintf(stderr, "%s: ", file_progname);
  719. vfprintf(stderr, fmt, ap);
  720. va_end(ap);
  721. if (se)
  722. fprintf(stderr, " (%s)\n", strerror(se));
  723. else
  724. fputc('\n', stderr);
  725. exit(e);
  726. }
  727. protected void
  728. file_errx(int e, const char *fmt, ...)
  729. {
  730. va_list ap;
  731. va_start(ap, fmt);
  732. fprintf(stderr, "%s: ", file_progname);
  733. vfprintf(stderr, fmt, ap);
  734. va_end(ap);
  735. fprintf(stderr, "\n");
  736. exit(e);
  737. }
  738. protected void
  739. file_warn(const char *fmt, ...)
  740. {
  741. va_list ap;
  742. int se = errno;
  743. va_start(ap, fmt);
  744. fprintf(stderr, "%s: ", file_progname);
  745. vfprintf(stderr, fmt, ap);
  746. va_end(ap);
  747. if (se)
  748. fprintf(stderr, " (%s)\n", strerror(se));
  749. else
  750. fputc('\n', stderr);
  751. errno = se;
  752. }
  753. protected void
  754. file_warnx(const char *fmt, ...)
  755. {
  756. va_list ap;
  757. int se = errno;
  758. va_start(ap, fmt);
  759. fprintf(stderr, "%s: ", file_progname);
  760. vfprintf(stderr, fmt, ap);
  761. va_end(ap);
  762. fprintf(stderr, "\n");
  763. errno = se;
  764. }