Debian Codegraph @

ztoc/compression/gzip_zinfo.c

raw symbols SCIP
1 /*
2 Copyright The Soci Snapshotter Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 /*
18 Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
19 This software is provided 'as-is', without any express or implied
20 warranty. In no event will the authors be held liable for any damages
21 arising from the use of this software.
22 Permission is granted to anyone to use this software for any purpose,
23 including commercial applications, and to alter it and redistribute it
24 freely, subject to the following restrictions:
25 1. The origin of this software must not be misrepresented; you must not
26 claim that you wrote the original software. If you use this software
27 in a product, an acknowledgment in the product documentation would be
28 appreciated but is not required.
29 2. Altered source versions must be plainly marked as such, and must not be
30 misrepresented as being the original software.
31 3. This notice may not be removed or altered from any source distribution.
32 Jean-loup Gailly Mark Adler
33 [email protected] [email protected]
34 */
35 /*
36 This source code is based on
37 https://github.com/madler/zlib/blob/master/examples/zran.c
38 and related code from that repository. It retains the copyright and
39 distribution restrictions of that work. It has been substantially modified
40 from the original.
41 */
42
43 #include "gzip_zinfo.h"
44
45 #include <endian.h>
46 #include <stdbool.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50
51 #define CHUNK (1 << 14) // file input buffer size
52
53
54 // zinfo - internal helpers start.
55
56 /* Convert integer types to little endian and vice versa.
57 This is needed to keep zinfo consistent across multiple architectures,
58 ensuring that all integer fields will be stored in little endian.
59 */
60 inline offset_t encode_offset(offset_t source) {
61 return htole64(source);
62 }
63
64 inline offset_t decode_offset(offset_t source) {
65 return le64toh(source);
66 }
67
68 inline int32_t encode_int32(int32_t source) {
69 return htole32(source);
70 }
71
72 inline int32_t decode_int32(int32_t source) {
73 return le32toh(source);
74 }
75
76 static int min(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
77
78 int init_flate(z_stream *strm, int windowBits) {
79 int ret;
80 strm->zalloc = Z_NULL;
81 strm->zfree = Z_NULL;
82 strm->opaque = Z_NULL;
83 strm->avail_in = 0;
84 strm->next_in = Z_NULL;
85 ret = inflateInit2(strm, windowBits);
86 return ret;
87 }
88
89 static uint8_t get_bits(struct gzip_zinfo *index, int checkpoint) {
90 return index->list[checkpoint].bits;
91 }
92
93 // zinfo - internal helpers end.
94
95 // zinfo - metadata starts.
96 int pt_index_from_ucmp_offset(struct gzip_zinfo* index, offset_t off) {
97 if (index == NULL)
98 return -1;
99
100 int res = 0;
101 struct gzip_checkpoint* here = index->list;
102 int ret = decode_int32(index->have);
103 while (--ret && decode_offset(here[1].out) <= off) {
104 here++;
105 res++;
106 }
107 return res;
108 }
109
110 offset_t get_ucomp_off(struct gzip_zinfo *index, int checkpoint) {
111 return decode_offset(index->list[checkpoint].out);
112 }
113
114 offset_t get_comp_off(struct gzip_zinfo *index, int checkpoint) {
115 return decode_offset(index->list[checkpoint].in);
116 }
117
118 unsigned get_blob_size(struct gzip_zinfo *index) {
119 if (index == NULL)
120 return 0;
121
122 unsigned size = decode_int32(index->size);
123 if (decode_int32(index->version) == ZINFO_VERSION_ONE)
124 size--;
125
126 /*
127 The buffer will be tightly packed. The layout of the buffer is:
128 - Some fixed size based on which version
129 - PACKED_CHECKPOINT_SIZE for each span.
130 If we have a v1 gzip_zinfo, we skip the first checkpoint
131 this is a bug, but it keeps backwards compatibility
132 */
133 return PACKED_CHECKPOINT_SIZE * size + BLOB_HEADER_SIZE;
134 }
135
136 int32_t get_max_span_id(struct gzip_zinfo *index) {
137 if (index == NULL)
138 return 0;
139 return decode_int32(index->have) - 1;
140 }
141
142 int has_bits(struct gzip_zinfo *index, int checkpoint) {
143 if (checkpoint >= decode_int32(index->have))
144 return 0;
145 return index->list[checkpoint].bits != 0;
146 }
147
148 // zinfo - metadata ends.
149
150 void free_zinfo(struct gzip_zinfo *index) {
151 if (index != NULL) {
152 free(index->list);
153 free(index);
154 }
155 }
156
157 // zinfo - generation/extraction starts.
158
159 /* Add an entry to the access point list. If out of memory, deallocate the
160 existing list and return NULL. */
161 static struct gzip_zinfo *add_checkpoint(struct gzip_zinfo *index, uint8_t bits,
162 offset_t in, offset_t out, unsigned left, unsigned char *window) {
163 struct gzip_checkpoint *next;
164
165 if (index == NULL) {
166 /* if list is empty, create it (start with eight points) */
167 index = malloc(sizeof(struct gzip_zinfo));
168 if (index == NULL) return NULL;
169 index->list = malloc(sizeof(struct gzip_checkpoint) << 3);
170 if (index->list == NULL) {
171 free(index);
172 return NULL;
173 }
174 index->size = 8;
175 index->have = 0;
176 } else if (index->have == index->size) {
177 /* if list is full, make it bigger */
178 index->size <<= 1;
179 next = realloc(index->list, sizeof(struct gzip_checkpoint) * index->size);
180 if (next == NULL) {
181 free_zinfo(index);
182 return NULL;
183 }
184 index->list = next;
185 }
186
187 /* fill in entry and increment how many we have */
188 next = index->list + index->have;
189 next->bits = bits;
190 next->in = encode_offset(in);
191 next->out = encode_offset(out);
192 if (left)
193 memcpy(next->window, window + WINSIZE - left, left);
194 if (left < WINSIZE)
195 memcpy(next->window + left, window, WINSIZE - left);
196 index->have++;
197
198 /* return list, possibly reallocated */
199 return index;
200 }
201
202 /* Pretty much the same as from zran.c */
203 int generate_zinfo_from_fp(FILE* in, offset_t span, struct gzip_zinfo** idx) {
204 int ret;
205 offset_t totin, totout; /* our own total counters to avoid 4GB limit */
206 offset_t last; /* totout value of last access point */
207 struct gzip_zinfo *index; /* access points being generated */
208 z_stream strm;
209 unsigned char input[CHUNK], window[WINSIZE];
210 memset(window, 0, WINSIZE);
211
212 /* initialize inflate */
213 ret = init_flate(&strm, 47); /* automatic zlib or gzip decoding */
214 if (ret != Z_OK)
215 return ret;
216
217 /* inflate the input, maintain a sliding window, and build an index -- this
218 also validates the integrity of the compressed data using the check
219 information at the end of the gzip or zlib stream */
220 totin = totout = last = 0;
221 index = NULL; /* will be allocated by first add_checkpoint() */
222 strm.avail_out = 0;
223 do {
224 /* get some compressed data from input file */
225 memset(input, 0, CHUNK);
226 strm.avail_in = fread(input, 1, CHUNK, in);
227 if (ferror(in)) {
228 ret = Z_ERRNO;
229 goto build_index_error;
230 }
231 if (strm.avail_in == 0) {
232 ret = Z_DATA_ERROR;
233 goto build_index_error;
234 }
235 strm.next_in = input;
236
237 /* process all of that, or until end of stream */
238 do {
239 /* reset sliding window if necessary */
240 if (strm.avail_out == 0) {
241 strm.avail_out = WINSIZE;
242 strm.next_out = window;
243 }
244
245 /* inflate until out of input, output, or at end of block --
246 update the total input and output counters */
247 totin += strm.avail_in;
248 totout += strm.avail_out;
249 ret = inflate(&strm, Z_BLOCK); /* return at end of block */
250 totin -= strm.avail_in;
251 totout -= strm.avail_out;
252 if (ret == Z_NEED_DICT)
253 ret = Z_DATA_ERROR;
254 if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
255 goto build_index_error;
256 if (ret == Z_STREAM_END)
257 break;
258
259 /* if at end of block, consider adding an index entry (note that if
260 data_type indicates an end-of-block, then all of the
261 uncompressed data from that block has been delivered, and none
262 of the compressed data after that block has been consumed,
263 except for up to seven bits) -- the totout == 0 provides an
264 entry point after the zlib or gzip header, and assures that the
265 index always has at least one access point; we avoid creating an
266 access point after the last block by checking bit 6 of data_type
267 */
268 if ((strm.data_type & 128) && !(strm.data_type & 64) &&
269 (totout == 0 || totout - last > span)) {
270 index = add_checkpoint(index, (uint8_t)(strm.data_type & 7), totin,
271 totout, strm.avail_out, window);
272 if (index == NULL) {
273 ret = Z_MEM_ERROR;
274 goto build_index_error;
275 }
276 last = totout;
277 }
278 } while (strm.avail_in != 0);
279 } while (ret != Z_STREAM_END);
280
281 /* clean up and return index (release unused entries in list) */
282 (void)inflateEnd(&strm);
283 index->list = realloc(index->list, sizeof(struct gzip_checkpoint) * index->have);
284 index->size = index->have;
285 index->have = encode_int32(index->have);
286 int32_t sz = index->size;
287 index->size = encode_int32(index->size);
288 index->span_size = encode_offset(span);
289 index->version = encode_int32(ZINFO_VERSION_CUR);
290 *idx = index;
291 return sz;
292
293 /* return error */
294 build_index_error:
295 (void)inflateEnd(&strm);
296 free_zinfo(index);
297 return ret;
298 }
299
300 int generate_zinfo_from_file(const char *filepath, offset_t span, struct gzip_zinfo **index) {
301 FILE *fp = fopen(filepath, "rb");
302 if (fp == NULL)
303 return GZIP_ZINFO_FILE_NOT_FOUND;
304 int ret = generate_zinfo_from_fp(fp, span, index);
305 fclose(fp);
306 return ret;
307 }
308
309 int extract_data_from_fp(FILE *in, struct gzip_zinfo *index, offset_t offset, void *buffer, int len) {
310 int ret, skip;
311 z_stream strm;
312 struct gzip_checkpoint *here;
313 unsigned char input[CHUNK], discard[WINSIZE];
314 uchar* buf = buffer;
315
316 /* proceed only if something reasonable to do */
317 if (len < 0)
318 return 0;
319
320 /* find where in stream to start */
321 here = index->list;
322 ret = decode_int32(index->have);
323 while (--ret && decode_offset(here[1].out) <= offset)
324 here++;
325
326 /* initialize inflate */
327 ret = init_flate(&strm, -15); /* raw inflate */
328 if (ret != Z_OK)
329 return ret;
330
331 ret = fseeko(in, decode_offset(here->in) - (here->bits ? 1 : 0), SEEK_SET);
332 if (ret == -1)
333 goto extract_ret;
334 if (here->bits) {
335 ret = getc(in);
336 if (ret == -1) {
337 ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR;
338 goto extract_ret;
339 }
340 (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits));
341 }
342 (void)inflateSetDictionary(&strm, here->window, WINSIZE);
343 /* skip uncompressed bytes until offset reached, then satisfy request */
344 offset -= decode_offset(here->out);
345 strm.avail_in = 0;
346 skip = 1; /* while skipping to offset */
347 do {
348 /* define where to put uncompressed data, and how much */
349 if (offset == 0 && skip) { /* at offset now */
350 strm.avail_out = len;
351 strm.next_out = buf;
352 skip = 0; /* only do this once */
353 }
354 if (offset > WINSIZE) { /* skip WINSIZE bytes */
355 strm.avail_out = WINSIZE;
356 strm.next_out = discard;
357 offset -= WINSIZE;
358 } else if (offset != 0) { /* last skip */
359 strm.avail_out = (unsigned)offset;
360 strm.next_out = discard;
361 offset = 0;
362 }
363 /* uncompress until avail_out filled, or end of stream */
364 do {
365 if (strm.avail_in == 0) {
366 strm.avail_in = fread(input, 1, CHUNK, in);
367 if (ferror(in)) {
368 ret = Z_ERRNO;
369 goto extract_ret;
370 }
371 if (strm.avail_in == 0) {
372 ret = Z_DATA_ERROR;
373 goto extract_ret;
374 }
375 strm.next_in = input;
376 }
377 ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */
378 if (ret == Z_NEED_DICT)
379 ret = Z_DATA_ERROR;
380 if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
381 goto extract_ret;
382 if (ret == Z_STREAM_END)
383 break;
384 } while (strm.avail_out != 0);
385
386 /* if reach end of stream, then don't keep trying to get more */
387 if (ret == Z_STREAM_END)
388 break;
389 /* do until offset reached and requested data read, or stream ends */
390 } while (skip);
391
392 /* compute number of uncompressed bytes read after offset */
393 ret = skip ? 0 : len - strm.avail_out;
394
395 /* clean up and return bytes read or error */
396 extract_ret:
397 (void)inflateEnd(&strm);
398 return ret;
399 }
400
401 int extract_data_from_file(const char* file, struct gzip_zinfo* index, offset_t offset, void* buf, int len) {
402 FILE* fp = fopen(file, "rb");
403 if (fp == NULL)
404 return GZIP_ZINFO_FILE_NOT_FOUND;
405
406 int ret = extract_data_from_fp(fp, index, offset, buf, len);
407 fclose(fp);
408 return ret;
409 }
410
411 // This is the same as extract_data_fp, but instead of a file, it decompresses
412 // data from a buffer which contains the exact data to decompress
413 int extract_data_from_buffer(void *d, offset_t datalen,
414 struct gzip_zinfo *index, offset_t offset,
415 void *buffer, offset_t len, int first_checkpoint) {
416 int ret, skip;
417 z_stream strm;
418 unsigned char input[CHUNK], discard[WINSIZE];
419 uchar *buf = buffer;
420 uchar *data = d;
421 /* proceed only if something reasonable to do */
422 if (len < 0)
423 return 0;
424
425 uint8_t bits = get_bits(index, first_checkpoint);
426
427 /* initialize inflate */
428 ret = init_flate(&strm, -15); /* raw inflate */
429 if (ret != Z_OK)
430 return ret;
431
432 if (bits) {
433 int ret = data[0];
434 inflatePrime(&strm, bits, ret >> (8 - bits));
435 data++;
436 }
437 (void)inflateSetDictionary(&strm, index->list[first_checkpoint].window,
438 WINSIZE);
439 offset -= decode_offset(index->list[first_checkpoint].out);
440 strm.avail_in = 0;
441 skip = 1; /* while skipping to offset */
442 int remaining = datalen;
443 do {
444 /* define where to put uncompressed data, and how much */
445 if (offset == 0 && skip) { /* at offset now */
446 strm.avail_out = len;
447 strm.next_out = buf;
448 skip = 0; /* only do this once */
449 }
450 if (offset > WINSIZE) { /* skip WINSIZE bytes */
451 strm.avail_out = WINSIZE;
452 strm.next_out = discard;
453 offset -= WINSIZE;
454 } else if (offset != 0) { /* last skip */
455 strm.avail_out = (unsigned)offset;
456 strm.next_out = discard;
457 offset = 0;
458 }
459 /* uncompress until avail_out filled, or end of stream */
460 do {
461 if (strm.avail_in == 0) {
462 int read = min(remaining, CHUNK);
463 remaining -= read;
464 memcpy(input, data, read);
465 data += read;
466 strm.avail_in = read;
467 strm.next_in = input;
468 }
469 ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */
470 if (ret == Z_NEED_DICT)
471 ret = Z_DATA_ERROR;
472 if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
473 goto extract_ret;
474 if (ret == Z_STREAM_END)
475 break;
476 } while (strm.avail_out != 0);
477
478 /* if reach end of stream, then don't keep trying to get more */
479 if (ret == Z_STREAM_END)
480 break;
481
482 /* do until offset reached and requested data read, or stream ends */
483 } while (skip);
484
485 /* compute number of uncompressed bytes read after offset */
486 ret = skip ? 0 : len - strm.avail_out;
487
488 /* clean up and return bytes read or error */
489 extract_ret:
490 (void)inflateEnd(&strm);
491 return ret;
492 }
493
494 // zinfo - generation/extraction ends.
495
496 // zinfo - zinfo <-> blob conversion starts.
497 int zinfo_to_blob(struct gzip_zinfo* index, void* buf) {
498 if (index == NULL)
499 return GZIP_ZINFO_INDEX_NULL;
500
501 // TODO: Since this will be serialized to file, we need to be mindful of endianness. Right now, we are just ignoring it
502 // Or maybe not, since Golang might take care of it
503 if (buf == NULL)
504 return 0;
505
506 uchar* cur = buf;
507 int32_t first_checkpoint_index;
508 memcpy(cur, &index->have, 4);
509 cur += 4;
510 memcpy(cur, &index->span_size, 8);
511 cur += 8;
512 first_checkpoint_index = 0;
513 // in v1, we skipped the 0th checkpoint becasue we assumed it was fixed size.
514 // in v2, we encode the 0th block because it's not a fixed size if gzip headers are used.
515 // for backwards compatibility we want to reserialize v1 zinfo to exactly the same bytes
516 // even though there is technically a bug.
517 if (decode_int32(index->version) == ZINFO_VERSION_ONE)
518 first_checkpoint_index = 1;
519
520 for(int i = first_checkpoint_index; i < decode_int32(index->have); i++) {
521 struct gzip_checkpoint* pt = &index->list[i];
522 memcpy(cur, &pt->in, 8);
523 cur += 8;
524 memcpy(cur, &pt->out, 8);
525 cur += 8;
526 memcpy(cur, &pt->bits, 1);
527 cur += 1;
528 memcpy(cur, &pt->window, WINSIZE);
529 cur += WINSIZE;
530 }
531
532 return get_blob_size(index);
533 }
534
535 struct gzip_zinfo* blob_to_zinfo(void* buf, offset_t len) {
536 if (buf == NULL)
537 return NULL;
538
539 if (len < BLOB_HEADER_SIZE)
540 return NULL;
541
542 struct gzip_zinfo* index = malloc(sizeof(struct gzip_zinfo));
543 if (index == NULL)
544 return NULL;
545
546 int32_t size, first_checkpoint_index, version;
547 offset_t claimed_size, span_size;
548
549 uchar* cur = buf;
550 memcpy(&size, cur, 4);
551 cur += 4;
552 memcpy(&span_size, cur, 8);
553 cur += 8;
554
555 claimed_size = PACKED_CHECKPOINT_SIZE * decode_int32(size) + BLOB_HEADER_SIZE;
556 if (claimed_size == len) {
557 // If we have exactly size checkpoints, then we have a current blob
558 version = ZINFO_VERSION_CUR;
559 } else if (claimed_size - PACKED_CHECKPOINT_SIZE == len) {
560 // If we only have size - 1 checkpoints, then we have a v1 blob
561 version = ZINFO_VERSION_ONE;
562 } else {
563 // size is invalid. don't attempt to deserialize any more data.
564 return NULL;
565 }
566
567 index->list = malloc(sizeof(struct gzip_checkpoint) * decode_int32(size));
568 if (index->list == NULL) {
569 free_zinfo(index);
570 return NULL;
571 }
572
573 first_checkpoint_index = 0;
574 index->version = encode_int32(version);
575
576 if (version == ZINFO_VERSION_ONE) {
577 first_checkpoint_index = 1;
578 struct gzip_checkpoint* pt0 = &index->list[0];
579 pt0->bits = 0;
580 pt0->in = encode_offset(10);
581 pt0->out = 0;
582 memset(pt0->window, 0, WINSIZE);
583 }
584
585 for(int32_t i = first_checkpoint_index; i < decode_int32(size); i++) {
586 struct gzip_checkpoint* pt = &index->list[i];
587 memcpy(&pt->in, cur, 8);
588 cur += 8;
589 memcpy(&pt->out, cur, 8);
590 cur += 8;
591 memcpy(&pt->bits, cur, 1);
592 cur += 1;
593 memcpy(&pt->window, cur, WINSIZE);
594 cur += WINSIZE;
595 }
596
597 index->have = size;
598 index->size = size;
599 index->span_size = span_size;
600
601 return index;
602 }
603
604 // zinfo - zinfo <-> blob conversion ends.