1//
2// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
3//
4// Distributed under the Boost Software License, Version 1.0. (See accompanying
5// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6//
7// Official repository: https://github.com/boostorg/beast
8//
9// This is a derivative work based on Zlib, copyright below:
10/*
11 Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
12
13 This software is provided 'as-is', without any express or implied
14 warranty. In no event will the authors be held liable for any damages
15 arising from the use of this software.
16
17 Permission is granted to anyone to use this software for any purpose,
18 including commercial applications, and to alter it and redistribute it
19 freely, subject to the following restrictions:
20
21 1. The origin of this software must not be misrepresented; you must not
22 claim that you wrote the original software. If you use this software
23 in a product, an acknowledgment in the product documentation would be
24 appreciated but is not required.
25 2. Altered source versions must be plainly marked as such, and must not be
26 misrepresented as being the original software.
27 3. This notice may not be removed or altered from any source distribution.
28
29 Jean-loup Gailly Mark Adler
30 jloup@gzip.org madler@alumni.caltech.edu
31
32 The data format used by the zlib library is described by RFCs (Request for
33 Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
34 (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
35*/
36
37#ifndef BOOST_BEAST_ZLIB_DETAIL_INFLATE_STREAM_IPP
38#define BOOST_BEAST_ZLIB_DETAIL_INFLATE_STREAM_IPP
39
40#include <boost/beast/zlib/detail/inflate_stream.hpp>
41#include <boost/throw_exception.hpp>
42#include <array>
43
44namespace boost {
45namespace beast {
46namespace zlib {
47namespace detail {
48
49void
50inflate_stream::
51doClear()
52{
53}
54
55void
56inflate_stream::
57doReset(int windowBits)
58{
59 if(windowBits < 8 || windowBits > 15)
60 BOOST_THROW_EXCEPTION(std::domain_error{
61 "windowBits out of range"});
62 w_.reset(bits: windowBits);
63
64 bi_.flush();
65 mode_ = HEAD;
66 last_ = 0;
67 dmax_ = 32768U;
68 lencode_ = codes_;
69 distcode_ = codes_;
70 next_ = codes_;
71 back_ = -1;
72}
73
74void
75inflate_stream::
76doWrite(z_params& zs, Flush flush, error_code& ec)
77{
78 ranges r;
79 r.in.first = static_cast<
80 std::uint8_t const*>(zs.next_in);
81 r.in.last = r.in.first + zs.avail_in;
82 r.in.next = r.in.first;
83 r.out.first = static_cast<
84 std::uint8_t*>(zs.next_out);
85 r.out.last = r.out.first + zs.avail_out;
86 r.out.next = r.out.first;
87
88 auto const done =
89 [&]
90 {
91 /*
92 Return from inflate(), updating the total counts and the check value.
93 If there was no progress during the inflate() call, return a buffer
94 error. Call updatewindow() to create and/or update the window state.
95 Note: a memory error from inflate() is non-recoverable.
96 */
97
98
99 // VFALCO TODO Don't allocate update the window unless necessary
100 if(/*wsize_ ||*/ (r.out.used() && mode_ < BAD &&
101 (mode_ < CHECK || flush != Flush::finish)))
102 w_.write(in: r.out.first, n: r.out.used());
103
104 zs.next_in = r.in.next;
105 zs.avail_in = r.in.avail();
106 zs.next_out = r.out.next;
107 zs.avail_out = r.out.avail();
108 zs.total_in += r.in.used();
109 zs.total_out += r.out.used();
110 zs.data_type = bi_.size() + (last_ ? 64 : 0) +
111 (mode_ == TYPE ? 128 : 0) +
112 (mode_ == LEN_ || mode_ == COPY_ ? 256 : 0);
113
114 if(((! r.in.used() && ! r.out.used()) ||
115 flush == Flush::finish) && ! ec)
116 {
117 BOOST_BEAST_ASSIGN_EC(ec, error::need_buffers);
118 }
119 };
120 auto const err =
121 [&](error e)
122 {
123 BOOST_BEAST_ASSIGN_EC(ec, e);
124 mode_ = BAD;
125 };
126
127 if(mode_ == TYPE)
128 mode_ = TYPEDO;
129
130 for(;;)
131 {
132 switch(mode_)
133 {
134 case HEAD:
135 mode_ = TYPEDO;
136 break;
137
138 case TYPE:
139 if(flush == Flush::block || flush == Flush::trees)
140 return done();
141 // fall through
142
143 case TYPEDO:
144 {
145 if(last_)
146 {
147 bi_.flush_byte();
148 mode_ = CHECK;
149 break;
150 }
151 if(! bi_.fill(n: 3, first&: r.in.next, last: r.in.last))
152 return done();
153 std::uint8_t v;
154 bi_.read(value&: v, n: 1);
155 last_ = v != 0;
156 bi_.read(value&: v, n: 2);
157 switch(v)
158 {
159 case 0:
160 // uncompressed block
161 mode_ = STORED;
162 break;
163 case 1:
164 // fixed Huffman table
165 fixedTables();
166 mode_ = LEN_; /* decode codes */
167 if(flush == Flush::trees)
168 return done();
169 break;
170 case 2:
171 // dynamic Huffman table
172 mode_ = TABLE;
173 break;
174
175 default:
176 return err(error::invalid_block_type);
177 }
178 break;
179 }
180
181 case STORED:
182 {
183 bi_.flush_byte();
184 std::uint32_t v;
185 if(! bi_.fill(n: 32, first&: r.in.next, last: r.in.last))
186 return done();
187 bi_.peek(value&: v, n: 32);
188 length_ = v & 0xffff;
189 if(length_ != ((v >> 16) ^ 0xffff))
190 return err(error::invalid_stored_length);
191 // flush instead of read, otherwise
192 // undefined right shift behavior.
193 bi_.flush();
194 mode_ = COPY_;
195 if(flush == Flush::trees)
196 return done();
197 BOOST_FALLTHROUGH;
198 }
199
200 case COPY_:
201 mode_ = COPY;
202 BOOST_FALLTHROUGH;
203
204 case COPY:
205 {
206 auto copy = length_;
207 if(copy == 0)
208 {
209 mode_ = TYPE;
210 break;
211 }
212 copy = clamp(u: copy, v: r.in.avail());
213 copy = clamp(u: copy, v: r.out.avail());
214 if(copy == 0)
215 return done();
216 std::memcpy(dest: r.out.next, src: r.in.next, n: copy);
217 r.in.next += copy;
218 r.out.next += copy;
219 length_ -= copy;
220 break;
221 }
222
223 case TABLE:
224 if(! bi_.fill(n: 5 + 5 + 4, first&: r.in.next, last: r.in.last))
225 return done();
226 bi_.read(value&: nlen_, n: 5);
227 nlen_ += 257;
228 bi_.read(value&: ndist_, n: 5);
229 ndist_ += 1;
230 bi_.read(value&: ncode_, n: 4);
231 ncode_ += 4;
232 if(nlen_ > 286 || ndist_ > 30)
233 return err(error::too_many_symbols);
234 have_ = 0;
235 mode_ = LENLENS;
236 BOOST_FALLTHROUGH;
237
238 case LENLENS:
239 {
240 static std::array<std::uint8_t, 19> constexpr order = {._M_elems: {
241 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}};
242 while(have_ < ncode_)
243 {
244 if(! bi_.fill(n: 3, first&: r.in.next, last: r.in.last))
245 return done();
246 bi_.read(value&: lens_[order[have_]], n: 3);
247 ++have_;
248 }
249 while(have_ < order.size())
250 lens_[order[have_++]] = 0;
251
252 next_ = &codes_[0];
253 lencode_ = next_;
254 lenbits_ = 7;
255 inflate_table(type: build::codes, lens: &lens_[0],
256 codes: order.size(), table: &next_, bits: &lenbits_, work: work_, ec);
257 if(ec)
258 {
259 mode_ = BAD;
260 break;
261 }
262 have_ = 0;
263 mode_ = CODELENS;
264 BOOST_FALLTHROUGH;
265 }
266
267 case CODELENS:
268 {
269 while(have_ < nlen_ + ndist_)
270 {
271 std::uint16_t v;
272 if(! bi_.fill(n: lenbits_, first&: r.in.next, last: r.in.last))
273 return done();
274 bi_.peek(value&: v, n: lenbits_);
275 auto cp = &lencode_[v];
276 if(cp->val < 16)
277 {
278 bi_.drop(n: cp->bits);
279 lens_[have_++] = cp->val;
280 }
281 else
282 {
283 std::uint16_t len;
284 std::uint16_t copy;
285 if(cp->val == 16)
286 {
287 if(! bi_.fill(n: cp->bits + 2, first&: r.in.next, last: r.in.last))
288 return done();
289 bi_.drop(n: cp->bits);
290 if(have_ == 0)
291 return err(error::invalid_bit_length_repeat);
292 bi_.read(value&: copy, n: 2);
293 len = lens_[have_ - 1];
294 copy += 3;
295
296 }
297 else if(cp->val == 17)
298 {
299 if(! bi_.fill(n: cp->bits + 3, first&: r.in.next, last: r.in.last))
300 return done();
301 bi_.drop(n: cp->bits);
302 bi_.read(value&: copy, n: 3);
303 len = 0;
304 copy += 3;
305 }
306 else
307 {
308 if(! bi_.fill(n: cp->bits + 7, first&: r.in.next, last: r.in.last))
309 return done();
310 bi_.drop(n: cp->bits);
311 bi_.read(value&: copy, n: 7);
312 len = 0;
313 copy += 11;
314 }
315 if(have_ + copy > nlen_ + ndist_)
316 return err(error::invalid_bit_length_repeat);
317 std::fill(first: &lens_[have_], last: &lens_[have_ + copy], value: len);
318 have_ += copy;
319 copy = 0;
320 }
321 }
322 // handle error breaks in while
323 if(mode_ == BAD)
324 break;
325 // check for end-of-block code (better have one)
326 if(lens_[256] == 0)
327 return err(error::missing_eob);
328 /* build code tables -- note: do not change the lenbits or distbits
329 values here (9 and 6) without reading the comments in inftrees.hpp
330 concerning the kEnough constants, which depend on those values */
331 next_ = &codes_[0];
332 lencode_ = next_;
333 lenbits_ = 9;
334 inflate_table(type: build::lens, lens: &lens_[0],
335 codes: nlen_, table: &next_, bits: &lenbits_, work: work_, ec);
336 if(ec)
337 {
338 mode_ = BAD;
339 return;
340 }
341 distcode_ = next_;
342 distbits_ = 6;
343 inflate_table(type: build::dists, lens: lens_ + nlen_,
344 codes: ndist_, table: &next_, bits: &distbits_, work: work_, ec);
345 if(ec)
346 {
347 mode_ = BAD;
348 return;
349 }
350 mode_ = LEN_;
351 if(flush == Flush::trees)
352 return done();
353 BOOST_FALLTHROUGH;
354 }
355
356 case LEN_:
357 mode_ = LEN;
358 BOOST_FALLTHROUGH;
359
360 case LEN:
361 {
362 if(r.in.avail() >= 6 && r.out.avail() >= 258)
363 {
364 inflate_fast(r, ec);
365 if(ec)
366 {
367 mode_ = BAD;
368 return;
369 }
370 if(mode_ == TYPE)
371 back_ = -1;
372 break;
373 }
374 if(! bi_.fill(n: lenbits_, first&: r.in.next, last: r.in.last))
375 return done();
376 std::uint16_t v;
377 back_ = 0;
378 bi_.peek(value&: v, n: lenbits_);
379 auto cp = &lencode_[v];
380 if(cp->op && (cp->op & 0xf0) == 0)
381 {
382 auto prev = cp;
383 if(! bi_.fill(n: prev->bits + prev->op, first&: r.in.next, last: r.in.last))
384 return done();
385 bi_.peek(value&: v, n: prev->bits + prev->op);
386 cp = &lencode_[prev->val + (v >> prev->bits)];
387 bi_.drop(n: prev->bits + cp->bits);
388 back_ += prev->bits + cp->bits;
389 }
390 else
391 {
392 bi_.drop(n: cp->bits);
393 back_ += cp->bits;
394 }
395 length_ = cp->val;
396 if(cp->op == 0)
397 {
398 mode_ = LIT;
399 break;
400 }
401 if(cp->op & 32)
402 {
403 back_ = -1;
404 mode_ = TYPE;
405 break;
406 }
407 if(cp->op & 64)
408 return err(error::invalid_literal_length);
409 extra_ = cp->op & 15;
410 mode_ = LENEXT;
411 BOOST_FALLTHROUGH;
412 }
413
414 case LENEXT:
415 if(extra_)
416 {
417 if(! bi_.fill(n: extra_, first&: r.in.next, last: r.in.last))
418 return done();
419 std::uint16_t v;
420 bi_.read(value&: v, n: extra_);
421 length_ += v;
422 back_ += extra_;
423 }
424 was_ = length_;
425 mode_ = DIST;
426 BOOST_FALLTHROUGH;
427
428 case DIST:
429 {
430 if(! bi_.fill(n: distbits_, first&: r.in.next, last: r.in.last))
431 return done();
432 std::uint16_t v;
433 bi_.peek(value&: v, n: distbits_);
434 auto cp = &distcode_[v];
435 if((cp->op & 0xf0) == 0)
436 {
437 auto prev = cp;
438 if(! bi_.fill(n: prev->bits + prev->op, first&: r.in.next, last: r.in.last))
439 return done();
440 bi_.peek(value&: v, n: prev->bits + prev->op);
441 cp = &distcode_[prev->val + (v >> prev->bits)];
442 bi_.drop(n: prev->bits + cp->bits);
443 back_ += prev->bits + cp->bits;
444 }
445 else
446 {
447 bi_.drop(n: cp->bits);
448 back_ += cp->bits;
449 }
450 if(cp->op & 64)
451 return err(error::invalid_distance_code);
452 offset_ = cp->val;
453 extra_ = cp->op & 15;
454 mode_ = DISTEXT;
455 BOOST_FALLTHROUGH;
456 }
457
458 case DISTEXT:
459 if(extra_)
460 {
461 std::uint16_t v;
462 if(! bi_.fill(n: extra_, first&: r.in.next, last: r.in.last))
463 return done();
464 bi_.read(value&: v, n: extra_);
465 offset_ += v;
466 back_ += extra_;
467 }
468#ifdef INFLATE_STRICT
469 if(offset_ > dmax_)
470 return err(error::invalid_distance);
471#endif
472 mode_ = MATCH;
473 BOOST_FALLTHROUGH;
474
475 case MATCH:
476 {
477 if(! r.out.avail())
478 return done();
479 if(offset_ > r.out.used())
480 {
481 // copy from window
482 auto offset = static_cast<std::uint16_t>(
483 offset_ - r.out.used());
484 if(offset > w_.size())
485 return err(error::invalid_distance);
486 auto const n = clamp(u: clamp(
487 u: length_, v: offset), v: r.out.avail());
488 w_.read(out: r.out.next, pos: offset, n);
489 r.out.next += n;
490 length_ -= n;
491 }
492 else
493 {
494 // copy from output
495 auto in = r.out.next - offset_;
496 auto n = clamp(u: length_, v: r.out.avail());
497 length_ -= n;
498 while(n--)
499 *r.out.next++ = *in++;
500 }
501 if(length_ == 0)
502 mode_ = LEN;
503 break;
504 }
505
506 case LIT:
507 {
508 if(! r.out.avail())
509 return done();
510 auto const v = static_cast<std::uint8_t>(length_);
511 *r.out.next++ = v;
512 mode_ = LEN;
513 break;
514 }
515
516 case CHECK:
517 mode_ = DONE;
518 BOOST_FALLTHROUGH;
519
520 case DONE:
521 {
522 BOOST_BEAST_ASSIGN_EC(ec, error::end_of_stream);
523 return done();
524 }
525
526 case BAD:
527 return done();
528
529 case SYNC:
530 default:
531 BOOST_THROW_EXCEPTION(std::logic_error{
532 "stream error"});
533 }
534 }
535}
536
537//------------------------------------------------------------------------------
538
539/* Build a set of tables to decode the provided canonical Huffman code.
540 The code lengths are lens[0..codes-1]. The result starts at *table,
541 whose indices are 0..2^bits-1. work is a writable array of at least
542 lens shorts, which is used as a work area. type is the type of code
543 to be generated, build::codes, build::lens, or build::dists. On
544 return, zero is success, -1 is an invalid code, and +1 means that
545 kEnough isn't enough. table on return points to the next available
546 entry's address. bits is the requested root table index bits, and
547 on return it is the actual root table index bits. It will differ if
548 the request is greater than the longest code or if it is less than
549 the shortest code.
550*/
551void
552inflate_stream::
553inflate_table(
554 build type,
555 std::uint16_t* lens,
556 std::size_t codes,
557 code** table,
558 unsigned *bits,
559 std::uint16_t* work,
560 error_code& ec)
561{
562 unsigned len; // a code's length in bits
563 unsigned sym; // index of code symbols
564 unsigned min, max; // minimum and maximum code lengths
565 unsigned root; // number of index bits for root table
566 unsigned curr; // number of index bits for current table
567 unsigned drop; // code bits to drop for sub-table
568 int left; // number of prefix codes available
569 unsigned used; // code entries in table used
570 unsigned huff; // Huffman code
571 unsigned incr; // for incrementing code, index
572 unsigned fill; // index for replicating entries
573 unsigned low; // low bits for current root entry
574 unsigned mask; // mask for low root bits
575 code here; // table entry for duplication
576 code *next; // next available space in table
577 std::uint16_t const* base; // base value table to use
578 std::uint16_t const* extra; // extra bits table to use
579 unsigned match; // use base and extra for symbol >= match
580 std::uint16_t count[15+1]; // number of codes of each length
581 std::uint16_t offs[15+1]; // offsets in table for each length
582
583 // Length codes 257..285 base
584 static std::uint16_t constexpr lbase[31] = {
585 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
586 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
587
588 // Length codes 257..285 extra
589 static std::uint16_t constexpr lext[31] = {
590 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
591 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202};
592
593 // Distance codes 0..29 base
594 static std::uint16_t constexpr dbase[32] = {
595 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
596 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
597 8193, 12289, 16385, 24577, 0, 0};
598
599 // Distance codes 0..29 extra
600 static std::uint16_t constexpr dext[32] = {
601 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
602 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
603 28, 28, 29, 29, 64, 64};
604
605 /*
606 Process a set of code lengths to create a canonical Huffman code. The
607 code lengths are lens[0..codes-1]. Each length corresponds to the
608 symbols 0..codes-1. The Huffman code is generated by first sorting the
609 symbols by length from short to long, and retaining the symbol order
610 for codes with equal lengths. Then the code starts with all zero bits
611 for the first code of the shortest length, and the codes are integer
612 increments for the same length, and zeros are appended as the length
613 increases. For the deflate format, these bits are stored backwards
614 from their more natural integer increment ordering, and so when the
615 decoding tables are built in the large loop below, the integer codes
616 are incremented backwards.
617
618 This routine assumes, but does not check, that all of the entries in
619 lens[] are in the range 0..15. The caller must assure this.
620 1..15 is interpreted as that code length. zero means that that
621 symbol does not occur in this code.
622
623 The codes are sorted by computing a count of codes for each length,
624 creating from that a table of starting indices for each length in the
625 sorted table, and then entering the symbols in order in the sorted
626 table. The sorted table is work[], with that space being provided by
627 the caller.
628
629 The length counts are used for other purposes as well, i.e. finding
630 the minimum and maximum length codes, determining if there are any
631 codes at all, checking for a valid set of lengths, and looking ahead
632 at length counts to determine sub-table sizes when building the
633 decoding tables.
634 */
635
636 /* accumulate lengths for codes (assumes lens[] all in 0..15) */
637 for (len = 0; len <= 15; len++)
638 count[len] = 0;
639 for (sym = 0; sym < codes; sym++)
640 count[lens[sym]]++;
641
642 /* bound code lengths, force root to be within code lengths */
643 root = *bits;
644 for (max = 15; max >= 1; max--)
645 if (count[max] != 0)
646 break;
647 if (root > max)
648 root = max;
649 if (max == 0)
650 { /* no symbols to code at all */
651 here.op = (std::uint8_t)64; /* invalid code marker */
652 here.bits = (std::uint8_t)1;
653 here.val = (std::uint16_t)0;
654 *(*table)++ = here; /* make a table to force an error */
655 *(*table)++ = here;
656 *bits = 1;
657 return; /* no symbols, but wait for decoding to report error */
658 }
659 for (min = 1; min < max; min++)
660 if (count[min] != 0)
661 break;
662 if (root < min)
663 root = min;
664
665 /* check for an over-subscribed or incomplete set of lengths */
666 left = 1;
667 for (len = 1; len <= 15; len++)
668 {
669 left <<= 1;
670 left -= count[len];
671 if (left < 0)
672 {
673 BOOST_BEAST_ASSIGN_EC(ec, error::over_subscribed_length);
674 return;
675 }
676 }
677 if (left > 0 && (type == build::codes || max != 1))
678 {
679 BOOST_BEAST_ASSIGN_EC(ec, error::incomplete_length_set);
680 return;
681 }
682
683 /* generate offsets into symbol table for each length for sorting */
684 offs[1] = 0;
685 for (len = 1; len < 15; len++)
686 offs[len + 1] = offs[len] + count[len];
687
688 /* sort symbols by length, by symbol order within each length */
689 for (sym = 0; sym < codes; sym++)
690 if (lens[sym] != 0)
691 work[offs[lens[sym]]++] = (std::uint16_t)sym;
692
693 /*
694 Create and fill in decoding tables. In this loop, the table being
695 filled is at next and has curr index bits. The code being used is huff
696 with length len. That code is converted to an index by dropping drop
697 bits off of the bottom. For codes where len is less than drop + curr,
698 those top drop + curr - len bits are incremented through all values to
699 fill the table with replicated entries.
700
701 root is the number of index bits for the root table. When len exceeds
702 root, sub-tables are created pointed to by the root entry with an index
703 of the low root bits of huff. This is saved in low to check for when a
704 new sub-table should be started. drop is zero when the root table is
705 being filled, and drop is root when sub-tables are being filled.
706
707 When a new sub-table is needed, it is necessary to look ahead in the
708 code lengths to determine what size sub-table is needed. The length
709 counts are used for this, and so count[] is decremented as codes are
710 entered in the tables.
711
712 used keeps track of how many table entries have been allocated from the
713 provided *table space. It is checked for build::lens and DIST tables against
714 the constants kEnoughLens and kEnoughDists to guard against changes in
715 the initial root table size constants. See the comments in inftrees.hpp
716 for more information.
717
718 sym increments through all symbols, and the loop terminates when
719 all codes of length max, i.e. all codes, have been processed. This
720 routine permits incomplete codes, so another loop after this one fills
721 in the rest of the decoding tables with invalid code markers.
722 */
723
724 /* set up for code type */
725 switch (type)
726 {
727 case build::codes:
728 base = extra = work; /* dummy value--not used */
729 match = 20;
730 break;
731 case build::lens:
732 base = lbase;
733 extra = lext;
734 match = 257;
735 break;
736 default: /* build::dists */
737 base = dbase;
738 extra = dext;
739 match = 0;
740 }
741
742 /* initialize state for loop */
743 huff = 0; /* starting code */
744 sym = 0; /* starting code symbol */
745 len = min; /* starting code length */
746 next = *table; /* current table to fill in */
747 curr = root; /* current table index bits */
748 drop = 0; /* current bits to drop from code for index */
749 low = (unsigned)(-1); /* trigger new sub-table when len > root */
750 used = 1U << root; /* use root table entries */
751 mask = used - 1; /* mask for comparing low */
752
753 auto const not_enough = []
754 {
755 BOOST_THROW_EXCEPTION(std::logic_error{
756 "insufficient output size when inflating tables"});
757 };
758
759 // check available table space
760 if ((type == build::lens && used > kEnoughLens) ||
761 (type == build::dists && used > kEnoughDists))
762 return not_enough();
763
764 /* process all codes and make table entries */
765 for (;;)
766 {
767 /* create table entry */
768 here.bits = (std::uint8_t)(len - drop);
769 if (work[sym] + 1U < match)
770 {
771 here.op = (std::uint8_t)0;
772 here.val = work[sym];
773 }
774 else if (work[sym] >= match)
775 {
776 here.op = (std::uint8_t)(extra[work[sym] - match]);
777 here.val = base[work[sym] - match];
778 }
779 else
780 {
781 here.op = (std::uint8_t)(32 + 64); /* end of block */
782 here.val = 0;
783 }
784
785 /* replicate for those indices with low len bits equal to huff */
786 incr = 1U << (len - drop);
787 fill = 1U << curr;
788 min = fill; /* save offset to next table */
789 do
790 {
791 fill -= incr;
792 next[(huff >> drop) + fill] = here;
793 } while (fill != 0);
794
795 /* backwards increment the len-bit code huff */
796 incr = 1U << (len - 1);
797 while (huff & incr)
798 incr >>= 1;
799 if (incr != 0)
800 {
801 huff &= incr - 1;
802 huff += incr;
803 }
804 else
805 huff = 0;
806
807 /* go to next symbol, update count, len */
808 sym++;
809 if (--(count[len]) == 0)
810 {
811 if (len == max) break;
812 len = lens[work[sym]];
813 }
814
815 /* create new sub-table if needed */
816 if (len > root && (huff & mask) != low)
817 {
818 /* if first time, transition to sub-tables */
819 if (drop == 0)
820 drop = root;
821
822 /* increment past last table */
823 next += min; /* here min is 1 << curr */
824
825 /* determine length of next table */
826 curr = len - drop;
827 left = (int)(1 << curr);
828 while (curr + drop < max)
829 {
830 left -= count[curr + drop];
831 if (left <= 0) break;
832 curr++;
833 left <<= 1;
834 }
835
836 /* check for enough space */
837 used += 1U << curr;
838 if ((type == build::lens && used > kEnoughLens) ||
839 (type == build::dists && used > kEnoughDists))
840 return not_enough();
841
842 /* point entry in root table to sub-table */
843 low = huff & mask;
844 (*table)[low].op = (std::uint8_t)curr;
845 (*table)[low].bits = (std::uint8_t)root;
846 (*table)[low].val = (std::uint16_t)(next - *table);
847 }
848 }
849
850 /* fill in remaining table entry if code is incomplete (guaranteed to have
851 at most one remaining entry, since if the code is incomplete, the
852 maximum code length that was allowed to get this far is one bit) */
853 if (huff != 0)
854 {
855 here.op = 64; // invalid code marker
856 here.bits = (std::uint8_t)(len - drop);
857 here.val = 0;
858 next[huff] = here;
859 }
860
861 *table += used;
862 *bits = root;
863}
864
865auto
866inflate_stream::
867get_fixed_tables() ->
868 codes const&
869{
870 struct fixed_codes : codes
871 {
872 code len_[512];
873 code dist_[32];
874
875 fixed_codes()
876 {
877 lencode = len_;
878 lenbits = 9;
879 distcode = dist_;
880 distbits = 5;
881
882 std::uint16_t lens[320];
883 std::uint16_t work[288];
884
885 std::fill(first: &lens[ 0], last: &lens[144], value: std::uint16_t{8});
886 std::fill(first: &lens[144], last: &lens[256], value: std::uint16_t{9});
887 std::fill(first: &lens[256], last: &lens[280], value: std::uint16_t{7});
888 std::fill(first: &lens[280], last: &lens[288], value: std::uint16_t{8});
889
890 {
891 error_code ec;
892 auto next = &len_[0];
893 inflate_table(type: build::lens,
894 lens, codes: 288, table: &next, bits: &lenbits, work, ec);
895 if(ec)
896 BOOST_THROW_EXCEPTION(std::logic_error{ec.message()});
897 }
898
899 // VFALCO These fixups are from ZLib
900 len_[ 99].op = 64;
901 len_[227].op = 64;
902 len_[355].op = 64;
903 len_[483].op = 64;
904
905 {
906 error_code ec;
907 auto next = &dist_[0];
908 std::fill(first: &lens[0], last: &lens[32], value: std::uint16_t{5});
909 inflate_table(type: build::dists,
910 lens, codes: 32, table: &next, bits: &distbits, work, ec);
911 if(ec)
912 BOOST_THROW_EXCEPTION(std::logic_error{ec.message()});
913 }
914 }
915 };
916
917 static fixed_codes const fc;
918 return fc;
919}
920
921void
922inflate_stream::
923fixedTables()
924{
925 auto const fc = get_fixed_tables();
926 lencode_ = fc.lencode;
927 lenbits_ = fc.lenbits;
928 distcode_ = fc.distcode;
929 distbits_ = fc.distbits;
930}
931
932/*
933 Decode literal, length, and distance codes and write out the resulting
934 literal and match bytes until either not enough input or output is
935 available, an end-of-block is encountered, or a data error is encountered.
936 When large enough input and output buffers are supplied to inflate(), for
937 example, a 16K input buffer and a 64K output buffer, more than 95% of the
938 inflate execution time is spent in this routine.
939
940 Entry assumptions:
941
942 state->mode_ == LEN
943 zs.avail_in >= 6
944 zs.avail_out >= 258
945 start >= zs.avail_out
946 state->bits_ < 8
947
948 On return, state->mode_ is one of:
949
950 LEN -- ran out of enough output space or enough available input
951 TYPE -- reached end of block code, inflate() to interpret next block
952 BAD -- error in block data
953
954 Notes:
955
956 - The maximum input bits used by a length/distance pair is 15 bits for the
957 length code, 5 bits for the length extra, 15 bits for the distance code,
958 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
959 Therefore if zs.avail_in >= 6, then there is enough input to avoid
960 checking for available input while decoding.
961
962 - The maximum bytes that a single length/distance pair can output is 258
963 bytes, which is the maximum length that can be coded. inflate_fast()
964 requires zs.avail_out >= 258 for each loop to avoid checking for
965 output space.
966
967 inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
968 - Using bit fields for code structure
969 - Different op definition to avoid & for extra bits (do & for table bits)
970 - Three separate decoding do-loops for direct, window, and wnext == 0
971 - Special case for distance > 1 copies to do overlapped load and store copy
972 - Explicit branch predictions (based on measured branch probabilities)
973 - Deferring match copy and interspersed it with decoding subsequent codes
974 - Swapping literal/length else
975 - Swapping window/direct else
976 - Larger unrolled copy loops (three is about right)
977 - Moving len -= 3 statement into middle of loop
978 */
979void
980inflate_stream::
981inflate_fast(ranges& r, error_code& ec)
982{
983 unsigned char const* last; // have enough input while in < last
984 unsigned char *end; // while out < end, enough space available
985 std::size_t op; // code bits, operation, extra bits, or window position, window bytes to copy
986 unsigned len; // match length, unused bytes
987 unsigned dist; // match distance
988 unsigned const lmask =
989 (1U << lenbits_) - 1; // mask for first level of length codes
990 unsigned const dmask =
991 (1U << distbits_) - 1; // mask for first level of distance codes
992
993 last = r.in.next + (r.in.avail() - 5);
994 end = r.out.next + (r.out.avail() - 257);
995
996 /* decode literals and length/distances until end-of-block or not enough
997 input data or output space */
998 do
999 {
1000 if(bi_.size() < 15)
1001 bi_.fill_16(it&: r.in.next);
1002 auto cp = &lencode_[bi_.peek_fast() & lmask];
1003 dolen:
1004 bi_.drop(n: cp->bits);
1005 op = (unsigned)(cp->op);
1006 if(op == 0)
1007 {
1008 // literal
1009 *r.out.next++ = (unsigned char)(cp->val);
1010 }
1011 else if(op & 16)
1012 {
1013 // length base
1014 len = (unsigned)(cp->val);
1015 op &= 15; // number of extra bits
1016 if(op)
1017 {
1018 if(bi_.size() < op)
1019 bi_.fill_8(it&: r.in.next);
1020 len += (unsigned)bi_.peek_fast() & ((1U << op) - 1);
1021 bi_.drop(n: op);
1022 }
1023 if(bi_.size() < 15)
1024 bi_.fill_16(it&: r.in.next);
1025 cp = &distcode_[bi_.peek_fast() & dmask];
1026 dodist:
1027 bi_.drop(n: cp->bits);
1028 op = (unsigned)(cp->op);
1029 if(op & 16)
1030 {
1031 // distance base
1032 dist = (unsigned)(cp->val);
1033 op &= 15; // number of extra bits
1034 if(bi_.size() < op)
1035 {
1036 bi_.fill_8(it&: r.in.next);
1037 if(bi_.size() < op)
1038 bi_.fill_8(it&: r.in.next);
1039 }
1040 dist += (unsigned)bi_.peek_fast() & ((1U << op) - 1);
1041#ifdef INFLATE_STRICT
1042 if(dist > dmax_)
1043 {
1044 BOOST_BEAST_ASSIGN_EC(ec, error::invalid_distance);
1045 mode_ = BAD;
1046 break;
1047 }
1048#endif
1049 bi_.drop(n: op);
1050
1051 op = r.out.used();
1052 if(dist > op)
1053 {
1054 // copy from window
1055 op = dist - op; // distance back in window
1056 if(op > w_.size())
1057 {
1058 BOOST_BEAST_ASSIGN_EC(ec, error::invalid_distance);
1059 mode_ = BAD;
1060 break;
1061 }
1062 auto const n = clamp(u: len, v: op);
1063 w_.read(out: r.out.next, pos: op, n);
1064 r.out.next += n;
1065 len -= n;
1066 }
1067 if(len > 0)
1068 {
1069 // copy from output
1070 auto in = r.out.next - dist;
1071 auto n = clamp(u: len, v: r.out.avail());
1072 len -= n;
1073 while(n--)
1074 *r.out.next++ = *in++;
1075 }
1076 }
1077 else if((op & 64) == 0)
1078 {
1079 // 2nd level distance code
1080 cp = &distcode_[cp->val + (bi_.peek_fast() & ((1U << op) - 1))];
1081 goto dodist;
1082 }
1083 else
1084 {
1085 BOOST_BEAST_ASSIGN_EC(ec, error::invalid_distance_code);
1086 mode_ = BAD;
1087 break;
1088 }
1089 }
1090 else if((op & 64) == 0)
1091 {
1092 // 2nd level length code
1093 cp = &lencode_[cp->val + (bi_.peek_fast() & ((1U << op) - 1))];
1094 goto dolen;
1095 }
1096 else if(op & 32)
1097 {
1098 // end-of-block
1099 mode_ = TYPE;
1100 break;
1101 }
1102 else
1103 {
1104 BOOST_BEAST_ASSIGN_EC(ec, error::invalid_literal_length);
1105 mode_ = BAD;
1106 break;
1107 }
1108 }
1109 while(r.in.next < last && r.out.next < end);
1110
1111 // return unused bytes (on entry, bits < 8, so in won't go too far back)
1112 bi_.rewind(it&: r.in.next);
1113}
1114
1115} // detail
1116} // zlib
1117} // beast
1118} // boost
1119
1120#endif
1121

source code of boost/libs/beast/include/boost/beast/zlib/detail/inflate_stream.ipp