file.c 19 KB

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