zran.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /* zran.c -- example of zlib/gzip stream indexing and random access
  2. * Copyright (C) 2005 Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. Version 1.0 29 May 2005 Mark Adler */
  5. /* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary()
  6. for random access of a compressed file. A file containing a zlib or gzip
  7. stream is provided on the command line. The compressed stream is decoded in
  8. its entirety, and an index built with access points about every SPAN bytes
  9. in the uncompressed output. The compressed file is left open, and can then
  10. be read randomly, having to decompress on the average SPAN/2 uncompressed
  11. bytes before getting to the desired block of data.
  12. An access point can be created at the start of any deflate block, by saving
  13. the starting file offset and bit of that block, and the 32K bytes of
  14. uncompressed data that precede that block. Also the uncompressed offset of
  15. that block is saved to provide a referece for locating a desired starting
  16. point in the uncompressed stream. build_index() works by decompressing the
  17. input zlib or gzip stream a block at a time, and at the end of each block
  18. deciding if enough uncompressed data has gone by to justify the creation of
  19. a new access point. If so, that point is saved in a data structure that
  20. grows as needed to accommodate the points.
  21. To use the index, an offset in the uncompressed data is provided, for which
  22. the latest accees point at or preceding that offset is located in the index.
  23. The input file is positioned to the specified location in the index, and if
  24. necessary the first few bits of the compressed data is read from the file.
  25. inflate is initialized with those bits and the 32K of uncompressed data, and
  26. the decompression then proceeds until the desired offset in the file is
  27. reached. Then the decompression continues to read the desired uncompressed
  28. data from the file.
  29. Another approach would be to generate the index on demand. In that case,
  30. requests for random access reads from the compressed data would try to use
  31. the index, but if a read far enough past the end of the index is required,
  32. then further index entries would be generated and added.
  33. There is some fair bit of overhead to starting inflation for the random
  34. access, mainly copying the 32K byte dictionary. So if small pieces of the
  35. file are being accessed, it would make sense to implement a cache to hold
  36. some lookahead and avoid many calls to extract() for small lengths.
  37. Another way to build an index would be to use inflateCopy(). That would
  38. not be constrained to have access points at block boundaries, but requires
  39. more memory per access point, and also cannot be saved to file due to the
  40. use of pointers in the state. The approach here allows for storage of the
  41. index in a file.
  42. */
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include "zlib.h"
  47. #define local static
  48. #define SPAN 1048576L /* desired distance between access points */
  49. #define WINSIZE 32768U /* sliding window size */
  50. #define CHUNK 16384 /* file input buffer size */
  51. /* access point entry */
  52. struct point {
  53. off_t out; /* corresponding offset in uncompressed data */
  54. off_t in; /* offset in input file of first full byte */
  55. int bits; /* number of bits (1-7) from byte at in - 1, or 0 */
  56. unsigned char window[WINSIZE]; /* preceding 32K of uncompressed data */
  57. };
  58. /* access point list */
  59. struct access {
  60. int have; /* number of list entries filled in */
  61. int size; /* number of list entries allocated */
  62. struct point *list; /* allocated list */
  63. };
  64. /* Deallocate an index built by build_index() */
  65. local void free_index(struct access *index)
  66. {
  67. if (index != NULL) {
  68. free(index->list);
  69. free(index);
  70. }
  71. }
  72. /* Add an entry to the access point list. If out of memory, deallocate the
  73. existing list and return NULL. */
  74. local struct access *addpoint(struct access *index, int bits,
  75. off_t in, off_t out, unsigned left, unsigned char *window)
  76. {
  77. struct point *next;
  78. /* if list is empty, create it (start with eight points) */
  79. if (index == NULL) {
  80. index = malloc(sizeof(struct access));
  81. if (index == NULL) return NULL;
  82. index->list = malloc(sizeof(struct point) << 3);
  83. if (index->list == NULL) {
  84. free(index);
  85. return NULL;
  86. }
  87. index->size = 8;
  88. index->have = 0;
  89. }
  90. /* if list is full, make it bigger */
  91. else if (index->have == index->size) {
  92. index->size <<= 1;
  93. next = realloc(index->list, sizeof(struct point) * index->size);
  94. if (next == NULL) {
  95. free_index(index);
  96. return NULL;
  97. }
  98. index->list = next;
  99. }
  100. /* fill in entry and increment how many we have */
  101. next = index->list + index->have;
  102. next->bits = bits;
  103. next->in = in;
  104. next->out = out;
  105. if (left)
  106. memcpy(next->window, window + WINSIZE - left, left);
  107. if (left < WINSIZE)
  108. memcpy(next->window + left, window, WINSIZE - left);
  109. index->have++;
  110. /* return list, possibly reallocated */
  111. return index;
  112. }
  113. /* Make one entire pass through the compressed stream and build an index, with
  114. access points about every span bytes of uncompressed output -- span is
  115. chosen to balance the speed of random access against the memory requirements
  116. of the list, about 32K bytes per access point. Note that data after the end
  117. of the first zlib or gzip stream in the file is ignored. build_index()
  118. returns the number of access points on success (>= 1), Z_MEM_ERROR for out
  119. of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a
  120. file read error. On success, *built points to the resulting index. */
  121. local int build_index(FILE *in, off_t span, struct access **built)
  122. {
  123. int ret;
  124. off_t totin, totout; /* our own total counters to avoid 4GB limit */
  125. off_t last; /* totout value of last access point */
  126. struct access *index; /* access points being generated */
  127. z_stream strm;
  128. unsigned char input[CHUNK];
  129. unsigned char window[WINSIZE];
  130. /* initialize inflate */
  131. strm.zalloc = Z_NULL;
  132. strm.zfree = Z_NULL;
  133. strm.opaque = Z_NULL;
  134. strm.avail_in = 0;
  135. strm.next_in = Z_NULL;
  136. ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */
  137. if (ret != Z_OK)
  138. return ret;
  139. /* inflate the input, maintain a sliding window, and build an index -- this
  140. also validates the integrity of the compressed data using the check
  141. information at the end of the gzip or zlib stream */
  142. totin = totout = last = 0;
  143. index = NULL; /* will be allocated by first addpoint() */
  144. strm.avail_out = 0;
  145. do {
  146. /* get some compressed data from input file */
  147. strm.avail_in = fread(input, 1, CHUNK, in);
  148. if (ferror(in)) {
  149. ret = Z_ERRNO;
  150. goto build_index_error;
  151. }
  152. if (strm.avail_in == 0) {
  153. ret = Z_DATA_ERROR;
  154. goto build_index_error;
  155. }
  156. strm.next_in = input;
  157. /* process all of that, or until end of stream */
  158. do {
  159. /* reset sliding window if necessary */
  160. if (strm.avail_out == 0) {
  161. strm.avail_out = WINSIZE;
  162. strm.next_out = window;
  163. }
  164. /* inflate until out of input, output, or at end of block --
  165. update the total input and output counters */
  166. totin += strm.avail_in;
  167. totout += strm.avail_out;
  168. ret = inflate(&strm, Z_BLOCK); /* return at end of block */
  169. totin -= strm.avail_in;
  170. totout -= strm.avail_out;
  171. if (ret == Z_NEED_DICT)
  172. ret = Z_DATA_ERROR;
  173. if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
  174. goto build_index_error;
  175. if (ret == Z_STREAM_END)
  176. break;
  177. /* if at end of block, consider adding an index entry (note that if
  178. data_type indicates an end-of-block, then all of the
  179. uncompressed data from that block has been delivered, and none
  180. of the compressed data after that block has been consumed,
  181. except for up to seven bits) -- the totout == 0 provides an
  182. entry point after the zlib or gzip header, and assures that the
  183. index always has at least one access point; we avoid creating an
  184. access point after the last block by checking bit 6 of data_type
  185. */
  186. if ((strm.data_type & 128) && !(strm.data_type & 64) &&
  187. (totout == 0 || totout - last > span)) {
  188. index = addpoint(index, strm.data_type & 7, totin,
  189. totout, strm.avail_out, window);
  190. if (index == NULL) {
  191. ret = Z_MEM_ERROR;
  192. goto build_index_error;
  193. }
  194. last = totout;
  195. }
  196. } while (strm.avail_in != 0);
  197. } while (ret != Z_STREAM_END);
  198. /* clean up and return index (release unused entries in list) */
  199. (void)inflateEnd(&strm);
  200. index = realloc(index, sizeof(struct point) * index->have);
  201. index->size = index->have;
  202. *built = index;
  203. return index->size;
  204. /* return error */
  205. build_index_error:
  206. (void)inflateEnd(&strm);
  207. if (index != NULL)
  208. free_index(index);
  209. return ret;
  210. }
  211. /* Use the index to read len bytes from offset into buf, return bytes read or
  212. negative for error (Z_DATA_ERROR or Z_MEM_ERROR). If data is requested past
  213. the end of the uncompressed data, then extract() will return a value less
  214. than len, indicating how much as actually read into buf. This function
  215. should not return a data error unless the file was modified since the index
  216. was generated. extract() may also return Z_ERRNO if there is an error on
  217. reading or seeking the input file. */
  218. local int extract(FILE *in, struct access *index, off_t offset,
  219. unsigned char *buf, int len)
  220. {
  221. int ret, skip;
  222. z_stream strm;
  223. struct point *here;
  224. unsigned char input[CHUNK];
  225. unsigned char discard[WINSIZE];
  226. /* proceed only if something reasonable to do */
  227. if (len < 0)
  228. return 0;
  229. /* find where in stream to start */
  230. here = index->list;
  231. ret = index->have;
  232. while (--ret && here[1].out <= offset)
  233. here++;
  234. /* initialize file and inflate state to start there */
  235. strm.zalloc = Z_NULL;
  236. strm.zfree = Z_NULL;
  237. strm.opaque = Z_NULL;
  238. strm.avail_in = 0;
  239. strm.next_in = Z_NULL;
  240. ret = inflateInit2(&strm, -15); /* raw inflate */
  241. if (ret != Z_OK)
  242. return ret;
  243. ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET);
  244. if (ret == -1)
  245. goto extract_ret;
  246. if (here->bits) {
  247. ret = getc(in);
  248. if (ret == -1) {
  249. ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR;
  250. goto extract_ret;
  251. }
  252. (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits));
  253. }
  254. (void)inflateSetDictionary(&strm, here->window, WINSIZE);
  255. /* skip uncompressed bytes until offset reached, then satisfy request */
  256. offset -= here->out;
  257. strm.avail_in = 0;
  258. skip = 1; /* while skipping to offset */
  259. do {
  260. /* define where to put uncompressed data, and how much */
  261. if (offset == 0 && skip) { /* at offset now */
  262. strm.avail_out = len;
  263. strm.next_out = buf;
  264. skip = 0; /* only do this once */
  265. }
  266. if (offset > WINSIZE) { /* skip WINSIZE bytes */
  267. strm.avail_out = WINSIZE;
  268. strm.next_out = discard;
  269. offset -= WINSIZE;
  270. }
  271. else if (offset != 0) { /* last skip */
  272. strm.avail_out = (unsigned)offset;
  273. strm.next_out = discard;
  274. offset = 0;
  275. }
  276. /* uncompress until avail_out filled, or end of stream */
  277. do {
  278. if (strm.avail_in == 0) {
  279. strm.avail_in = fread(input, 1, CHUNK, in);
  280. if (ferror(in)) {
  281. ret = Z_ERRNO;
  282. goto extract_ret;
  283. }
  284. if (strm.avail_in == 0) {
  285. ret = Z_DATA_ERROR;
  286. goto extract_ret;
  287. }
  288. strm.next_in = input;
  289. }
  290. ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */
  291. if (ret == Z_NEED_DICT)
  292. ret = Z_DATA_ERROR;
  293. if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
  294. goto extract_ret;
  295. if (ret == Z_STREAM_END)
  296. break;
  297. } while (strm.avail_out != 0);
  298. /* if reach end of stream, then don't keep trying to get more */
  299. if (ret == Z_STREAM_END)
  300. break;
  301. /* do until offset reached and requested data read, or stream ends */
  302. } while (skip);
  303. /* compute number of uncompressed bytes read after offset */
  304. ret = skip ? 0 : len - strm.avail_out;
  305. /* clean up and return bytes read or error */
  306. extract_ret:
  307. (void)inflateEnd(&strm);
  308. return ret;
  309. }
  310. /* Demonstrate the use of build_index() and extract() by processing the file
  311. provided on the command line, and the extracting 16K from about 2/3rds of
  312. the way through the uncompressed output, and writing that to stdout. */
  313. int main(int argc, char **argv)
  314. {
  315. int len;
  316. off_t offset;
  317. FILE *in;
  318. struct access *index = NULL;
  319. unsigned char buf[CHUNK];
  320. /* open input file */
  321. if (argc != 2) {
  322. fprintf(stderr, "usage: zran file.gz\n");
  323. return 1;
  324. }
  325. in = fopen(argv[1], "rb");
  326. if (in == NULL) {
  327. fprintf(stderr, "zran: could not open %s for reading\n", argv[1]);
  328. return 1;
  329. }
  330. /* build index */
  331. len = build_index(in, SPAN, &index);
  332. if (len < 0) {
  333. fclose(in);
  334. switch (len) {
  335. case Z_MEM_ERROR:
  336. fprintf(stderr, "zran: out of memory\n");
  337. break;
  338. case Z_DATA_ERROR:
  339. fprintf(stderr, "zran: compressed data error in %s\n", argv[1]);
  340. break;
  341. case Z_ERRNO:
  342. fprintf(stderr, "zran: read error on %s\n", argv[1]);
  343. break;
  344. default:
  345. fprintf(stderr, "zran: error %d while building index\n", len);
  346. }
  347. return 1;
  348. }
  349. fprintf(stderr, "zran: built index with %d access points\n", len);
  350. /* use index by reading some bytes from an arbitrary offset */
  351. offset = (index->list[index->have - 1].out << 1) / 3;
  352. len = extract(in, index, offset, buf, CHUNK);
  353. if (len < 0)
  354. fprintf(stderr, "zran: extraction failed: %s error\n",
  355. len == Z_MEM_ERROR ? "out of memory" : "input corrupted");
  356. else {
  357. fwrite(buf, 1, len, stdout);
  358. fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset);
  359. }
  360. /* clean up and exit */
  361. free_index(index);
  362. fclose(in);
  363. return 0;
  364. }