zran.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /* zran.c -- example of deflate stream indexing and random access
  2. * Copyright (C) 2005, 2012, 2018, 2023 Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. * Version 1.4 13 Apr 2023 Mark Adler */
  5. /* Version History:
  6. 1.0 29 May 2005 First version
  7. 1.1 29 Sep 2012 Fix memory reallocation error
  8. 1.2 14 Oct 2018 Handle gzip streams with multiple members
  9. Add a header file to facilitate usage in applications
  10. 1.3 18 Feb 2023 Permit raw deflate streams as well as zlib and gzip
  11. Permit crossing gzip member boundaries when extracting
  12. Support a size_t size when extracting (was an int)
  13. Do a binary search over the index for an access point
  14. Expose the access point type to enable save and load
  15. 1.4 13 Apr 2023 Add a NOPRIME define to not use inflatePrime()
  16. */
  17. // Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary()
  18. // for random access of a compressed file. A file containing a raw deflate
  19. // stream is provided on the command line. The compressed stream is decoded in
  20. // its entirety, and an index built with access points about every SPAN bytes
  21. // in the uncompressed output. The compressed file is left open, and can then
  22. // be read randomly, having to decompress on the average SPAN/2 uncompressed
  23. // bytes before getting to the desired block of data.
  24. //
  25. // An access point can be created at the start of any deflate block, by saving
  26. // the starting file offset and bit of that block, and the 32K bytes of
  27. // uncompressed data that precede that block. Also the uncompressed offset of
  28. // that block is saved to provide a reference for locating a desired starting
  29. // point in the uncompressed stream. deflate_index_build() decompresses the
  30. // input raw deflate stream a block at a time, and at the end of each block
  31. // decides if enough uncompressed data has gone by to justify the creation of a
  32. // new access point. If so, that point is saved in a data structure that grows
  33. // as needed to accommodate the points.
  34. //
  35. // To use the index, an offset in the uncompressed data is provided, for which
  36. // the latest access point at or preceding that offset is located in the index.
  37. // The input file is positioned to the specified location in the index, and if
  38. // necessary the first few bits of the compressed data is read from the file.
  39. // inflate is initialized with those bits and the 32K of uncompressed data, and
  40. // decompression then proceeds until the desired offset in the file is reached.
  41. // Then decompression continues to read the requested uncompressed data from
  42. // the file.
  43. //
  44. // There is some fair bit of overhead to starting inflation for the random
  45. // access, mainly copying the 32K byte dictionary. If small pieces of the file
  46. // are being accessed, it would make sense to implement a cache to hold some
  47. // lookahead to avoid many calls to deflate_index_extract() for small lengths.
  48. //
  49. // Another way to build an index would be to use inflateCopy(). That would not
  50. // be constrained to have access points at block boundaries, but would require
  51. // more memory per access point, and could not be saved to a file due to the
  52. // use of pointers in the state. The approach here allows for storage of the
  53. // index in a file.
  54. #include <stdio.h>
  55. #include <stdlib.h>
  56. #include <string.h>
  57. #include <limits.h>
  58. #include "zlib.h"
  59. #include "zran.h"
  60. #define WINSIZE 32768U // sliding window size
  61. #define CHUNK 16384 // file input buffer size
  62. // See comments in zran.h.
  63. void deflate_index_free(struct deflate_index *index) {
  64. if (index != NULL) {
  65. free(index->list);
  66. free(index);
  67. }
  68. }
  69. // Add an access point to the list. If out of memory, deallocate the existing
  70. // list and return NULL. index->mode is temporarily the allocated number of
  71. // access points, until it is time for deflate_index_build() to return. Then
  72. // index->mode is set to the mode of inflation.
  73. static struct deflate_index *add_point(struct deflate_index *index, int bits,
  74. off_t in, off_t out, unsigned left,
  75. unsigned char *window) {
  76. if (index == NULL) {
  77. // The list is empty. Create it, starting with eight access points.
  78. index = malloc(sizeof(struct deflate_index));
  79. if (index == NULL)
  80. return NULL;
  81. index->have = 0;
  82. index->mode = 8;
  83. index->list = malloc(sizeof(point_t) * index->mode);
  84. if (index->list == NULL) {
  85. free(index);
  86. return NULL;
  87. }
  88. }
  89. else if (index->have == index->mode) {
  90. // The list is full. Make it bigger.
  91. index->mode <<= 1;
  92. point_t *next = realloc(index->list, sizeof(point_t) * index->mode);
  93. if (next == NULL) {
  94. deflate_index_free(index);
  95. return NULL;
  96. }
  97. index->list = next;
  98. }
  99. // Fill in the access point and increment how many we have.
  100. point_t *next = (point_t *)(index->list) + index->have++;
  101. if (index->have < 0) {
  102. // Overflowed the int!
  103. deflate_index_free(index);
  104. return NULL;
  105. }
  106. next->out = out;
  107. next->in = in;
  108. next->bits = bits;
  109. if (left)
  110. memcpy(next->window, window + WINSIZE - left, left);
  111. if (left < WINSIZE)
  112. memcpy(next->window + left, window, WINSIZE - left);
  113. // Return the index, which may have been newly allocated or destroyed.
  114. return index;
  115. }
  116. // Decompression modes. These are the inflateInit2() windowBits parameter.
  117. #define RAW -15
  118. #define ZLIB 15
  119. #define GZIP 31
  120. // See comments in zran.h.
  121. int deflate_index_build(FILE *in, off_t span, struct deflate_index **built) {
  122. // Set up inflation state.
  123. z_stream strm = {0}; // inflate engine (gets fired up later)
  124. unsigned char buf[CHUNK]; // input buffer
  125. unsigned char win[WINSIZE] = {0}; // output sliding window
  126. off_t totin = 0; // total bytes read from input
  127. off_t totout = 0; // total bytes uncompressed
  128. int mode = 0; // mode: RAW, ZLIB, or GZIP (0 => not set yet)
  129. // Decompress from in, generating access points along the way.
  130. int ret; // the return value from zlib, or Z_ERRNO
  131. off_t last; // last access point uncompressed offset
  132. struct deflate_index *index = NULL; // list of access points
  133. do {
  134. // Assure available input, at least until reaching EOF.
  135. if (strm.avail_in == 0) {
  136. strm.avail_in = fread(buf, 1, sizeof(buf), in);
  137. totin += strm.avail_in;
  138. strm.next_in = buf;
  139. if (strm.avail_in < sizeof(buf) && ferror(in)) {
  140. ret = Z_ERRNO;
  141. break;
  142. }
  143. if (mode == 0) {
  144. // At the start of the input -- determine the type. Assume raw
  145. // if it is neither zlib nor gzip. This could in theory result
  146. // in a false positive for zlib, but in practice the fill bits
  147. // after a stored block are always zeros, so a raw stream won't
  148. // start with an 8 in the low nybble.
  149. mode = strm.avail_in == 0 ? RAW : // empty -- will fail
  150. (strm.next_in[0] & 0xf) == 8 ? ZLIB :
  151. strm.next_in[0] == 0x1f ? GZIP :
  152. /* else */ RAW;
  153. ret = inflateInit2(&strm, mode);
  154. if (ret != Z_OK)
  155. break;
  156. }
  157. }
  158. // Assure available output. This rotates the output through, for use as
  159. // a sliding window on the uncompressed data.
  160. if (strm.avail_out == 0) {
  161. strm.avail_out = sizeof(win);
  162. strm.next_out = win;
  163. }
  164. if (mode == RAW && index == NULL)
  165. // We skip the inflate() call at the start of raw deflate data in
  166. // order generate an access point there. Set data_type to imitate
  167. // the end of a header.
  168. strm.data_type = 0x80;
  169. else {
  170. // Inflate and update the number of uncompressed bytes.
  171. unsigned before = strm.avail_out;
  172. ret = inflate(&strm, Z_BLOCK);
  173. totout += before - strm.avail_out;
  174. }
  175. if ((strm.data_type & 0xc0) == 0x80 &&
  176. (index == NULL || totout - last >= span)) {
  177. // We are at the end of a header or a non-last deflate block, so we
  178. // can add an access point here. Furthermore, we are either at the
  179. // very start for the first access point, or there has been span or
  180. // more uncompressed bytes since the last access point, so we want
  181. // to add an access point here.
  182. index = add_point(index, strm.data_type & 7, totin - strm.avail_in,
  183. totout, strm.avail_out, win);
  184. if (index == NULL) {
  185. ret = Z_MEM_ERROR;
  186. break;
  187. }
  188. last = totout;
  189. }
  190. if (ret == Z_STREAM_END && mode == GZIP &&
  191. (strm.avail_in || ungetc(getc(in), in) != EOF))
  192. // There is more input after the end of a gzip member. Reset the
  193. // inflate state to read another gzip member. On success, this will
  194. // set ret to Z_OK to continue decompressing.
  195. ret = inflateReset2(&strm, GZIP);
  196. // Keep going until Z_STREAM_END or error. If the compressed data ends
  197. // prematurely without a file read error, Z_BUF_ERROR is returned.
  198. } while (ret == Z_OK);
  199. inflateEnd(&strm);
  200. if (ret != Z_STREAM_END) {
  201. // An error was encountered. Discard the index and return a negative
  202. // error code.
  203. deflate_index_free(index);
  204. return ret == Z_NEED_DICT ? Z_DATA_ERROR : ret;
  205. }
  206. // Shrink the index to only the occupied access points and return it.
  207. index->mode = mode;
  208. index->length = totout;
  209. point_t *list = realloc(index->list, sizeof(point_t) * index->have);
  210. if (list == NULL) {
  211. // Seems like a realloc() to make something smaller should always work,
  212. // but just in case.
  213. deflate_index_free(index);
  214. return Z_MEM_ERROR;
  215. }
  216. index->list = list;
  217. *built = index;
  218. return index->have;
  219. }
  220. #ifdef NOPRIME
  221. // Support zlib versions before 1.2.3 (July 2005), or incomplete zlib clones
  222. // that do not have inflatePrime().
  223. # define INFLATEPRIME inflatePreface
  224. // Append the low bits bits of value to in[] at bit position *have, updating
  225. // *have. value must be zero above its low bits bits. bits must be positive.
  226. // This assumes that any bits above the *have bits in the last byte are zeros.
  227. // That assumption is preserved on return, as any bits above *have + bits in
  228. // the last byte written will be set to zeros.
  229. static inline void append_bits(unsigned value, int bits,
  230. unsigned char *in, int *have) {
  231. in += *have >> 3; // where the first bits from value will go
  232. int k = *have & 7; // the number of bits already there
  233. *have += bits;
  234. if (k)
  235. *in |= value << k; // write value above the low k bits
  236. else
  237. *in = value;
  238. k = 8 - k; // the number of bits just appended
  239. while (bits > k) {
  240. value >>= k; // drop the bits appended
  241. bits -= k;
  242. k = 8; // now at a byte boundary
  243. *++in = value;
  244. }
  245. }
  246. // Insert enough bits in the form of empty deflate blocks in front of the
  247. // low bits bits of value, in order to bring the sequence to a byte boundary.
  248. // Then feed that to inflate(). This does what inflatePrime() does, except that
  249. // a negative value of bits is not supported. bits must be in 0..16. If the
  250. // arguments are invalid, Z_STREAM_ERROR is returned. Otherwise the return
  251. // value from inflate() is returned.
  252. static int inflatePreface(z_stream *strm, int bits, int value) {
  253. // Check input.
  254. if (strm == Z_NULL || bits < 0 || bits > 16)
  255. return Z_STREAM_ERROR;
  256. if (bits == 0)
  257. return Z_OK;
  258. value &= (2 << (bits - 1)) - 1;
  259. // An empty dynamic block with an odd number of bits (95). The high bit of
  260. // the last byte is unused.
  261. static const unsigned char dyn[] = {
  262. 4, 0xe0, 0x81, 8, 0, 0, 0, 0, 0x20, 0xa8, 0xab, 0x1f
  263. };
  264. const int dynlen = 95; // number of bits in the block
  265. // Build an input buffer for inflate that is a multiple of eight bits in
  266. // length, and that ends with the low bits bits of value.
  267. unsigned char in[(dynlen + 3 * 10 + 16 + 7) / 8];
  268. int have = 0;
  269. if (bits & 1) {
  270. // Insert an empty dynamic block to get to an odd number of bits, so
  271. // when bits bits from value are appended, we are at an even number of
  272. // bits.
  273. memcpy(in, dyn, sizeof(dyn));
  274. have = dynlen;
  275. }
  276. while ((have + bits) & 7)
  277. // Insert empty fixed blocks until appending bits bits would put us on
  278. // a byte boundary. This will insert at most three fixed blocks.
  279. append_bits(2, 10, in, &have);
  280. // Append the bits bits from value, which takes us to a byte boundary.
  281. append_bits(value, bits, in, &have);
  282. // Deliver the input to inflate(). There is no output space provided, but
  283. // inflate() can't get stuck waiting on output not ingesting all of the
  284. // provided input. The reason is that there will be at most 16 bits of
  285. // input from value after the empty deflate blocks (which themselves
  286. // generate no output). At least ten bits are needed to generate the first
  287. // output byte from a fixed block. The last two bytes of the buffer have to
  288. // be ingested in order to get ten bits, which is the most that value can
  289. // occupy.
  290. strm->avail_in = have >> 3;
  291. strm->next_in = in;
  292. strm->avail_out = 0;
  293. strm->next_out = in; // not used, but can't be NULL
  294. return inflate(strm, Z_NO_FLUSH);
  295. }
  296. #else
  297. # define INFLATEPRIME inflatePrime
  298. #endif
  299. // See comments in zran.h.
  300. ptrdiff_t deflate_index_extract(FILE *in, struct deflate_index *index,
  301. off_t offset, unsigned char *buf, size_t len) {
  302. // Do a quick sanity check on the index.
  303. if (index == NULL || index->have < 1 || index->list[0].out != 0)
  304. return Z_STREAM_ERROR;
  305. // If nothing to extract, return zero bytes extracted.
  306. if (len == 0 || offset < 0 || offset >= index->length)
  307. return 0;
  308. // Find the access point closest to but not after offset.
  309. int lo = -1, hi = index->have;
  310. point_t *point = index->list;
  311. while (hi - lo > 1) {
  312. int mid = (lo + hi) >> 1;
  313. if (offset < point[mid].out)
  314. hi = mid;
  315. else
  316. lo = mid;
  317. }
  318. point += lo;
  319. // Initialize the input file and prime the inflate engine to start there.
  320. int ret = fseeko(in, point->in - (point->bits ? 1 : 0), SEEK_SET);
  321. if (ret == -1)
  322. return Z_ERRNO;
  323. int ch = 0;
  324. if (point->bits && (ch = getc(in)) == EOF)
  325. return ferror(in) ? Z_ERRNO : Z_BUF_ERROR;
  326. z_stream strm = {0};
  327. ret = inflateInit2(&strm, RAW);
  328. if (ret != Z_OK)
  329. return ret;
  330. if (point->bits)
  331. INFLATEPRIME(&strm, point->bits, ch >> (8 - point->bits));
  332. inflateSetDictionary(&strm, point->window, WINSIZE);
  333. // Skip uncompressed bytes until offset reached, then satisfy request.
  334. unsigned char input[CHUNK];
  335. unsigned char discard[WINSIZE];
  336. offset -= point->out; // number of bytes to skip to get to offset
  337. size_t left = len; // number of bytes left to read after offset
  338. do {
  339. if (offset) {
  340. // Discard up to offset uncompressed bytes.
  341. strm.avail_out = offset < WINSIZE ? (unsigned)offset : WINSIZE;
  342. strm.next_out = discard;
  343. }
  344. else {
  345. // Uncompress up to left bytes into buf.
  346. strm.avail_out = left < UINT_MAX ? (unsigned)left : UINT_MAX;
  347. strm.next_out = buf + len - left;
  348. }
  349. // Uncompress, setting got to the number of bytes uncompressed.
  350. if (strm.avail_in == 0) {
  351. // Assure available input.
  352. strm.avail_in = fread(input, 1, CHUNK, in);
  353. if (strm.avail_in < CHUNK && ferror(in)) {
  354. ret = Z_ERRNO;
  355. break;
  356. }
  357. strm.next_in = input;
  358. }
  359. unsigned got = strm.avail_out;
  360. ret = inflate(&strm, Z_NO_FLUSH);
  361. got -= strm.avail_out;
  362. // Update the appropriate count.
  363. if (offset)
  364. offset -= got;
  365. else
  366. left -= got;
  367. // If we're at the end of a gzip member and there's more to read,
  368. // continue to the next gzip member.
  369. if (ret == Z_STREAM_END && index->mode == GZIP) {
  370. // Discard the gzip trailer.
  371. unsigned drop = 8; // length of gzip trailer
  372. if (strm.avail_in >= drop) {
  373. strm.avail_in -= drop;
  374. strm.next_in += drop;
  375. }
  376. else {
  377. // Read and discard the remainder of the gzip trailer.
  378. drop -= strm.avail_in;
  379. strm.avail_in = 0;
  380. do {
  381. if (getc(in) == EOF)
  382. // The input does not have a complete trailer.
  383. return ferror(in) ? Z_ERRNO : Z_BUF_ERROR;
  384. } while (--drop);
  385. }
  386. if (strm.avail_in || ungetc(getc(in), in) != EOF) {
  387. // There's more after the gzip trailer. Use inflate to skip the
  388. // gzip header and resume the raw inflate there.
  389. inflateReset2(&strm, GZIP);
  390. do {
  391. if (strm.avail_in == 0) {
  392. strm.avail_in = fread(input, 1, CHUNK, in);
  393. if (strm.avail_in < CHUNK && ferror(in)) {
  394. ret = Z_ERRNO;
  395. break;
  396. }
  397. strm.next_in = input;
  398. }
  399. strm.avail_out = WINSIZE;
  400. strm.next_out = discard;
  401. ret = inflate(&strm, Z_BLOCK); // stop at end of header
  402. } while (ret == Z_OK && (strm.data_type & 0x80) == 0);
  403. if (ret != Z_OK)
  404. break;
  405. inflateReset2(&strm, RAW);
  406. }
  407. }
  408. // Continue until we have the requested data, the deflate data has
  409. // ended, or an error is encountered.
  410. } while (ret == Z_OK && left);
  411. inflateEnd(&strm);
  412. // Return the number of uncompressed bytes read into buf, or the error.
  413. return ret == Z_OK || ret == Z_STREAM_END ? len - left : ret;
  414. }
  415. #ifdef TEST
  416. #define SPAN 1048576L // desired distance between access points
  417. #define LEN 16384 // number of bytes to extract
  418. // Demonstrate the use of deflate_index_build() and deflate_index_extract() by
  419. // processing the file provided on the command line, and extracting LEN bytes
  420. // from 2/3rds of the way through the uncompressed output, writing that to
  421. // stdout. An offset can be provided as the second argument, in which case the
  422. // data is extracted from there instead.
  423. int main(int argc, char **argv) {
  424. // Open the input file.
  425. if (argc < 2 || argc > 3) {
  426. fprintf(stderr, "usage: zran file.raw [offset]\n");
  427. return 1;
  428. }
  429. FILE *in = fopen(argv[1], "rb");
  430. if (in == NULL) {
  431. fprintf(stderr, "zran: could not open %s for reading\n", argv[1]);
  432. return 1;
  433. }
  434. // Get optional offset.
  435. off_t offset = -1;
  436. if (argc == 3) {
  437. char *end;
  438. offset = strtoll(argv[2], &end, 10);
  439. if (*end || offset < 0) {
  440. fprintf(stderr, "zran: %s is not a valid offset\n", argv[2]);
  441. return 1;
  442. }
  443. }
  444. // Build index.
  445. struct deflate_index *index = NULL;
  446. int len = deflate_index_build(in, SPAN, &index);
  447. if (len < 0) {
  448. fclose(in);
  449. switch (len) {
  450. case Z_MEM_ERROR:
  451. fprintf(stderr, "zran: out of memory\n");
  452. break;
  453. case Z_BUF_ERROR:
  454. fprintf(stderr, "zran: %s ended prematurely\n", argv[1]);
  455. break;
  456. case Z_DATA_ERROR:
  457. fprintf(stderr, "zran: compressed data error in %s\n", argv[1]);
  458. break;
  459. case Z_ERRNO:
  460. fprintf(stderr, "zran: read error on %s\n", argv[1]);
  461. break;
  462. default:
  463. fprintf(stderr, "zran: error %d while building index\n", len);
  464. }
  465. return 1;
  466. }
  467. fprintf(stderr, "zran: built index with %d access points\n", len);
  468. // Use index by reading some bytes from an arbitrary offset.
  469. unsigned char buf[LEN];
  470. if (offset == -1)
  471. offset = ((index->length + 1) << 1) / 3;
  472. ptrdiff_t got = deflate_index_extract(in, index, offset, buf, LEN);
  473. if (got < 0)
  474. fprintf(stderr, "zran: extraction failed: %s error\n",
  475. got == Z_MEM_ERROR ? "out of memory" : "input corrupted");
  476. else {
  477. fwrite(buf, 1, got, stdout);
  478. fprintf(stderr, "zran: extracted %ld bytes at %lld\n", got, offset);
  479. }
  480. // Clean up and exit.
  481. deflate_index_free(index);
  482. fclose(in);
  483. return 0;
  484. }
  485. #endif