Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

621 lines
16 KiB

  1. // zinflate.cpp - written and placed in the public domain by Wei Dai
  2. // This is a complete reimplementation of the DEFLATE decompression algorithm.
  3. // It should not be affected by any security vulnerabilities in the zlib
  4. // compression library. In particular it is not affected by the double free bug
  5. // (http://www.kb.cert.org/vuls/id/368819).
  6. #include "pch.h"
  7. #include "zinflate.h"
  8. NAMESPACE_BEGIN(CryptoPP)
  9. struct CodeLessThan
  10. {
  11. inline bool operator()(CryptoPP::HuffmanDecoder::code_t lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs)
  12. {return lhs < rhs.code;}
  13. // needed for MSVC .NET 2005
  14. inline bool operator()(const CryptoPP::HuffmanDecoder::CodeInfo &lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs)
  15. {return lhs.code < rhs.code;}
  16. };
  17. inline bool LowFirstBitReader::FillBuffer(unsigned int length)
  18. {
  19. while (m_bitsBuffered < length)
  20. {
  21. byte b;
  22. if (!m_store.Get(b))
  23. return false;
  24. m_buffer |= (unsigned long)b << m_bitsBuffered;
  25. m_bitsBuffered += 8;
  26. }
  27. assert(m_bitsBuffered <= sizeof(unsigned long)*8);
  28. return true;
  29. }
  30. inline unsigned long LowFirstBitReader::PeekBits(unsigned int length)
  31. {
  32. bool result = FillBuffer(length);
  33. assert(result);
  34. return m_buffer & (((unsigned long)1 << length) - 1);
  35. }
  36. inline void LowFirstBitReader::SkipBits(unsigned int length)
  37. {
  38. assert(m_bitsBuffered >= length);
  39. m_buffer >>= length;
  40. m_bitsBuffered -= length;
  41. }
  42. inline unsigned long LowFirstBitReader::GetBits(unsigned int length)
  43. {
  44. unsigned long result = PeekBits(length);
  45. SkipBits(length);
  46. return result;
  47. }
  48. inline HuffmanDecoder::code_t HuffmanDecoder::NormalizeCode(HuffmanDecoder::code_t code, unsigned int codeBits)
  49. {
  50. return code << (MAX_CODE_BITS - codeBits);
  51. }
  52. void HuffmanDecoder::Initialize(const unsigned int *codeBits, unsigned int nCodes)
  53. {
  54. // the Huffman codes are represented in 3 ways in this code:
  55. //
  56. // 1. most significant code bit (i.e. top of code tree) in the least significant bit position
  57. // 2. most significant code bit (i.e. top of code tree) in the most significant bit position
  58. // 3. most significant code bit (i.e. top of code tree) in n-th least significant bit position,
  59. // where n is the maximum code length for this code tree
  60. //
  61. // (1) is the way the codes come in from the deflate stream
  62. // (2) is used to sort codes so they can be binary searched
  63. // (3) is used in this function to compute codes from code lengths
  64. //
  65. // a code in representation (2) is called "normalized" here
  66. // The BitReverse() function is used to convert between (1) and (2)
  67. // The NormalizeCode() function is used to convert from (3) to (2)
  68. if (nCodes == 0)
  69. throw Err("null code");
  70. m_maxCodeBits = *std::max_element(codeBits, codeBits+nCodes);
  71. if (m_maxCodeBits > MAX_CODE_BITS)
  72. throw Err("code length exceeds maximum");
  73. if (m_maxCodeBits == 0)
  74. throw Err("null code");
  75. // count number of codes of each length
  76. SecBlockWithHint<unsigned int, 15+1> blCount(m_maxCodeBits+1);
  77. std::fill(blCount.begin(), blCount.end(), 0);
  78. unsigned int i;
  79. for (i=0; i<nCodes; i++)
  80. blCount[codeBits[i]]++;
  81. // compute the starting code of each length
  82. code_t code = 0;
  83. SecBlockWithHint<code_t, 15+1> nextCode(m_maxCodeBits+1);
  84. nextCode[1] = 0;
  85. for (i=2; i<=m_maxCodeBits; i++)
  86. {
  87. // compute this while checking for overflow: code = (code + blCount[i-1]) << 1
  88. if (code > code + blCount[i-1])
  89. throw Err("codes oversubscribed");
  90. code += blCount[i-1];
  91. if (code > (code << 1))
  92. throw Err("codes oversubscribed");
  93. code <<= 1;
  94. nextCode[i] = code;
  95. }
  96. if (code > (1 << m_maxCodeBits) - blCount[m_maxCodeBits])
  97. throw Err("codes oversubscribed");
  98. else if (m_maxCodeBits != 1 && code < (1 << m_maxCodeBits) - blCount[m_maxCodeBits])
  99. throw Err("codes incomplete");
  100. // compute a vector of <code, length, value> triples sorted by code
  101. m_codeToValue.resize(nCodes - blCount[0]);
  102. unsigned int j=0;
  103. for (i=0; i<nCodes; i++)
  104. {
  105. unsigned int len = codeBits[i];
  106. if (len != 0)
  107. {
  108. code = NormalizeCode(nextCode[len]++, len);
  109. m_codeToValue[j].code = code;
  110. m_codeToValue[j].len = len;
  111. m_codeToValue[j].value = i;
  112. j++;
  113. }
  114. }
  115. std::sort(m_codeToValue.begin(), m_codeToValue.end());
  116. // initialize the decoding cache
  117. m_cacheBits = STDMIN(9U, m_maxCodeBits);
  118. m_cacheMask = (1 << m_cacheBits) - 1;
  119. m_normalizedCacheMask = NormalizeCode(m_cacheMask, m_cacheBits);
  120. assert(m_normalizedCacheMask == BitReverse(m_cacheMask));
  121. if (m_cache.size() != size_t(1) << m_cacheBits)
  122. m_cache.resize(1 << m_cacheBits);
  123. for (i=0; i<m_cache.size(); i++)
  124. m_cache[i].type = 0;
  125. }
  126. void HuffmanDecoder::FillCacheEntry(LookupEntry &entry, code_t normalizedCode) const
  127. {
  128. normalizedCode &= m_normalizedCacheMask;
  129. const CodeInfo &codeInfo = *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode, CodeLessThan())-1);
  130. if (codeInfo.len <= m_cacheBits)
  131. {
  132. entry.type = 1;
  133. entry.value = codeInfo.value;
  134. entry.len = codeInfo.len;
  135. }
  136. else
  137. {
  138. entry.begin = &codeInfo;
  139. const CodeInfo *last = & *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode + ~m_normalizedCacheMask, CodeLessThan())-1);
  140. if (codeInfo.len == last->len)
  141. {
  142. entry.type = 2;
  143. entry.len = codeInfo.len;
  144. }
  145. else
  146. {
  147. entry.type = 3;
  148. entry.end = last+1;
  149. }
  150. }
  151. }
  152. inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value) const
  153. {
  154. assert(m_codeToValue.size() > 0);
  155. LookupEntry &entry = m_cache[code & m_cacheMask];
  156. code_t normalizedCode;
  157. if (entry.type != 1)
  158. normalizedCode = BitReverse(code);
  159. if (entry.type == 0)
  160. FillCacheEntry(entry, normalizedCode);
  161. if (entry.type == 1)
  162. {
  163. value = entry.value;
  164. return entry.len;
  165. }
  166. else
  167. {
  168. const CodeInfo &codeInfo = (entry.type == 2)
  169. ? entry.begin[(normalizedCode << m_cacheBits) >> (MAX_CODE_BITS - (entry.len - m_cacheBits))]
  170. : *(std::upper_bound(entry.begin, entry.end, normalizedCode, CodeLessThan())-1);
  171. value = codeInfo.value;
  172. return codeInfo.len;
  173. }
  174. }
  175. bool HuffmanDecoder::Decode(LowFirstBitReader &reader, value_t &value) const
  176. {
  177. reader.FillBuffer(m_maxCodeBits);
  178. unsigned int codeBits = Decode(reader.PeekBuffer(), value);
  179. if (codeBits > reader.BitsBuffered())
  180. return false;
  181. reader.SkipBits(codeBits);
  182. return true;
  183. }
  184. // *************************************************************
  185. Inflator::Inflator(BufferedTransformation *attachment, bool repeat, int propagation)
  186. : AutoSignaling<Filter>(propagation)
  187. , m_state(PRE_STREAM), m_repeat(repeat), m_reader(m_inQueue)
  188. {
  189. Detach(attachment);
  190. }
  191. void Inflator::IsolatedInitialize(const NameValuePairs &parameters)
  192. {
  193. m_state = PRE_STREAM;
  194. parameters.GetValue("Repeat", m_repeat);
  195. m_inQueue.Clear();
  196. m_reader.SkipBits(m_reader.BitsBuffered());
  197. }
  198. void Inflator::OutputByte(byte b)
  199. {
  200. m_window[m_current++] = b;
  201. if (m_current == m_window.size())
  202. {
  203. ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush);
  204. m_lastFlush = 0;
  205. m_current = 0;
  206. m_wrappedAround = true;
  207. }
  208. }
  209. void Inflator::OutputString(const byte *string, size_t length)
  210. {
  211. while (length)
  212. {
  213. size_t len = UnsignedMin(length, m_window.size() - m_current);
  214. memcpy(m_window + m_current, string, len);
  215. m_current += len;
  216. if (m_current == m_window.size())
  217. {
  218. ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush);
  219. m_lastFlush = 0;
  220. m_current = 0;
  221. m_wrappedAround = true;
  222. }
  223. string += len;
  224. length -= len;
  225. }
  226. }
  227. void Inflator::OutputPast(unsigned int length, unsigned int distance)
  228. {
  229. size_t start;
  230. if (distance <= m_current)
  231. start = m_current - distance;
  232. else if (m_wrappedAround && distance <= m_window.size())
  233. start = m_current + m_window.size() - distance;
  234. else
  235. throw BadBlockErr();
  236. if (start + length > m_window.size())
  237. {
  238. for (; start < m_window.size(); start++, length--)
  239. OutputByte(m_window[start]);
  240. start = 0;
  241. }
  242. if (start + length > m_current || m_current + length >= m_window.size())
  243. {
  244. while (length--)
  245. OutputByte(m_window[start++]);
  246. }
  247. else
  248. {
  249. memcpy(m_window + m_current, m_window + start, length);
  250. m_current += length;
  251. }
  252. }
  253. size_t Inflator::Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
  254. {
  255. if (!blocking)
  256. throw BlockingInputOnly("Inflator");
  257. LazyPutter lp(m_inQueue, inString, length);
  258. ProcessInput(messageEnd != 0);
  259. if (messageEnd)
  260. if (!(m_state == PRE_STREAM || m_state == AFTER_END))
  261. throw UnexpectedEndErr();
  262. Output(0, NULL, 0, messageEnd, blocking);
  263. return 0;
  264. }
  265. bool Inflator::IsolatedFlush(bool hardFlush, bool blocking)
  266. {
  267. if (!blocking)
  268. throw BlockingInputOnly("Inflator");
  269. if (hardFlush)
  270. ProcessInput(true);
  271. FlushOutput();
  272. return false;
  273. }
  274. void Inflator::ProcessInput(bool flush)
  275. {
  276. while (true)
  277. {
  278. switch (m_state)
  279. {
  280. case PRE_STREAM:
  281. if (!flush && m_inQueue.CurrentSize() < MaxPrestreamHeaderSize())
  282. return;
  283. ProcessPrestreamHeader();
  284. m_state = WAIT_HEADER;
  285. m_wrappedAround = false;
  286. m_current = 0;
  287. m_lastFlush = 0;
  288. m_window.New(1 << GetLog2WindowSize());
  289. break;
  290. case WAIT_HEADER:
  291. {
  292. // maximum number of bytes before actual compressed data starts
  293. const size_t MAX_HEADER_SIZE = BitsToBytes(3+5+5+4+19*7+286*15+19*15);
  294. if (m_inQueue.CurrentSize() < (flush ? 1 : MAX_HEADER_SIZE))
  295. return;
  296. DecodeHeader();
  297. break;
  298. }
  299. case DECODING_BODY:
  300. if (!DecodeBody())
  301. return;
  302. break;
  303. case POST_STREAM:
  304. if (!flush && m_inQueue.CurrentSize() < MaxPoststreamTailSize())
  305. return;
  306. ProcessPoststreamTail();
  307. m_state = m_repeat ? PRE_STREAM : AFTER_END;
  308. Output(0, NULL, 0, GetAutoSignalPropagation(), true); // TODO: non-blocking
  309. if (m_inQueue.IsEmpty())
  310. return;
  311. break;
  312. case AFTER_END:
  313. m_inQueue.TransferTo(*AttachedTransformation());
  314. return;
  315. }
  316. }
  317. }
  318. void Inflator::DecodeHeader()
  319. {
  320. if (!m_reader.FillBuffer(3))
  321. throw UnexpectedEndErr();
  322. m_eof = m_reader.GetBits(1) != 0;
  323. m_blockType = (byte)m_reader.GetBits(2);
  324. switch (m_blockType)
  325. {
  326. case 0: // stored
  327. {
  328. m_reader.SkipBits(m_reader.BitsBuffered() % 8);
  329. if (!m_reader.FillBuffer(32))
  330. throw UnexpectedEndErr();
  331. m_storedLen = (word16)m_reader.GetBits(16);
  332. word16 nlen = (word16)m_reader.GetBits(16);
  333. if (nlen != (word16)~m_storedLen)
  334. throw BadBlockErr();
  335. break;
  336. }
  337. case 1: // fixed codes
  338. m_nextDecode = LITERAL;
  339. break;
  340. case 2: // dynamic codes
  341. {
  342. if (!m_reader.FillBuffer(5+5+4))
  343. throw UnexpectedEndErr();
  344. unsigned int hlit = m_reader.GetBits(5);
  345. unsigned int hdist = m_reader.GetBits(5);
  346. unsigned int hclen = m_reader.GetBits(4);
  347. FixedSizeSecBlock<unsigned int, 286+32> codeLengths;
  348. unsigned int i;
  349. static const unsigned int border[] = { // Order of the bit length code lengths
  350. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  351. std::fill(codeLengths.begin(), codeLengths+19, 0);
  352. for (i=0; i<hclen+4; i++)
  353. codeLengths[border[i]] = m_reader.GetBits(3);
  354. try
  355. {
  356. HuffmanDecoder codeLengthDecoder(codeLengths, 19);
  357. for (i = 0; i < hlit+257+hdist+1; )
  358. {
  359. unsigned int k, count, repeater;
  360. bool result = codeLengthDecoder.Decode(m_reader, k);
  361. if (!result)
  362. throw UnexpectedEndErr();
  363. if (k <= 15)
  364. {
  365. count = 1;
  366. repeater = k;
  367. }
  368. else switch (k)
  369. {
  370. case 16:
  371. if (!m_reader.FillBuffer(2))
  372. throw UnexpectedEndErr();
  373. count = 3 + m_reader.GetBits(2);
  374. if (i == 0)
  375. throw BadBlockErr();
  376. repeater = codeLengths[i-1];
  377. break;
  378. case 17:
  379. if (!m_reader.FillBuffer(3))
  380. throw UnexpectedEndErr();
  381. count = 3 + m_reader.GetBits(3);
  382. repeater = 0;
  383. break;
  384. case 18:
  385. if (!m_reader.FillBuffer(7))
  386. throw UnexpectedEndErr();
  387. count = 11 + m_reader.GetBits(7);
  388. repeater = 0;
  389. break;
  390. }
  391. if (i + count > hlit+257+hdist+1)
  392. throw BadBlockErr();
  393. std::fill(codeLengths + i, codeLengths + i + count, repeater);
  394. i += count;
  395. }
  396. m_dynamicLiteralDecoder.Initialize(codeLengths, hlit+257);
  397. if (hdist == 0 && codeLengths[hlit+257] == 0)
  398. {
  399. if (hlit != 0) // a single zero distance code length means all literals
  400. throw BadBlockErr();
  401. }
  402. else
  403. m_dynamicDistanceDecoder.Initialize(codeLengths+hlit+257, hdist+1);
  404. m_nextDecode = LITERAL;
  405. }
  406. catch (HuffmanDecoder::Err &)
  407. {
  408. throw BadBlockErr();
  409. }
  410. break;
  411. }
  412. default:
  413. throw BadBlockErr(); // reserved block type
  414. }
  415. m_state = DECODING_BODY;
  416. }
  417. bool Inflator::DecodeBody()
  418. {
  419. bool blockEnd = false;
  420. switch (m_blockType)
  421. {
  422. case 0: // stored
  423. assert(m_reader.BitsBuffered() == 0);
  424. while (!m_inQueue.IsEmpty() && !blockEnd)
  425. {
  426. size_t size;
  427. const byte *block = m_inQueue.Spy(size);
  428. size = UnsignedMin(m_storedLen, size);
  429. OutputString(block, size);
  430. m_inQueue.Skip(size);
  431. m_storedLen -= (word16)size;
  432. if (m_storedLen == 0)
  433. blockEnd = true;
  434. }
  435. break;
  436. case 1: // fixed codes
  437. case 2: // dynamic codes
  438. static const unsigned int lengthStarts[] = {
  439. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  440. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
  441. static const unsigned int lengthExtraBits[] = {
  442. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  443. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
  444. static const unsigned int distanceStarts[] = {
  445. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  446. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  447. 8193, 12289, 16385, 24577};
  448. static const unsigned int distanceExtraBits[] = {
  449. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  450. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  451. 12, 12, 13, 13};
  452. const HuffmanDecoder& literalDecoder = GetLiteralDecoder();
  453. const HuffmanDecoder& distanceDecoder = GetDistanceDecoder();
  454. switch (m_nextDecode)
  455. {
  456. case LITERAL:
  457. while (true)
  458. {
  459. if (!literalDecoder.Decode(m_reader, m_literal))
  460. {
  461. m_nextDecode = LITERAL;
  462. break;
  463. }
  464. if (m_literal < 256)
  465. OutputByte((byte)m_literal);
  466. else if (m_literal == 256) // end of block
  467. {
  468. blockEnd = true;
  469. break;
  470. }
  471. else
  472. {
  473. if (m_literal > 285)
  474. throw BadBlockErr();
  475. unsigned int bits;
  476. case LENGTH_BITS:
  477. bits = lengthExtraBits[m_literal-257];
  478. if (!m_reader.FillBuffer(bits))
  479. {
  480. m_nextDecode = LENGTH_BITS;
  481. break;
  482. }
  483. m_literal = m_reader.GetBits(bits) + lengthStarts[m_literal-257];
  484. case DISTANCE:
  485. if (!distanceDecoder.Decode(m_reader, m_distance))
  486. {
  487. m_nextDecode = DISTANCE;
  488. break;
  489. }
  490. case DISTANCE_BITS:
  491. bits = distanceExtraBits[m_distance];
  492. if (!m_reader.FillBuffer(bits))
  493. {
  494. m_nextDecode = DISTANCE_BITS;
  495. break;
  496. }
  497. m_distance = m_reader.GetBits(bits) + distanceStarts[m_distance];
  498. OutputPast(m_literal, m_distance);
  499. }
  500. }
  501. }
  502. }
  503. if (blockEnd)
  504. {
  505. if (m_eof)
  506. {
  507. FlushOutput();
  508. m_reader.SkipBits(m_reader.BitsBuffered()%8);
  509. if (m_reader.BitsBuffered())
  510. {
  511. // undo too much lookahead
  512. SecBlockWithHint<byte, 4> buffer(m_reader.BitsBuffered() / 8);
  513. for (unsigned int i=0; i<buffer.size(); i++)
  514. buffer[i] = (byte)m_reader.GetBits(8);
  515. m_inQueue.Unget(buffer, buffer.size());
  516. }
  517. m_state = POST_STREAM;
  518. }
  519. else
  520. m_state = WAIT_HEADER;
  521. }
  522. return blockEnd;
  523. }
  524. void Inflator::FlushOutput()
  525. {
  526. if (m_state != PRE_STREAM)
  527. {
  528. assert(m_current >= m_lastFlush);
  529. ProcessDecompressedData(m_window + m_lastFlush, m_current - m_lastFlush);
  530. m_lastFlush = m_current;
  531. }
  532. }
  533. struct NewFixedLiteralDecoder
  534. {
  535. HuffmanDecoder * operator()() const
  536. {
  537. unsigned int codeLengths[288];
  538. std::fill(codeLengths + 0, codeLengths + 144, 8);
  539. std::fill(codeLengths + 144, codeLengths + 256, 9);
  540. std::fill(codeLengths + 256, codeLengths + 280, 7);
  541. std::fill(codeLengths + 280, codeLengths + 288, 8);
  542. std::auto_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder);
  543. pDecoder->Initialize(codeLengths, 288);
  544. return pDecoder.release();
  545. }
  546. };
  547. struct NewFixedDistanceDecoder
  548. {
  549. HuffmanDecoder * operator()() const
  550. {
  551. unsigned int codeLengths[32];
  552. std::fill(codeLengths + 0, codeLengths + 32, 5);
  553. std::auto_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder);
  554. pDecoder->Initialize(codeLengths, 32);
  555. return pDecoder.release();
  556. }
  557. };
  558. const HuffmanDecoder& Inflator::GetLiteralDecoder() const
  559. {
  560. return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedLiteralDecoder>().Ref() : m_dynamicLiteralDecoder;
  561. }
  562. const HuffmanDecoder& Inflator::GetDistanceDecoder() const
  563. {
  564. return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedDistanceDecoder>().Ref() : m_dynamicDistanceDecoder;
  565. }
  566. NAMESPACE_END