compress.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. * compress routines:
  30. * zmagic() - returns 0 if not recognized, uncompresses and prints
  31. * information if recognized
  32. * uncompress(method, old, n, newch) - uncompress old into new,
  33. * using method, return sizeof new
  34. */
  35. #include "file.h"
  36. #ifndef lint
  37. FILE_RCSID("@(#)$File: compress.c,v 1.158 2024/11/10 16:52:27 christos Exp $")
  38. #endif
  39. #include "magic.h"
  40. #include <stdlib.h>
  41. #ifdef HAVE_UNISTD_H
  42. #include <unistd.h>
  43. #endif
  44. #ifdef HAVE_SPAWN_H
  45. #include <spawn.h>
  46. #endif
  47. #include <stdio.h>
  48. #include <string.h>
  49. #include <errno.h>
  50. #include <ctype.h>
  51. #include <stdarg.h>
  52. #include <signal.h>
  53. #ifndef HAVE_SIG_T
  54. typedef void (*sig_t)(int);
  55. #endif /* HAVE_SIG_T */
  56. #ifdef HAVE_SYS_IOCTL_H
  57. #include <sys/ioctl.h>
  58. #endif
  59. #ifdef HAVE_SYS_WAIT_H
  60. #include <sys/wait.h>
  61. #endif
  62. #if defined(HAVE_SYS_TIME_H)
  63. #include <sys/time.h>
  64. #endif
  65. #if defined(HAVE_ZLIB_H) && defined(ZLIBSUPPORT)
  66. #define BUILTIN_DECOMPRESS
  67. #include <zlib.h>
  68. #endif
  69. #if defined(HAVE_BZLIB_H) && defined(BZLIBSUPPORT)
  70. #define BUILTIN_BZLIB
  71. #include <bzlib.h>
  72. #endif
  73. #if defined(HAVE_LZMA_H) && defined(XZLIBSUPPORT)
  74. #define BUILTIN_XZLIB
  75. #include <lzma.h>
  76. #endif
  77. #if defined(HAVE_ZSTD_H) && defined(ZSTDLIBSUPPORT)
  78. #define BUILTIN_ZSTDLIB
  79. #include <zstd.h>
  80. #include <zstd_errors.h>
  81. #endif
  82. #if defined(HAVE_LZLIB_H) && defined(LZLIBSUPPORT)
  83. #define BUILTIN_LZLIB
  84. #include <lzlib.h>
  85. #endif
  86. #ifdef notyet
  87. #if defined(HAVE_LRZIP_H) && defined(LRZIPLIBSUPPORT)
  88. #define BUILTIN_LRZIP
  89. #include <Lrzip.h>
  90. #endif
  91. #endif
  92. #ifdef DEBUG
  93. int tty = -1;
  94. #define DPRINTF(...) do { \
  95. if (tty == -1) \
  96. tty = open("/dev/tty", O_RDWR); \
  97. if (tty == -1) \
  98. abort(); \
  99. dprintf(tty, __VA_ARGS__); \
  100. } while (/*CONSTCOND*/0)
  101. #else
  102. #define DPRINTF(...)
  103. #endif
  104. #ifdef ZLIBSUPPORT
  105. /*
  106. * The following python code is not really used because ZLIBSUPPORT is only
  107. * defined if we have a built-in zlib, and the built-in zlib handles that.
  108. * That is not true for android where we have zlib.h and not -lz.
  109. */
  110. static const char zlibcode[] =
  111. "import sys, zlib; sys.stdout.write(zlib.decompress(sys.stdin.read()))";
  112. static const char *zlib_args[] = { "python", "-c", zlibcode, NULL };
  113. static int
  114. zlibcmp(const unsigned char *buf)
  115. {
  116. unsigned short x = 1;
  117. unsigned char *s = CAST(unsigned char *, CAST(void *, &x));
  118. if ((buf[0] & 0xf) != 8 || (buf[0] & 0x80) != 0)
  119. return 0;
  120. if (s[0] != 1) /* endianness test */
  121. x = buf[0] | (buf[1] << 8);
  122. else
  123. x = buf[1] | (buf[0] << 8);
  124. if (x % 31)
  125. return 0;
  126. return 1;
  127. }
  128. #endif
  129. static int
  130. lzmacmp(const unsigned char *buf)
  131. {
  132. if (buf[0] != 0x5d || buf[1] || buf[2])
  133. return 0;
  134. if (buf[12] && buf[12] != 0xff)
  135. return 0;
  136. return 1;
  137. }
  138. #define gzip_flags "-cd"
  139. #define lzip_flags gzip_flags
  140. static const char *gzip_args[] = {
  141. "gzip", gzip_flags, NULL
  142. };
  143. static const char *uncompress_args[] = {
  144. "uncompress", "-c", NULL
  145. };
  146. static const char *bzip2_args[] = {
  147. "bzip2", "-cd", NULL
  148. };
  149. static const char *lzip_args[] = {
  150. "lzip", lzip_flags, NULL
  151. };
  152. static const char *xz_args[] = {
  153. "xz", "-cd", NULL
  154. };
  155. static const char *lrzip_args[] = {
  156. "lrzip", "-qdf", "-", NULL
  157. };
  158. static const char *lz4_args[] = {
  159. "lz4", "-cd", NULL
  160. };
  161. static const char *zstd_args[] = {
  162. "zstd", "-cd", NULL
  163. };
  164. #define do_zlib NULL
  165. #define do_bzlib NULL
  166. file_private const struct {
  167. union {
  168. const char *magic;
  169. int (*func)(const unsigned char *);
  170. } u;
  171. int maglen;
  172. const char **argv;
  173. void *unused;
  174. } compr[] = {
  175. #define METH_FROZEN 2
  176. #define METH_BZIP 7
  177. #define METH_XZ 9
  178. #define METH_LZIP 8
  179. #define METH_LRZIP 10
  180. #define METH_ZSTD 12
  181. #define METH_LZMA 13
  182. #define METH_ZLIB 14
  183. { { .magic = "\037\235" }, 2, gzip_args, NULL }, /* 0, compressed */
  184. /* Uncompress can get stuck; so use gzip first if we have it
  185. * Idea from Damien Clark, thanks! */
  186. { { .magic = "\037\235" }, 2, uncompress_args, NULL },/* 1, compressed */
  187. { { .magic = "\037\213" }, 2, gzip_args, do_zlib },/* 2, gzipped */
  188. { { .magic = "\037\236" }, 2, gzip_args, NULL }, /* 3, frozen */
  189. { { .magic = "\037\240" }, 2, gzip_args, NULL }, /* 4, SCO LZH */
  190. /* the standard pack utilities do not accept standard input */
  191. { { .magic = "\037\036" }, 2, gzip_args, NULL }, /* 5, packed */
  192. { { .magic = "PK\3\4" }, 4, gzip_args, NULL }, /* 6, pkziped */
  193. /* ...only first file examined */
  194. { { .magic = "BZh" }, 3, bzip2_args, do_bzlib },/* 7, bzip2-ed */
  195. { { .magic = "LZIP" }, 4, lzip_args, NULL }, /* 8, lzip-ed */
  196. { { .magic = "\3757zXZ\0" },6, xz_args, NULL }, /* 9, XZ Util */
  197. { { .magic = "LRZI" }, 4, lrzip_args, NULL }, /* 10, LRZIP */
  198. { { .magic = "\004\"M\030" },4, lz4_args, NULL }, /* 11, LZ4 */
  199. { { .magic = "\x28\xB5\x2F\xFD" }, 4, zstd_args, NULL },/* 12, zstd */
  200. { { .func = lzmacmp }, -13, xz_args, NULL }, /* 13, lzma */
  201. #ifdef ZLIBSUPPORT
  202. { { .func = zlibcmp }, -2, zlib_args, NULL }, /* 14, zlib */
  203. #endif
  204. };
  205. #define OKDATA 0
  206. #define NODATA 1
  207. #define ERRDATA 2
  208. file_private ssize_t swrite(int, const void *, size_t);
  209. #if HAVE_FORK
  210. file_private size_t ncompr = __arraycount(compr);
  211. file_private int uncompressbuf(int, size_t, size_t, int, const unsigned char *,
  212. unsigned char **, size_t *);
  213. #ifdef BUILTIN_DECOMPRESS
  214. file_private int uncompresszlib(const unsigned char *, unsigned char **, size_t,
  215. size_t *, int);
  216. file_private int uncompressgzipped(const unsigned char *, unsigned char **, size_t,
  217. size_t *, int);
  218. #endif
  219. #ifdef BUILTIN_BZLIB
  220. file_private int uncompressbzlib(const unsigned char *, unsigned char **, size_t,
  221. size_t *, int);
  222. #endif
  223. #ifdef BUILTIN_XZLIB
  224. file_private int uncompressxzlib(const unsigned char *, unsigned char **, size_t,
  225. size_t *, int);
  226. #endif
  227. #ifdef BUILTIN_ZSTDLIB
  228. file_private int uncompresszstd(const unsigned char *, unsigned char **, size_t,
  229. size_t *, int);
  230. #endif
  231. #ifdef BUILTIN_LZLIB
  232. file_private int uncompresslzlib(const unsigned char *, unsigned char **, size_t,
  233. size_t *, int);
  234. #endif
  235. #ifdef BUILTIN_LRZIP
  236. file_private int uncompresslrzip(const unsigned char *, unsigned char **, size_t,
  237. size_t *, int);
  238. #endif
  239. static int makeerror(unsigned char **, size_t *, const char *, ...)
  240. __attribute__((__format__(__printf__, 3, 4)));
  241. file_private const char *methodname(size_t);
  242. file_private int
  243. format_decompression_error(struct magic_set *ms, size_t i, unsigned char *buf)
  244. {
  245. unsigned char *p;
  246. int mime = ms->flags & MAGIC_MIME;
  247. if (!mime)
  248. return file_printf(ms, "ERROR:[%s: %s]", methodname(i), buf);
  249. for (p = buf; *p; p++)
  250. if (!isalnum(*p))
  251. *p = '-';
  252. return file_printf(ms, "application/x-decompression-error-%s-%s",
  253. methodname(i), buf);
  254. }
  255. file_protected int
  256. file_zmagic(struct magic_set *ms, const struct buffer *b, const char *name)
  257. {
  258. unsigned char *newbuf = NULL;
  259. size_t i, nsz;
  260. char *rbuf;
  261. file_pushbuf_t *pb;
  262. int urv, prv, rv = 0;
  263. int mime = ms->flags & MAGIC_MIME;
  264. int fd = b->fd;
  265. const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
  266. size_t nbytes = b->flen;
  267. int sa_saved = 0;
  268. struct sigaction sig_act;
  269. if ((ms->flags & MAGIC_COMPRESS) == 0)
  270. return 0;
  271. for (i = 0; i < ncompr; i++) {
  272. int zm;
  273. if (nbytes < CAST(size_t, abs(compr[i].maglen)))
  274. continue;
  275. if (compr[i].maglen < 0) {
  276. zm = (*compr[i].u.func)(buf);
  277. } else {
  278. zm = memcmp(buf, compr[i].u.magic,
  279. CAST(size_t, compr[i].maglen)) == 0;
  280. }
  281. if (!zm)
  282. continue;
  283. /* Prevent SIGPIPE death if child dies unexpectedly */
  284. if (!sa_saved) {
  285. //We can use sig_act for both new and old, but
  286. struct sigaction new_act;
  287. memset(&new_act, 0, sizeof(new_act));
  288. new_act.sa_handler = SIG_IGN;
  289. sa_saved = sigaction(SIGPIPE, &new_act, &sig_act) != -1;
  290. }
  291. nsz = nbytes;
  292. free(newbuf);
  293. urv = uncompressbuf(fd, ms->bytes_max, i,
  294. (ms->flags & MAGIC_NO_COMPRESS_FORK), buf, &newbuf, &nsz);
  295. DPRINTF("uncompressbuf = %d, %s, %" SIZE_T_FORMAT "u\n", urv,
  296. (char *)newbuf, nsz);
  297. switch (urv) {
  298. case OKDATA:
  299. case ERRDATA:
  300. ms->flags &= ~MAGIC_COMPRESS;
  301. if (urv == ERRDATA)
  302. prv = format_decompression_error(ms, i, newbuf);
  303. else
  304. prv = file_buffer(ms, -1, NULL, name, newbuf,
  305. nsz);
  306. if (prv == -1)
  307. goto error;
  308. rv = 1;
  309. if ((ms->flags & MAGIC_COMPRESS_TRANSP) != 0)
  310. goto out;
  311. if (mime != MAGIC_MIME && mime != 0)
  312. goto out;
  313. if ((file_printf(ms,
  314. mime ? " compressed-encoding=" : " (")) == -1)
  315. goto error;
  316. if ((pb = file_push_buffer(ms)) == NULL)
  317. goto error;
  318. /*
  319. * XXX: If file_buffer fails here, we overwrite
  320. * the compressed text. FIXME.
  321. */
  322. if (file_buffer(ms, -1, NULL, NULL, buf, nbytes) == -1)
  323. {
  324. if (file_pop_buffer(ms, pb) != NULL)
  325. abort();
  326. goto error;
  327. }
  328. if ((rbuf = file_pop_buffer(ms, pb)) != NULL) {
  329. if (file_printf(ms, "%s", rbuf) == -1) {
  330. free(rbuf);
  331. goto error;
  332. }
  333. free(rbuf);
  334. }
  335. if (!mime && file_printf(ms, ")") == -1)
  336. goto error;
  337. /*FALLTHROUGH*/
  338. case NODATA:
  339. break;
  340. default:
  341. abort();
  342. /*NOTREACHED*/
  343. error:
  344. rv = -1;
  345. break;
  346. }
  347. }
  348. out:
  349. DPRINTF("rv = %d\n", rv);
  350. if (sa_saved && sig_act.sa_handler != SIG_IGN)
  351. (void)sigaction(SIGPIPE, &sig_act, NULL);
  352. free(newbuf);
  353. ms->flags |= MAGIC_COMPRESS;
  354. DPRINTF("Zmagic returns %d\n", rv);
  355. return rv;
  356. }
  357. #endif
  358. /*
  359. * `safe' write for sockets and pipes.
  360. */
  361. file_private ssize_t
  362. swrite(int fd, const void *buf, size_t n)
  363. {
  364. ssize_t rv;
  365. size_t rn = n;
  366. do
  367. switch (rv = write(fd, buf, n)) {
  368. case -1:
  369. if (errno == EINTR)
  370. continue;
  371. return -1;
  372. default:
  373. n -= rv;
  374. buf = CAST(const char *, buf) + rv;
  375. break;
  376. }
  377. while (n > 0);
  378. return rn;
  379. }
  380. /*
  381. * `safe' read for sockets and pipes.
  382. */
  383. file_protected ssize_t
  384. sread(int fd, void *buf, size_t n, int canbepipe __attribute__((__unused__)))
  385. {
  386. ssize_t rv;
  387. #if defined(FIONREAD) && !defined(__MINGW32__)
  388. int t = 0;
  389. #endif
  390. size_t rn = n;
  391. if (fd == STDIN_FILENO)
  392. goto nocheck;
  393. #if defined(FIONREAD) && !defined(__MINGW32__)
  394. if (canbepipe && (ioctl(fd, FIONREAD, &t) == -1 || t == 0)) {
  395. #ifdef FD_ZERO
  396. ssize_t cnt;
  397. for (cnt = 0;; cnt++) {
  398. fd_set check;
  399. struct timeval tout = {0, 100 * 1000};
  400. int selrv;
  401. FD_ZERO(&check);
  402. FD_SET(fd, &check);
  403. /*
  404. * Avoid soft deadlock: do not read if there
  405. * is nothing to read from sockets and pipes.
  406. */
  407. selrv = select(fd + 1, &check, NULL, NULL, &tout);
  408. if (selrv == -1) {
  409. if (errno == EINTR || errno == EAGAIN)
  410. continue;
  411. } else if (selrv == 0 && cnt >= 5) {
  412. return 0;
  413. } else
  414. break;
  415. }
  416. #endif
  417. (void)ioctl(fd, FIONREAD, &t);
  418. }
  419. if (t > 0 && CAST(size_t, t) < n) {
  420. n = t;
  421. rn = n;
  422. }
  423. #endif
  424. nocheck:
  425. do
  426. switch ((rv = read(fd, buf, n))) {
  427. case -1:
  428. if (errno == EINTR)
  429. continue;
  430. return -1;
  431. case 0:
  432. return rn - n;
  433. default:
  434. n -= rv;
  435. buf = CAST(char *, CCAST(void *, buf)) + rv;
  436. break;
  437. }
  438. while (n > 0);
  439. return rn;
  440. }
  441. file_protected int
  442. file_pipe2file(struct magic_set *ms, int fd, const void *startbuf,
  443. size_t nbytes)
  444. {
  445. char buf[4096];
  446. ssize_t r;
  447. int tfd;
  448. #ifdef WIN32
  449. const char *t;
  450. buf[0] = '\0';
  451. if ((t = getenv("TEMP")) != NULL)
  452. (void)strlcpy(buf, t, sizeof(buf));
  453. else if ((t = getenv("TMP")) != NULL)
  454. (void)strlcpy(buf, t, sizeof(buf));
  455. else if ((t = getenv("TMPDIR")) != NULL)
  456. (void)strlcpy(buf, t, sizeof(buf));
  457. if (buf[0] != '\0')
  458. (void)strlcat(buf, "/", sizeof(buf));
  459. (void)strlcat(buf, "file.XXXXXX", sizeof(buf));
  460. #else
  461. (void)strlcpy(buf, "/tmp/file.XXXXXX", sizeof(buf));
  462. #endif
  463. #ifndef HAVE_MKSTEMP
  464. {
  465. char *ptr = mktemp(buf);
  466. tfd = open(ptr, O_RDWR|O_TRUNC|O_EXCL|O_CREAT, 0600);
  467. r = errno;
  468. (void)unlink(ptr);
  469. errno = r;
  470. }
  471. #else
  472. {
  473. int te;
  474. mode_t ou = umask(0);
  475. tfd = mkstemp(buf);
  476. (void)umask(ou);
  477. te = errno;
  478. (void)unlink(buf);
  479. errno = te;
  480. }
  481. #endif
  482. if (tfd == -1) {
  483. file_error(ms, errno,
  484. "cannot create temporary file for pipe copy");
  485. return -1;
  486. }
  487. if (swrite(tfd, startbuf, nbytes) != CAST(ssize_t, nbytes))
  488. r = 1;
  489. else {
  490. while ((r = sread(fd, buf, sizeof(buf), 1)) > 0)
  491. if (swrite(tfd, buf, CAST(size_t, r)) != r)
  492. break;
  493. }
  494. switch (r) {
  495. case -1:
  496. file_error(ms, errno, "error copying from pipe to temp file");
  497. return -1;
  498. case 0:
  499. break;
  500. default:
  501. file_error(ms, errno, "error while writing to temp file");
  502. return -1;
  503. }
  504. /*
  505. * We duplicate the file descriptor, because fclose on a
  506. * tmpfile will delete the file, but any open descriptors
  507. * can still access the phantom inode.
  508. */
  509. if ((fd = dup2(tfd, fd)) == -1) {
  510. file_error(ms, errno, "could not dup descriptor for temp file");
  511. return -1;
  512. }
  513. (void)close(tfd);
  514. if (lseek(fd, CAST(off_t, 0), SEEK_SET) == CAST(off_t, -1)) {
  515. file_badseek(ms);
  516. return -1;
  517. }
  518. return fd;
  519. }
  520. #if HAVE_FORK
  521. #ifdef BUILTIN_DECOMPRESS
  522. #define FHCRC (1 << 1)
  523. #define FEXTRA (1 << 2)
  524. #define FNAME (1 << 3)
  525. #define FCOMMENT (1 << 4)
  526. file_private int
  527. uncompressgzipped(const unsigned char *old, unsigned char **newch,
  528. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  529. {
  530. unsigned char flg;
  531. size_t data_start = 10;
  532. if (*n < 4) {
  533. goto err;
  534. }
  535. flg = old[3];
  536. if (flg & FEXTRA) {
  537. if (data_start + 1 >= *n)
  538. goto err;
  539. data_start += 2 + old[data_start] + old[data_start + 1] * 256;
  540. }
  541. if (flg & FNAME) {
  542. while(data_start < *n && old[data_start])
  543. data_start++;
  544. data_start++;
  545. }
  546. if (flg & FCOMMENT) {
  547. while(data_start < *n && old[data_start])
  548. data_start++;
  549. data_start++;
  550. }
  551. if (flg & FHCRC)
  552. data_start += 2;
  553. if (data_start >= *n)
  554. goto err;
  555. *n -= data_start;
  556. old += data_start;
  557. return uncompresszlib(old, newch, bytes_max, n, 0);
  558. err:
  559. return makeerror(newch, n, "File too short");
  560. }
  561. file_private int
  562. uncompresszlib(const unsigned char *old, unsigned char **newch,
  563. size_t bytes_max, size_t *n, int zlib)
  564. {
  565. int rc;
  566. z_stream z;
  567. DPRINTF("builtin zlib decompression\n");
  568. z.next_in = CCAST(Bytef *, old);
  569. z.avail_in = CAST(uint32_t, *n);
  570. z.next_out = *newch;
  571. z.avail_out = CAST(unsigned int, bytes_max);
  572. z.zalloc = Z_NULL;
  573. z.zfree = Z_NULL;
  574. z.opaque = Z_NULL;
  575. /* LINTED bug in header macro */
  576. rc = zlib ? inflateInit(&z) : inflateInit2(&z, -15);
  577. if (rc != Z_OK)
  578. goto err;
  579. rc = inflate(&z, Z_SYNC_FLUSH);
  580. if (rc != Z_OK && rc != Z_STREAM_END) {
  581. inflateEnd(&z);
  582. goto err;
  583. }
  584. *n = CAST(size_t, z.total_out);
  585. rc = inflateEnd(&z);
  586. if (rc != Z_OK)
  587. goto err;
  588. /* let's keep the nul-terminate tradition */
  589. (*newch)[*n] = '\0';
  590. return OKDATA;
  591. err:
  592. return makeerror(newch, n, "%s", z.msg ? z.msg : zError(rc));
  593. }
  594. #endif
  595. #ifdef BUILTIN_BZLIB
  596. file_private int
  597. uncompressbzlib(const unsigned char *old, unsigned char **newch,
  598. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  599. {
  600. int rc;
  601. bz_stream bz;
  602. DPRINTF("builtin bzlib decompression\n");
  603. memset(&bz, 0, sizeof(bz));
  604. rc = BZ2_bzDecompressInit(&bz, 0, 0);
  605. if (rc != BZ_OK)
  606. goto err;
  607. bz.next_in = CCAST(char *, RCAST(const char *, old));
  608. bz.avail_in = CAST(uint32_t, *n);
  609. bz.next_out = RCAST(char *, *newch);
  610. bz.avail_out = CAST(unsigned int, bytes_max);
  611. rc = BZ2_bzDecompress(&bz);
  612. if (rc != BZ_OK && rc != BZ_STREAM_END) {
  613. BZ2_bzDecompressEnd(&bz);
  614. goto err;
  615. }
  616. /* Assume byte_max is within 32bit */
  617. /* assert(bz.total_out_hi32 == 0); */
  618. *n = CAST(size_t, bz.total_out_lo32);
  619. rc = BZ2_bzDecompressEnd(&bz);
  620. if (rc != BZ_OK)
  621. goto err;
  622. /* let's keep the nul-terminate tradition */
  623. (*newch)[*n] = '\0';
  624. return OKDATA;
  625. err:
  626. return makeerror(newch, n, "bunzip error %d", rc);
  627. }
  628. #endif
  629. #ifdef BUILTIN_XZLIB
  630. file_private int
  631. uncompressxzlib(const unsigned char *old, unsigned char **newch,
  632. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  633. {
  634. int rc;
  635. lzma_stream xz;
  636. DPRINTF("builtin xzlib decompression\n");
  637. memset(&xz, 0, sizeof(xz));
  638. rc = lzma_auto_decoder(&xz, UINT64_MAX, 0);
  639. if (rc != LZMA_OK)
  640. goto err;
  641. xz.next_in = CCAST(const uint8_t *, old);
  642. xz.avail_in = CAST(uint32_t, *n);
  643. xz.next_out = RCAST(uint8_t *, *newch);
  644. xz.avail_out = CAST(unsigned int, bytes_max);
  645. rc = lzma_code(&xz, LZMA_RUN);
  646. if (rc != LZMA_OK && rc != LZMA_STREAM_END) {
  647. lzma_end(&xz);
  648. goto err;
  649. }
  650. *n = CAST(size_t, xz.total_out);
  651. lzma_end(&xz);
  652. /* let's keep the nul-terminate tradition */
  653. (*newch)[*n] = '\0';
  654. return OKDATA;
  655. err:
  656. return makeerror(newch, n, "unxz error %d", rc);
  657. }
  658. #endif
  659. #ifdef BUILTIN_ZSTDLIB
  660. file_private int
  661. uncompresszstd(const unsigned char *old, unsigned char **newch,
  662. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  663. {
  664. size_t rc;
  665. ZSTD_DStream *zstd;
  666. ZSTD_inBuffer in;
  667. ZSTD_outBuffer out;
  668. DPRINTF("builtin zstd decompression\n");
  669. if ((zstd = ZSTD_createDStream()) == NULL) {
  670. return makeerror(newch, n, "No ZSTD decompression stream, %s",
  671. strerror(errno));
  672. }
  673. rc = ZSTD_DCtx_reset(zstd, ZSTD_reset_session_only);
  674. if (ZSTD_isError(rc))
  675. goto err;
  676. in.src = CCAST(const void *, old);
  677. in.size = *n;
  678. in.pos = 0;
  679. out.dst = RCAST(void *, *newch);
  680. out.size = bytes_max;
  681. out.pos = 0;
  682. rc = ZSTD_decompressStream(zstd, &out, &in);
  683. if (ZSTD_isError(rc))
  684. goto err;
  685. *n = out.pos;
  686. ZSTD_freeDStream(zstd);
  687. /* let's keep the nul-terminate tradition */
  688. (*newch)[*n] = '\0';
  689. return OKDATA;
  690. err:
  691. ZSTD_freeDStream(zstd);
  692. return makeerror(newch, n, "zstd error %d", ZSTD_getErrorCode(rc));
  693. }
  694. #endif
  695. #ifdef BUILTIN_LZLIB
  696. file_private int
  697. uncompresslzlib(const unsigned char *old, unsigned char **newch,
  698. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  699. {
  700. enum LZ_Errno err;
  701. size_t old_remaining = *n;
  702. size_t new_remaining = bytes_max;
  703. size_t total_read = 0;
  704. unsigned char *bufp;
  705. struct LZ_Decoder *dec;
  706. bufp = *newch;
  707. DPRINTF("builtin lzlib decompression\n");
  708. dec = LZ_decompress_open();
  709. if (!dec) {
  710. return makeerror(newch, n, "unable to allocate LZ_Decoder");
  711. }
  712. if (LZ_decompress_errno(dec) != LZ_ok)
  713. goto err;
  714. for (;;) {
  715. // LZ_decompress_read() stops at member boundaries, so we may
  716. // have more than one successful read after writing all data
  717. // we have.
  718. if (old_remaining > 0) {
  719. int wr = LZ_decompress_write(dec, old, old_remaining);
  720. if (wr < 0)
  721. goto err;
  722. old_remaining -= wr;
  723. old += wr;
  724. }
  725. int rd = LZ_decompress_read(dec, bufp, new_remaining);
  726. if (rd > 0) {
  727. new_remaining -= rd;
  728. bufp += rd;
  729. total_read += rd;
  730. }
  731. if (rd < 0 || LZ_decompress_errno(dec) != LZ_ok)
  732. goto err;
  733. if (new_remaining == 0)
  734. break;
  735. if (old_remaining == 0 && rd == 0)
  736. break;
  737. }
  738. LZ_decompress_close(dec);
  739. *n = total_read;
  740. /* let's keep the nul-terminate tradition */
  741. *bufp = '\0';
  742. return OKDATA;
  743. err:
  744. err = LZ_decompress_errno(dec);
  745. LZ_decompress_close(dec);
  746. return makeerror(newch, n, "lzlib error: %s", LZ_strerror(err));
  747. }
  748. #endif
  749. #ifdef BUILTIN_LRZIP
  750. file_private int
  751. uncompresslrzip(const unsigned char *old, unsigned char **newch,
  752. size_t bytes_max, size_t *n, int extra __attribute__((__unused__)))
  753. {
  754. Lrzip *lr;
  755. FILE *in, *out;
  756. int res = OKDATA;
  757. DPRINTF("builtin rlzip decompression\n");
  758. lr = lrzip_new(LRZIP_MODE_DECOMPRESS);
  759. if (lr == NULL) {
  760. res = makeerror(newch, n, "unable to create an lrzip decoder");
  761. goto out0;
  762. }
  763. lrzip_config_env(lr);
  764. in = fmemopen(RCAST(void *, old), bytes_max, "r");
  765. if (in == NULL) {
  766. res = makeerror(newch, n, "unable to construct input file");
  767. goto out1;
  768. }
  769. if (!lrzip_file_add(lr, in)) {
  770. res = makeerror(newch, n, "unable to add input file");
  771. goto out2;
  772. }
  773. *newch = calloc(*n = 2 * bytes_max, 1);
  774. if (*newch == NULL) {
  775. res = makeerror(newch, n, "unable to allocate output buffer");
  776. goto out2;
  777. }
  778. out = fmemopen(*newch, *n, "w");
  779. if (out == NULL) {
  780. free(*newch);
  781. res = makeerror(newch, n, "unable to allocate output file");
  782. goto out2;
  783. }
  784. lrzip_outfile_set(lr, out);
  785. if (lrzip_run(lr)) {
  786. free(*newch);
  787. res = makeerror(newch, n, "unable to decompress file");
  788. goto out3;
  789. }
  790. *n = (size_t)ftell(out);
  791. out3:
  792. fclose(out);
  793. out2:
  794. fclose(in);
  795. out1:
  796. lrzip_free(lr);
  797. out0:
  798. return res;
  799. }
  800. #endif
  801. static int
  802. makeerror(unsigned char **buf, size_t *len, const char *fmt, ...)
  803. {
  804. char *msg;
  805. va_list ap;
  806. int rv;
  807. DPRINTF("Makeerror %s\n", fmt);
  808. free(*buf);
  809. va_start(ap, fmt);
  810. rv = vasprintf(&msg, fmt, ap);
  811. va_end(ap);
  812. if (rv < 0) {
  813. DPRINTF("Makeerror failed");
  814. *buf = NULL;
  815. *len = 0;
  816. return NODATA;
  817. }
  818. *buf = RCAST(unsigned char *, msg);
  819. *len = strlen(msg);
  820. return ERRDATA;
  821. }
  822. static void
  823. closefd(int *fd, size_t i)
  824. {
  825. if (fd[i] == -1)
  826. return;
  827. (void) close(fd[i]);
  828. fd[i] = -1;
  829. }
  830. static void
  831. closep(int *fd)
  832. {
  833. size_t i;
  834. for (i = 0; i < 2; i++)
  835. closefd(fd, i);
  836. }
  837. static void
  838. movedesc(void *v, int i, int fd)
  839. {
  840. if (fd == i)
  841. return; /* "no dup was necessary" */
  842. #ifdef HAVE_POSIX_SPAWNP
  843. posix_spawn_file_actions_t *fa = RCAST(posix_spawn_file_actions_t *, v);
  844. posix_spawn_file_actions_adddup2(fa, fd, i);
  845. posix_spawn_file_actions_addclose(fa, fd);
  846. #else
  847. if (dup2(fd, i) == -1) {
  848. DPRINTF("dup(%d, %d) failed (%s)\n", fd, i, strerror(errno));
  849. exit(EXIT_FAILURE);
  850. }
  851. close(v ? fd : fd);
  852. #endif
  853. }
  854. static void
  855. closedesc(void *v, int fd)
  856. {
  857. #ifdef HAVE_POSIX_SPAWNP
  858. posix_spawn_file_actions_t *fa = RCAST(posix_spawn_file_actions_t *, v);
  859. posix_spawn_file_actions_addclose(fa, fd);
  860. #else
  861. close(v ? fd : fd);
  862. #endif
  863. }
  864. static void
  865. handledesc(void *v, int fd, int fdp[3][2])
  866. {
  867. if (fd != -1) {
  868. (void) lseek(fd, CAST(off_t, 0), SEEK_SET);
  869. movedesc(v, STDIN_FILENO, fd);
  870. } else {
  871. movedesc(v, STDIN_FILENO, fdp[STDIN_FILENO][0]);
  872. if (fdp[STDIN_FILENO][1] > 2)
  873. closedesc(v, fdp[STDIN_FILENO][1]);
  874. }
  875. file_clear_closexec(STDIN_FILENO);
  876. ///FIXME: if one of the fdp[i][j] is 0 or 1, this can bomb spectacularly
  877. movedesc(v, STDOUT_FILENO, fdp[STDOUT_FILENO][1]);
  878. if (fdp[STDOUT_FILENO][0] > 2)
  879. closedesc(v, fdp[STDOUT_FILENO][0]);
  880. file_clear_closexec(STDOUT_FILENO);
  881. movedesc(v, STDERR_FILENO, fdp[STDERR_FILENO][1]);
  882. if (fdp[STDERR_FILENO][0] > 2)
  883. closedesc(v, fdp[STDERR_FILENO][0]);
  884. file_clear_closexec(STDERR_FILENO);
  885. }
  886. static pid_t
  887. writechild(int fd, const void *old, size_t n)
  888. {
  889. pid_t pid;
  890. /*
  891. * fork again, to avoid blocking because both
  892. * pipes filled
  893. */
  894. pid = fork();
  895. if (pid == -1) {
  896. DPRINTF("Fork failed (%s)\n", strerror(errno));
  897. return -1;
  898. }
  899. if (pid == 0) {
  900. /* child */
  901. if (swrite(fd, old, n) != CAST(ssize_t, n)) {
  902. DPRINTF("Write failed (%s)\n", strerror(errno));
  903. exit(EXIT_FAILURE);
  904. }
  905. exit(EXIT_SUCCESS);
  906. }
  907. /* parent */
  908. return pid;
  909. }
  910. static ssize_t
  911. filter_error(unsigned char *ubuf, ssize_t n)
  912. {
  913. char *p;
  914. char *buf;
  915. ubuf[n] = '\0';
  916. buf = RCAST(char *, ubuf);
  917. while (isspace(CAST(unsigned char, *buf)))
  918. buf++;
  919. DPRINTF("Filter error[[[%s]]]\n", buf);
  920. if ((p = strchr(CAST(char *, buf), '\n')) != NULL)
  921. *p = '\0';
  922. if ((p = strchr(CAST(char *, buf), ';')) != NULL)
  923. *p = '\0';
  924. if ((p = strrchr(CAST(char *, buf), ':')) != NULL) {
  925. ++p;
  926. while (isspace(CAST(unsigned char, *p)))
  927. p++;
  928. n = strlen(p);
  929. memmove(ubuf, p, CAST(size_t, n + 1));
  930. }
  931. DPRINTF("Filter error after[[[%s]]]\n", (char *)ubuf);
  932. if (islower(*ubuf))
  933. *ubuf = toupper(*ubuf);
  934. return n;
  935. }
  936. file_private const char *
  937. methodname(size_t method)
  938. {
  939. switch (method) {
  940. #ifdef BUILTIN_DECOMPRESS
  941. case METH_FROZEN:
  942. case METH_ZLIB:
  943. return "zlib";
  944. #endif
  945. #ifdef BUILTIN_BZLIB
  946. case METH_BZIP:
  947. return "bzlib";
  948. #endif
  949. #ifdef BUILTIN_XZLIB
  950. case METH_XZ:
  951. case METH_LZMA:
  952. return "xzlib";
  953. #endif
  954. #ifdef BUILTIN_ZSTDLIB
  955. case METH_ZSTD:
  956. return "zstd";
  957. #endif
  958. #ifdef BUILTIN_LZLIB
  959. case METH_LZIP:
  960. return "lzlib";
  961. #endif
  962. #ifdef BUILTIN_LRZIP
  963. case METH_LRZIP:
  964. return "lrzip";
  965. #endif
  966. default:
  967. return compr[method].argv[0];
  968. }
  969. }
  970. file_private int (*
  971. getdecompressor(size_t method))(const unsigned char *, unsigned char **, size_t,
  972. size_t *, int)
  973. {
  974. switch (method) {
  975. #ifdef BUILTIN_DECOMPRESS
  976. case METH_FROZEN:
  977. return uncompressgzipped;
  978. case METH_ZLIB:
  979. return uncompresszlib;
  980. #endif
  981. #ifdef BUILTIN_BZLIB
  982. case METH_BZIP:
  983. return uncompressbzlib;
  984. #endif
  985. #ifdef BUILTIN_XZLIB
  986. case METH_XZ:
  987. case METH_LZMA:
  988. return uncompressxzlib;
  989. #endif
  990. #ifdef BUILTIN_ZSTDLIB
  991. case METH_ZSTD:
  992. return uncompresszstd;
  993. #endif
  994. #ifdef BUILTIN_LZLIB
  995. case METH_LZIP:
  996. return uncompresslzlib;
  997. #endif
  998. #ifdef BUILTIN_LRZIP
  999. case METH_LRZIP:
  1000. return uncompresslrzip;
  1001. #endif
  1002. default:
  1003. return NULL;
  1004. }
  1005. }
  1006. file_private int
  1007. uncompressbuf(int fd, size_t bytes_max, size_t method, int nofork,
  1008. const unsigned char *old, unsigned char **newch, size_t* n)
  1009. {
  1010. int fdp[3][2];
  1011. int status, rv, w;
  1012. pid_t pid;
  1013. pid_t writepid = -1;
  1014. size_t i;
  1015. ssize_t r, re;
  1016. char *const *args;
  1017. #ifdef HAVE_POSIX_SPAWNP
  1018. posix_spawn_file_actions_t fa;
  1019. #endif
  1020. int (*decompress)(const unsigned char *, unsigned char **,
  1021. size_t, size_t *, int) = getdecompressor(method);
  1022. *newch = CAST(unsigned char *, malloc(bytes_max + 1));
  1023. if (*newch == NULL)
  1024. return makeerror(newch, n, "No buffer, %s", strerror(errno));
  1025. if (decompress) {
  1026. if (nofork) {
  1027. return makeerror(newch, n,
  1028. "Fork is required to uncompress, but disabled");
  1029. }
  1030. return (*decompress)(old, newch, bytes_max, n, 1);
  1031. }
  1032. (void)fflush(stdout);
  1033. (void)fflush(stderr);
  1034. for (i = 0; i < __arraycount(fdp); i++)
  1035. fdp[i][0] = fdp[i][1] = -1;
  1036. /*
  1037. * There are multithreaded users who run magic_file()
  1038. * from dozens of threads. If two parallel magic_file() calls
  1039. * analyze two large compressed files, both will spawn
  1040. * an uncompressing child here, which writes out uncompressed data.
  1041. * We read some portion, then close the pipe, then waitpid() the child.
  1042. * If uncompressed data is larger, child should get EPIPE and exit.
  1043. * However, with *parallel* calls OTHER child may unintentionally
  1044. * inherit pipe fds, thus keeping pipe open and making writes in
  1045. * our child block instead of failing with EPIPE!
  1046. * (For the bug to occur, two threads must mutually inherit their pipes,
  1047. * and both must have large outputs. Thus it happens not that often).
  1048. * To avoid this, be sure to create pipes with O_CLOEXEC.
  1049. */
  1050. if ((fd == -1 && file_pipe_closexec(fdp[STDIN_FILENO]) == -1) ||
  1051. file_pipe_closexec(fdp[STDOUT_FILENO]) == -1 ||
  1052. file_pipe_closexec(fdp[STDERR_FILENO]) == -1) {
  1053. closep(fdp[STDIN_FILENO]);
  1054. closep(fdp[STDOUT_FILENO]);
  1055. return makeerror(newch, n, "Cannot create pipe, %s",
  1056. strerror(errno));
  1057. }
  1058. args = RCAST(char *const *, RCAST(intptr_t, compr[method].argv));
  1059. #ifdef HAVE_POSIX_SPAWNP
  1060. posix_spawn_file_actions_init(&fa);
  1061. handledesc(&fa, fd, fdp);
  1062. DPRINTF("Executing %s\n", compr[method].argv[0]);
  1063. status = posix_spawnp(&pid, compr[method].argv[0], &fa, NULL,
  1064. args, NULL);
  1065. posix_spawn_file_actions_destroy(&fa);
  1066. if (status == -1) {
  1067. return makeerror(newch, n, "Cannot posix_spawn `%s', %s",
  1068. compr[method].argv[0], strerror(errno));
  1069. }
  1070. #else
  1071. /* For processes with large mapped virtual sizes, vfork
  1072. * may be _much_ faster (10-100 times) than fork.
  1073. */
  1074. pid = vfork();
  1075. if (pid == -1) {
  1076. return makeerror(newch, n, "Cannot vfork, %s",
  1077. strerror(errno));
  1078. }
  1079. if (pid == 0) {
  1080. /* child */
  1081. /* Note: we are after vfork, do not modify memory
  1082. * in a way which confuses parent. In particular,
  1083. * do not modify fdp[i][j].
  1084. */
  1085. handledesc(NULL, fd, fdp);
  1086. DPRINTF("Executing %s\n", compr[method].argv[0]);
  1087. (void)execvp(compr[method].argv[0], args);
  1088. dprintf(STDERR_FILENO, "exec `%s' failed, %s",
  1089. compr[method].argv[0], strerror(errno));
  1090. _exit(EXIT_FAILURE); /* _exit(), not exit(), because of vfork */
  1091. }
  1092. #endif
  1093. /* parent */
  1094. /* Close write sides of child stdout/err pipes */
  1095. for (i = 1; i < __arraycount(fdp); i++)
  1096. closefd(fdp[i], 1);
  1097. /* Write the buffer data to child stdin, if we don't have fd */
  1098. if (fd == -1) {
  1099. closefd(fdp[STDIN_FILENO], 0);
  1100. writepid = writechild(fdp[STDIN_FILENO][1], old, *n);
  1101. if (writepid == (pid_t)-1) {
  1102. rv = makeerror(newch, n, "Write to child failed, %s",
  1103. strerror(errno));
  1104. DPRINTF("Write to child failed\n");
  1105. goto err;
  1106. }
  1107. closefd(fdp[STDIN_FILENO], 1);
  1108. }
  1109. rv = OKDATA;
  1110. r = sread(fdp[STDOUT_FILENO][0], *newch, bytes_max, 0);
  1111. DPRINTF("read got %zd\n", r);
  1112. if (r < 0) {
  1113. rv = ERRDATA;
  1114. DPRINTF("Read stdout failed %d (%s)\n", fdp[STDOUT_FILENO][0],
  1115. strerror(errno));
  1116. goto err;
  1117. }
  1118. if (CAST(size_t, r) == bytes_max) {
  1119. /*
  1120. * close fd so that the child exits with sigpipe and ignore
  1121. * errors, otherwise we risk the child blocking and never
  1122. * exiting.
  1123. */
  1124. DPRINTF("Closing stdout for bytes_max\n");
  1125. closefd(fdp[STDOUT_FILENO], 0);
  1126. goto ok;
  1127. }
  1128. if ((re = sread(fdp[STDERR_FILENO][0], *newch, bytes_max, 0)) > 0) {
  1129. DPRINTF("Got stuff from stderr %s\n", *newch);
  1130. rv = ERRDATA;
  1131. r = filter_error(*newch, r);
  1132. goto ok;
  1133. }
  1134. if (re == 0)
  1135. goto ok;
  1136. rv = makeerror(newch, n, "Read stderr failed, %s",
  1137. strerror(errno));
  1138. goto err;
  1139. ok:
  1140. *n = r;
  1141. /* NUL terminate, as every buffer is handled here. */
  1142. (*newch)[*n] = '\0';
  1143. err:
  1144. closefd(fdp[STDIN_FILENO], 1);
  1145. closefd(fdp[STDOUT_FILENO], 0);
  1146. closefd(fdp[STDERR_FILENO], 0);
  1147. w = waitpid(pid, &status, 0);
  1148. wait_err:
  1149. if (w == -1) {
  1150. rv = makeerror(newch, n, "Wait failed, %s", strerror(errno));
  1151. DPRINTF("Child wait return %#x\n", status);
  1152. } else if (!WIFEXITED(status)) {
  1153. DPRINTF("Child not exited (%#x)\n", status);
  1154. } else if (WEXITSTATUS(status) != 0) {
  1155. DPRINTF("Child exited (%#x)\n", WEXITSTATUS(status));
  1156. }
  1157. if (writepid > 0) {
  1158. /* _After_ we know decompressor has exited, our input writer
  1159. * definitely will exit now (at worst, writing fails in it,
  1160. * since output fd is closed now on the reading size).
  1161. */
  1162. w = waitpid(writepid, &status, 0);
  1163. writepid = -1;
  1164. goto wait_err;
  1165. }
  1166. closefd(fdp[STDIN_FILENO], 0); //why? it is already closed here!
  1167. DPRINTF("Returning %p n=%" SIZE_T_FORMAT "u rv=%d\n", *newch, *n, rv);
  1168. return rv;
  1169. }
  1170. #endif