funcs.c 21 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. /*
  2. * Copyright (c) Christos Zoulas 2003.
  3. * All Rights Reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice immediately at the beginning of the file, without modification,
  10. * this list of conditions, and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
  19. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. * SUCH DAMAGE.
  26. */
  27. #include "file.h"
  28. #ifndef lint
  29. FILE_RCSID("@(#)$File: funcs.c,v 1.148 2026/01/10 16:18:18 christos Exp $")
  30. #endif /* lint */
  31. #include "magic.h"
  32. #include <assert.h>
  33. #include <stdarg.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <ctype.h>
  37. #ifdef HAVE_UNISTD_H
  38. #include <unistd.h> /* for pipe2() */
  39. #endif
  40. #if defined(HAVE_WCHAR_H)
  41. #include <wchar.h>
  42. #endif
  43. #if defined(HAVE_WCTYPE_H)
  44. #include <wctype.h>
  45. #endif
  46. #include <limits.h>
  47. #ifndef SIZE_MAX
  48. #define SIZE_MAX ((size_t)~0)
  49. #endif
  50. file_protected char *
  51. file_copystr(char *buf, size_t blen, size_t width, const char *str)
  52. {
  53. if (blen == 0)
  54. return buf;
  55. if (width >= blen)
  56. width = blen - 1;
  57. memcpy(buf, str, width);
  58. buf[width] = '\0';
  59. return buf;
  60. }
  61. file_private void
  62. file_clearbuf(struct magic_set *ms)
  63. {
  64. free(ms->o.buf);
  65. ms->o.buf = NULL;
  66. ms->o.blen = 0;
  67. }
  68. file_private int
  69. file_checkfield(char *msg, size_t mlen, const char *what, const char **pp)
  70. {
  71. const char *p = *pp;
  72. int fw = 0;
  73. while (*p && isdigit((unsigned char)*p))
  74. fw = fw * 10 + (*p++ - '0');
  75. *pp = p;
  76. if (fw < 1024)
  77. return 1;
  78. if (msg)
  79. snprintf(msg, mlen, "field %s too large: %d", what, fw);
  80. return 0;
  81. }
  82. file_protected int
  83. file_checkfmt(char *msg, size_t mlen, const char *fmt)
  84. {
  85. const char *p;
  86. for (p = fmt; *p; p++) {
  87. if (*p != '%')
  88. continue;
  89. if (*++p == '%')
  90. continue;
  91. if (*p == '\0') {
  92. if (msg)
  93. snprintf(msg, mlen, "incomplete %% format");
  94. return -1;
  95. }
  96. // Skip uninteresting.
  97. while (*p != '\0' && strchr("#0.'+- ", *p) != NULL)
  98. p++;
  99. if (*p == '*') {
  100. if (msg)
  101. snprintf(msg, mlen, "* not allowed in format");
  102. return -1;
  103. }
  104. if (!file_checkfield(msg, mlen, "width", &p))
  105. return -1;
  106. if (*p == '.') {
  107. p++;
  108. if (!file_checkfield(msg, mlen, "precision", &p))
  109. return -1;
  110. }
  111. if (!isalpha((unsigned char)*p)) {
  112. if (msg)
  113. snprintf(msg, mlen, "bad format char: %c", *p);
  114. return -1;
  115. }
  116. }
  117. return 0;
  118. }
  119. /*
  120. * Like printf, only we append to a buffer.
  121. */
  122. file_protected int
  123. file_vprintf(struct magic_set *ms, const char *fmt, va_list ap)
  124. {
  125. int len;
  126. char *buf, *newstr;
  127. char tbuf[1024];
  128. if (ms->event_flags & EVENT_HAD_ERR)
  129. return 0;
  130. if (file_checkfmt(tbuf, sizeof(tbuf), fmt)) {
  131. file_clearbuf(ms);
  132. file_error(ms, 0, "Bad magic format `%s' (%s)", fmt, tbuf);
  133. return -1;
  134. }
  135. len = vasprintf(&buf, fmt, ap);
  136. if (len < 0 || (size_t)len > 1024 || len + ms->o.blen > 1024 * 1024) {
  137. size_t blen = ms->o.blen;
  138. free(buf);
  139. file_clearbuf(ms);
  140. file_error(ms, 0, "Output buffer space exceeded %d+%"
  141. SIZE_T_FORMAT "u", len, blen);
  142. return -1;
  143. }
  144. if (ms->o.buf != NULL) {
  145. len = asprintf(&newstr, "%s%s", ms->o.buf, buf);
  146. free(buf);
  147. if (len < 0)
  148. goto out;
  149. free(ms->o.buf);
  150. buf = newstr;
  151. }
  152. ms->o.buf = buf;
  153. ms->o.blen = len;
  154. return 0;
  155. out:
  156. file_clearbuf(ms);
  157. file_error(ms, errno, "vasprintf failed");
  158. return -1;
  159. }
  160. file_protected int
  161. file_printf(struct magic_set *ms, const char *fmt, ...)
  162. {
  163. int rv;
  164. va_list ap;
  165. va_start(ap, fmt);
  166. rv = file_vprintf(ms, fmt, ap);
  167. va_end(ap);
  168. return rv;
  169. }
  170. /*
  171. * error - print best error message possible
  172. */
  173. /*VARARGS*/
  174. __attribute__((__format__(__printf__, 3, 0)))
  175. file_private void
  176. file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
  177. size_t lineno)
  178. {
  179. /* Only the first error is ok */
  180. if (ms->event_flags & EVENT_HAD_ERR)
  181. return;
  182. if (lineno != 0) {
  183. file_clearbuf(ms);
  184. (void)file_printf(ms, "line %" SIZE_T_FORMAT "u:", lineno);
  185. }
  186. if (ms->o.buf && *ms->o.buf)
  187. (void)file_printf(ms, " ");
  188. (void)file_vprintf(ms, f, va);
  189. if (error > 0)
  190. (void)file_printf(ms, " (%s)", strerror(error));
  191. ms->event_flags |= EVENT_HAD_ERR;
  192. ms->error = error;
  193. }
  194. /*VARARGS*/
  195. file_protected void
  196. file_error(struct magic_set *ms, int error, const char *f, ...)
  197. {
  198. va_list va;
  199. va_start(va, f);
  200. file_error_core(ms, error, f, va, 0);
  201. va_end(va);
  202. }
  203. /*
  204. * Print an error with magic line number.
  205. */
  206. /*VARARGS*/
  207. file_protected void
  208. file_magerror(struct magic_set *ms, const char *f, ...)
  209. {
  210. va_list va;
  211. va_start(va, f);
  212. file_error_core(ms, 0, f, va, ms->line);
  213. va_end(va);
  214. }
  215. file_protected void
  216. file_oomem(struct magic_set *ms, size_t len)
  217. {
  218. file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
  219. len);
  220. }
  221. file_protected void
  222. file_badseek(struct magic_set *ms)
  223. {
  224. file_error(ms, errno, "error seeking");
  225. }
  226. file_protected void
  227. file_badread(struct magic_set *ms)
  228. {
  229. file_error(ms, errno, "error reading");
  230. }
  231. #ifndef COMPILE_ONLY
  232. #define FILE_SEPARATOR "\n- "
  233. file_protected int
  234. file_separator(struct magic_set *ms)
  235. {
  236. return file_printf(ms, FILE_SEPARATOR);
  237. }
  238. static void
  239. trim_separator(struct magic_set *ms)
  240. {
  241. size_t l;
  242. if (ms->o.buf == NULL)
  243. return;
  244. l = strlen(ms->o.buf);
  245. if (l < sizeof(FILE_SEPARATOR))
  246. return;
  247. l -= sizeof(FILE_SEPARATOR) - 1;
  248. if (strcmp(ms->o.buf + l, FILE_SEPARATOR) != 0)
  249. return;
  250. ms->o.buf[l] = '\0';
  251. }
  252. static int
  253. checkdone(struct magic_set *ms, int *rv)
  254. {
  255. if ((ms->flags & MAGIC_CONTINUE) == 0)
  256. return 1;
  257. if (file_separator(ms) == -1)
  258. *rv = -1;
  259. return 0;
  260. }
  261. file_protected int
  262. file_default(struct magic_set *ms, size_t nb)
  263. {
  264. if (ms->flags & MAGIC_MIME) {
  265. if ((ms->flags & MAGIC_MIME_TYPE) &&
  266. file_printf(ms, "application/%s",
  267. nb ? "octet-stream" : "x-empty") == -1)
  268. return -1;
  269. return 1;
  270. }
  271. if (ms->flags & MAGIC_APPLE) {
  272. // This is not a typo: Type: UNKN Creator: UNKN
  273. if (file_printf(ms, "UNKNUNKN") == -1)
  274. return -1;
  275. return 1;
  276. }
  277. if (ms->flags & MAGIC_EXTENSION) {
  278. if (file_printf(ms, "???") == -1)
  279. return -1;
  280. return 1;
  281. }
  282. return 0;
  283. }
  284. /*
  285. * The magic detection functions return:
  286. * 1: found
  287. * 0: not found
  288. * -1: error
  289. */
  290. /*ARGSUSED*/
  291. file_protected int
  292. file_buffer(struct magic_set *ms, int fd, struct stat *st,
  293. const char *inname __attribute__ ((__unused__)),
  294. const void *buf, size_t nb)
  295. {
  296. int m = 0, rv = 0, looks_text = 0;
  297. const char *code = NULL;
  298. const char *code_mime = "binary";
  299. const char *def = "data";
  300. const char *ftype = NULL;
  301. char *rbuf = NULL;
  302. struct buffer b;
  303. buffer_init(&b, fd, st, buf, nb);
  304. ms->mode = b.st.st_mode;
  305. if (nb == 0) {
  306. def = "empty";
  307. goto simple;
  308. } else if (nb == 1) {
  309. def = "very short file (no magic)";
  310. goto simple;
  311. }
  312. if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
  313. looks_text = file_encoding(ms, &b, NULL, 0,
  314. &code, &code_mime, &ftype);
  315. }
  316. #ifdef __EMX__
  317. if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
  318. m = file_os2_apptype(ms, inname, &b);
  319. if ((ms->flags & MAGIC_DEBUG) != 0)
  320. (void)fprintf(stderr, "[try os2_apptype %d]\n", m);
  321. switch (m) {
  322. case -1:
  323. return -1;
  324. case 0:
  325. break;
  326. default:
  327. return 1;
  328. }
  329. }
  330. #endif
  331. #if HAVE_FORK
  332. /* try compression stuff */
  333. if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) {
  334. m = file_zmagic(ms, &b, inname);
  335. if ((ms->flags & MAGIC_DEBUG) != 0)
  336. (void)fprintf(stderr, "[try zmagic %d]\n", m);
  337. if (m) {
  338. goto done_encoding;
  339. }
  340. }
  341. #endif
  342. /* Check if we have a tar file */
  343. if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) {
  344. m = file_is_tar(ms, &b);
  345. if ((ms->flags & MAGIC_DEBUG) != 0)
  346. (void)fprintf(stderr, "[try tar %d]\n", m);
  347. if (m) {
  348. if (checkdone(ms, &rv))
  349. goto done;
  350. }
  351. }
  352. /* Check if we have a JSON file */
  353. if ((ms->flags & MAGIC_NO_CHECK_JSON) == 0) {
  354. m = file_is_json(ms, &b);
  355. if ((ms->flags & MAGIC_DEBUG) != 0)
  356. (void)fprintf(stderr, "[try json %d]\n", m);
  357. if (m) {
  358. if (checkdone(ms, &rv))
  359. goto done;
  360. }
  361. }
  362. /* Check if we have a CSV file */
  363. if ((ms->flags & MAGIC_NO_CHECK_CSV) == 0) {
  364. m = file_is_csv(ms, &b, looks_text, code);
  365. if ((ms->flags & MAGIC_DEBUG) != 0)
  366. (void)fprintf(stderr, "[try csv %d]\n", m);
  367. if (m) {
  368. if (checkdone(ms, &rv))
  369. goto done;
  370. }
  371. }
  372. /* Check if we have a SIMH tape file */
  373. if ((ms->flags & MAGIC_NO_CHECK_SIMH) == 0) {
  374. m = file_is_simh(ms, &b);
  375. if ((ms->flags & MAGIC_DEBUG) != 0)
  376. (void)fprintf(stderr, "[try simh %d]\n", m);
  377. if (m) {
  378. if (checkdone(ms, &rv))
  379. goto done;
  380. }
  381. }
  382. /* Check if we have a CDF file */
  383. if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
  384. m = file_trycdf(ms, &b);
  385. if ((ms->flags & MAGIC_DEBUG) != 0)
  386. (void)fprintf(stderr, "[try cdf %d]\n", m);
  387. if (m) {
  388. if (checkdone(ms, &rv))
  389. goto done;
  390. }
  391. }
  392. #ifdef BUILTIN_ELF
  393. if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && nb > 5 && fd != -1) {
  394. file_pushbuf_t *pb;
  395. /*
  396. * We matched something in the file, so this
  397. * *might* be an ELF file, and the file is at
  398. * least 5 bytes long, so if it's an ELF file
  399. * it has at least one byte past the ELF magic
  400. * number - try extracting information from the
  401. * ELF headers that cannot easily be extracted
  402. * with rules in the magic file. We we don't
  403. * print the information yet.
  404. */
  405. if ((pb = file_push_buffer(ms)) == NULL)
  406. return -1;
  407. rv = file_tryelf(ms, &b);
  408. rbuf = file_pop_buffer(ms, pb);
  409. if (rv == -1) {
  410. free(rbuf);
  411. rbuf = NULL;
  412. }
  413. if ((ms->flags & MAGIC_DEBUG) != 0)
  414. (void)fprintf(stderr, "[try elf %d]\n", m);
  415. }
  416. #endif
  417. /* try soft magic tests */
  418. if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
  419. m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
  420. if ((ms->flags & MAGIC_DEBUG) != 0)
  421. (void)fprintf(stderr, "[try softmagic %d]\n", m);
  422. if (m == 1 && rbuf) {
  423. if (file_printf(ms, "%s", rbuf) == -1)
  424. goto done;
  425. }
  426. if (m) {
  427. if (checkdone(ms, &rv))
  428. goto done;
  429. }
  430. }
  431. /* try text properties */
  432. if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
  433. m = file_ascmagic(ms, &b, looks_text);
  434. if ((ms->flags & MAGIC_DEBUG) != 0)
  435. (void)fprintf(stderr, "[try ascmagic %d]\n", m);
  436. if (m) {
  437. goto done;
  438. }
  439. }
  440. simple:
  441. /* give up */
  442. if (m == 0) {
  443. m = 1;
  444. rv = file_default(ms, nb);
  445. if (rv == 0)
  446. if (file_printf(ms, "%s", def) == -1)
  447. rv = -1;
  448. }
  449. done:
  450. trim_separator(ms);
  451. if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
  452. if (ms->flags & MAGIC_MIME_TYPE)
  453. if (file_printf(ms, "; charset=") == -1)
  454. rv = -1;
  455. if (file_printf(ms, "%s", code_mime) == -1)
  456. rv = -1;
  457. }
  458. #if HAVE_FORK
  459. done_encoding:
  460. #endif
  461. free(rbuf);
  462. buffer_fini(&b);
  463. if (rv)
  464. return rv;
  465. return m;
  466. }
  467. #endif
  468. file_protected int
  469. file_reset(struct magic_set *ms, int checkloaded)
  470. {
  471. if (checkloaded && ms->mlist[0] == NULL) {
  472. file_error(ms, 0, "no magic files loaded");
  473. return -1;
  474. }
  475. file_clearbuf(ms);
  476. if (ms->o.pbuf) {
  477. free(ms->o.pbuf);
  478. ms->o.pbuf = NULL;
  479. }
  480. ms->event_flags &= ~EVENT_HAD_ERR;
  481. ms->error = -1;
  482. return 0;
  483. }
  484. #define OCTALIFY(n, o) \
  485. /*LINTED*/ \
  486. (void)(*(n)++ = '\\', \
  487. *(n)++ = ((CAST(uint32_t, *(o)) >> 6) & 3) + '0', \
  488. *(n)++ = ((CAST(uint32_t, *(o)) >> 3) & 7) + '0', \
  489. *(n)++ = ((CAST(uint32_t, *(o)) >> 0) & 7) + '0', \
  490. (o)++)
  491. file_protected const char *
  492. file_getbuffer(struct magic_set *ms)
  493. {
  494. char *pbuf, *op, *np;
  495. size_t psize, len;
  496. if (ms->event_flags & EVENT_HAD_ERR)
  497. return NULL;
  498. if (ms->flags & MAGIC_RAW)
  499. return ms->o.buf;
  500. if (ms->o.buf == NULL)
  501. return NULL;
  502. /* * 4 is for octal representation, + 1 is for NUL */
  503. len = strlen(ms->o.buf);
  504. if (len > (SIZE_MAX - 1) / 4) {
  505. file_oomem(ms, len);
  506. return NULL;
  507. }
  508. psize = len * 4 + 1;
  509. if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) {
  510. file_oomem(ms, psize);
  511. return NULL;
  512. }
  513. ms->o.pbuf = pbuf;
  514. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  515. {
  516. mbstate_t state;
  517. wchar_t nextchar;
  518. int mb_conv = 1;
  519. size_t bytesconsumed;
  520. char *eop;
  521. (void)memset(&state, 0, sizeof(mbstate_t));
  522. np = ms->o.pbuf;
  523. op = ms->o.buf;
  524. eop = op + len;
  525. while (op < eop) {
  526. bytesconsumed = mbrtowc(&nextchar, op,
  527. CAST(size_t, eop - op), &state);
  528. if (bytesconsumed == CAST(size_t, -1) ||
  529. bytesconsumed == CAST(size_t, -2)) {
  530. mb_conv = 0;
  531. break;
  532. }
  533. if (iswprint(nextchar)) {
  534. (void)memcpy(np, op, bytesconsumed);
  535. op += bytesconsumed;
  536. np += bytesconsumed;
  537. } else {
  538. while (bytesconsumed-- > 0)
  539. OCTALIFY(np, op);
  540. }
  541. }
  542. *np = '\0';
  543. /* Parsing succeeded as a multi-byte sequence */
  544. if (mb_conv != 0)
  545. return ms->o.pbuf;
  546. }
  547. #endif
  548. for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
  549. if (isprint(CAST(unsigned char, *op))) {
  550. *np++ = *op++;
  551. } else {
  552. OCTALIFY(np, op);
  553. }
  554. }
  555. *np = '\0';
  556. return ms->o.pbuf;
  557. }
  558. file_protected int
  559. file_check_mem(struct magic_set *ms, unsigned int level)
  560. {
  561. size_t len;
  562. if (level >= ms->c.len) {
  563. len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
  564. ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
  565. malloc(len) :
  566. realloc(ms->c.li, len));
  567. if (ms->c.li == NULL) {
  568. file_oomem(ms, len);
  569. return -1;
  570. }
  571. }
  572. ms->c.li[level].got_match = 0;
  573. #ifdef ENABLE_CONDITIONALS
  574. ms->c.li[level].last_match = 0;
  575. ms->c.li[level].last_cond = COND_NONE;
  576. #endif /* ENABLE_CONDITIONALS */
  577. return 0;
  578. }
  579. file_protected size_t
  580. file_printedlen(const struct magic_set *ms)
  581. {
  582. return ms->o.blen;
  583. }
  584. file_protected int
  585. file_replace(struct magic_set *ms, const char *pat, const char *rep)
  586. {
  587. file_regex_t rx;
  588. int rc, rv = -1;
  589. rc = file_regcomp(ms, &rx, pat, REG_EXTENDED);
  590. if (rc == 0) {
  591. regmatch_t rm;
  592. int nm = 0;
  593. while (file_regexec(ms, &rx, ms->o.buf, 1, &rm, 0) == 0) {
  594. ms->o.buf[rm.rm_so] = '\0';
  595. if (file_printf(ms, "%s%s", rep,
  596. rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1)
  597. goto out;
  598. nm++;
  599. }
  600. rv = nm;
  601. }
  602. out:
  603. file_regfree(&rx);
  604. return rv;
  605. }
  606. file_private int
  607. check_regex(struct magic_set *ms, const char *pat)
  608. {
  609. char sbuf[512];
  610. unsigned char oc = '\0';
  611. const char *p;
  612. unsigned long l;
  613. static const char wild[] = "?*+{";
  614. for (p = pat; *p; p++) {
  615. unsigned char c = *p;
  616. // Avoid repetition of wild characters
  617. if (strchr(wild, oc) != NULL && strchr(wild, c) != NULL) {
  618. size_t len = strlen(pat);
  619. file_magwarn(ms,
  620. "repetition-operator operand `%c%c' "
  621. "invalid in regex `%s'", oc, c,
  622. file_printable(ms, sbuf, sizeof(sbuf), pat, len));
  623. return -1;
  624. }
  625. if (c == '{') {
  626. char *ep, *eep;
  627. if (oc == '}') {
  628. file_magwarn(ms, "cascading repetition "
  629. "operators in regex `%s'", pat);
  630. return -1;
  631. }
  632. errno = 0;
  633. l = strtoul(p + 1, &ep, 10);
  634. if (ep != p + 1 && l > 1000)
  635. goto bounds;
  636. if (*ep == ',') {
  637. l = strtoul(ep + 1, &eep, 10);
  638. if (eep != ep + 1 && l > 1000)
  639. goto bounds;
  640. }
  641. }
  642. oc = c;
  643. if (isprint(c) || isspace(c) || c == '\b'
  644. || c == 0x8a) // XXX: apple magic fixme
  645. continue;
  646. size_t len = strlen(pat);
  647. file_magwarn(ms,
  648. "non-ascii characters in regex \\%#o `%s'",
  649. c, file_printable(ms, sbuf, sizeof(sbuf), pat, len));
  650. return -1;
  651. }
  652. return 0;
  653. bounds:
  654. file_magwarn(ms, "bounds too large %ld in regex `%s'", l, pat);
  655. return -1;
  656. }
  657. file_protected int
  658. file_regcomp(struct magic_set *ms file_locale_used, file_regex_t *rx,
  659. const char *pat, int flags)
  660. {
  661. if (check_regex(ms, pat) == -1)
  662. return -1;
  663. #ifdef USE_C_LOCALE
  664. locale_t old = uselocale(ms->c_lc_ctype);
  665. assert(old != NULL);
  666. #else
  667. char old[1024];
  668. strlcpy(old, setlocale(LC_CTYPE, NULL), sizeof(old));
  669. (void)setlocale(LC_CTYPE, "C");
  670. #endif
  671. int rc;
  672. rc = regcomp(rx, pat, flags);
  673. #ifdef USE_C_LOCALE
  674. uselocale(old);
  675. #else
  676. (void)setlocale(LC_CTYPE, old);
  677. #endif
  678. if (rc > 0 && (ms->flags & MAGIC_CHECK)) {
  679. char errmsg[512], buf[512];
  680. (void)regerror(rc, rx, errmsg, sizeof(errmsg));
  681. file_magerror(ms, "regex error %d for `%s', (%s)", rc,
  682. file_printable(ms, buf, sizeof(buf), pat, strlen(pat)),
  683. errmsg);
  684. }
  685. return rc;
  686. }
  687. /*ARGSUSED*/
  688. file_protected int
  689. file_regexec(struct magic_set *ms file_locale_used, file_regex_t *rx,
  690. const char *str, size_t nmatch, regmatch_t* pmatch, int eflags)
  691. {
  692. #ifdef USE_C_LOCALE
  693. locale_t old = uselocale(ms->c_lc_ctype);
  694. assert(old != NULL);
  695. #else
  696. char old[1024];
  697. strlcpy(old, setlocale(LC_CTYPE, NULL), sizeof(old));
  698. (void)setlocale(LC_CTYPE, "C");
  699. #endif
  700. int rc;
  701. /* XXX: force initialization because glibc does not always do this */
  702. if (nmatch != 0)
  703. memset(pmatch, 0, nmatch * sizeof(*pmatch));
  704. rc = regexec(rx, str, nmatch, pmatch, eflags);
  705. #ifdef USE_C_LOCALE
  706. uselocale(old);
  707. #else
  708. (void)setlocale(LC_CTYPE, old);
  709. #endif
  710. return rc;
  711. }
  712. file_protected void
  713. file_regfree(file_regex_t *rx)
  714. {
  715. regfree(rx);
  716. }
  717. file_protected file_pushbuf_t *
  718. file_push_buffer(struct magic_set *ms)
  719. {
  720. file_pushbuf_t *pb;
  721. if (ms->event_flags & EVENT_HAD_ERR)
  722. return NULL;
  723. if ((pb = (CAST(file_pushbuf_t *, malloc(sizeof(*pb))))) == NULL)
  724. return NULL;
  725. pb->buf = ms->o.buf;
  726. pb->blen = ms->o.blen;
  727. pb->offset = ms->offset;
  728. ms->o.buf = NULL;
  729. ms->o.blen = 0;
  730. ms->offset = 0;
  731. return pb;
  732. }
  733. file_protected char *
  734. file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
  735. {
  736. char *rbuf;
  737. if (ms->event_flags & EVENT_HAD_ERR) {
  738. free(pb->buf);
  739. free(pb);
  740. return NULL;
  741. }
  742. rbuf = ms->o.buf;
  743. ms->o.buf = pb->buf;
  744. ms->o.blen = pb->blen;
  745. ms->offset = pb->offset;
  746. free(pb);
  747. return rbuf;
  748. }
  749. /*
  750. * convert string to ascii printable format.
  751. */
  752. file_protected char *
  753. file_printable(struct magic_set *ms, char *buf, size_t bufsiz,
  754. const char *str, size_t slen)
  755. {
  756. char *ptr, *eptr = buf + bufsiz - 1;
  757. const unsigned char *s = RCAST(const unsigned char *, str);
  758. const unsigned char *es = s + slen;
  759. for (ptr = buf; ptr < eptr && s < es && *s; s++) {
  760. if ((ms->flags & MAGIC_RAW) != 0 || isprint(*s)) {
  761. *ptr++ = *s;
  762. continue;
  763. }
  764. if (ptr >= eptr - 3)
  765. break;
  766. *ptr++ = '\\';
  767. *ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
  768. *ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
  769. *ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
  770. }
  771. *ptr = '\0';
  772. return buf;
  773. }
  774. struct guid {
  775. uint32_t data1;
  776. uint16_t data2;
  777. uint16_t data3;
  778. uint8_t data4[8];
  779. };
  780. static char XDIGIT[] = "0123456789abcdef";
  781. static int
  782. atox(const uint8_t c)
  783. {
  784. uint8_t d = isupper(c) ? tolower(c) : c;
  785. const char *q = d ? strchr(XDIGIT, isupper(c) ? tolower(c) : c) : NULL;
  786. if (q == NULL)
  787. return -1;
  788. return q - XDIGIT;
  789. }
  790. static int
  791. getxvalue(void *p, const char *s, size_t n)
  792. {
  793. uint64_t v = 0;
  794. for (size_t i = 0; i < n; i++) {
  795. int x = atox(s[i]);
  796. if (x == -1)
  797. return 0;
  798. v = (v << 4) | x;
  799. }
  800. switch (n) {
  801. case 8:
  802. *(uint32_t *)p = v;
  803. return 1;
  804. case 4:
  805. *(uint16_t *)p = v;
  806. return 1;
  807. case 2:
  808. *(uint8_t *)p = v;
  809. return 1;
  810. default:
  811. return 0;
  812. }
  813. }
  814. file_protected int
  815. file_parse_guid(const char *s, uint64_t *guid)
  816. {
  817. struct guid *g = CAST(struct guid *, CAST(void *, guid));
  818. if (!getxvalue(&g->data1, s, 8) || s[8] != '-')
  819. return -1;
  820. s += 9;
  821. if (!getxvalue(&g->data2, s, 4) || s[4] != '-')
  822. return -1;
  823. s += 5;
  824. if (!getxvalue(&g->data3, s, 4) || s[4] != '-')
  825. return -1;
  826. s += 5;
  827. if (!getxvalue(&g->data4[0], s, 2) ||
  828. !getxvalue(&g->data4[1], s + 2, 2) || s[4] != '-')
  829. return -1;
  830. s += 5;
  831. if (!getxvalue(&g->data4[2], s, 2) ||
  832. !getxvalue(&g->data4[3], s + 2, 2) ||
  833. !getxvalue(&g->data4[4], s + 4, 2) ||
  834. !getxvalue(&g->data4[5], s + 6, 2) ||
  835. !getxvalue(&g->data4[6], s + 8, 2) ||
  836. !getxvalue(&g->data4[7], s + 10, 2))
  837. return -1;
  838. return 0;
  839. }
  840. file_protected int
  841. file_print_guid(char *str, size_t len, const uint64_t *guid)
  842. {
  843. const struct guid *g = CAST(const struct guid *,
  844. CAST(const void *, guid));
  845. #ifndef WIN32
  846. return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hhX%.2hhX-"
  847. "%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX",
  848. g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
  849. g->data4[2], g->data4[3], g->data4[4], g->data4[5],
  850. g->data4[6], g->data4[7]);
  851. #else
  852. return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hX%.2hX-"
  853. "%.2hX%.2hX%.2hX%.2hX%.2hX%.2hX",
  854. g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
  855. g->data4[2], g->data4[3], g->data4[4], g->data4[5],
  856. g->data4[6], g->data4[7]);
  857. #endif
  858. }
  859. file_protected int
  860. file_pipe_closexec(int *fds)
  861. {
  862. #ifdef __MINGW32__
  863. return 0;
  864. #elif defined(HAVE_PIPE2)
  865. return pipe2(fds, O_CLOEXEC);
  866. #else
  867. if (pipe(fds) == -1)
  868. return -1;
  869. # ifdef F_SETFD
  870. (void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
  871. (void)fcntl(fds[1], F_SETFD, FD_CLOEXEC);
  872. # endif
  873. return 0;
  874. #endif
  875. }
  876. file_protected int
  877. file_clear_closexec(int fd) {
  878. #ifdef F_SETFD
  879. return fcntl(fd, F_SETFD, 0);
  880. #else
  881. return 0;
  882. #endif
  883. }
  884. file_protected char *
  885. file_strtrim(char *str)
  886. {
  887. char *last;
  888. while (isspace(CAST(unsigned char, *str)))
  889. str++;
  890. last = str;
  891. while (*last)
  892. last++;
  893. --last;
  894. while (isspace(CAST(unsigned char, *last)))
  895. last--;
  896. *++last = '\0';
  897. return str;
  898. }