DEFLATEDecompressor.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /* Copyright (C) Teemu Suutari */
  2. #include <cstdint>
  3. #include <cstring>
  4. #include "DEFLATEDecompressor.hpp"
  5. #include "HuffmanDecoder.hpp"
  6. #include "InputStream.hpp"
  7. #include "OutputStream.hpp"
  8. #include "common/CRC32.hpp"
  9. #include "common/OverflowCheck.hpp"
  10. #include "common/Common.hpp"
  11. namespace ancient::internal
  12. {
  13. static uint32_t Adler32(const Buffer &buffer,size_t offset,size_t len)
  14. {
  15. if (!len || OverflowCheck::sum(offset,len)>buffer.size()) throw Buffer::OutOfBoundsError();
  16. const uint8_t *ptr=buffer.data()+offset;
  17. uint32_t s1=1,s2=0;
  18. for (size_t i=0;i<len;i++)
  19. {
  20. s1+=ptr[i];
  21. if (s1>=65521) s1-=65521;
  22. s2+=s1;
  23. if (s2>=65521) s2-=65521;
  24. }
  25. return (s2<<16)|s1;
  26. }
  27. bool DEFLATEDecompressor::detectHeader(uint32_t hdr) noexcept
  28. {
  29. return ((hdr>>16)==0x1f8b);
  30. }
  31. bool DEFLATEDecompressor::detectHeaderXPK(uint32_t hdr) noexcept
  32. {
  33. return (hdr==FourCC("GZIP"));
  34. }
  35. std::shared_ptr<Decompressor> DEFLATEDecompressor::create(const Buffer &packedData,bool exactSizeKnown,bool verify)
  36. {
  37. return std::make_shared<DEFLATEDecompressor>(packedData,exactSizeKnown,verify);
  38. }
  39. std::shared_ptr<XPKDecompressor> DEFLATEDecompressor::create(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::shared_ptr<XPKDecompressor::State> &state,bool verify)
  40. {
  41. return std::make_shared<DEFLATEDecompressor>(hdr,recursionLevel,packedData,state,verify);
  42. }
  43. bool DEFLATEDecompressor::detectZLib()
  44. {
  45. if (_packedData.size()<6) return false;
  46. // no knowledge about rawSize, before decompression
  47. // packedSize told by decompressor
  48. _packedSize=uint32_t(_packedData.size());
  49. _packedOffset=2;
  50. uint8_t cm=_packedData.read8(0);
  51. if ((cm&0xf)!=8) return false;
  52. if ((cm&0xf0)>0x70) return false;
  53. uint8_t flags=_packedData.read8(1);
  54. if (flags&0x20)
  55. {
  56. if (_packedSize<8) return false;
  57. _packedOffset+=4;
  58. }
  59. if (((uint16_t(cm)<<8)|uint16_t(flags))%31) return false;
  60. _type=Type::ZLib;
  61. return true;
  62. }
  63. DEFLATEDecompressor::DEFLATEDecompressor(const Buffer &packedData,bool exactSizeKnown,bool verify) :
  64. _packedData(packedData),
  65. _exactSizeKnown(exactSizeKnown)
  66. {
  67. if (_packedData.size()<18) throw InvalidFormatError();
  68. uint32_t hdr=_packedData.readBE32(0);
  69. if (!detectHeader(hdr)) throw InvalidFormatError();
  70. uint8_t cm=_packedData.read8(2);
  71. if (cm!=8) throw InvalidFormatError();;
  72. uint8_t flags=_packedData.read8(3);
  73. if (flags&0xe0) throw InvalidFormatError();;
  74. uint32_t currentOffset=10;
  75. if (flags&4)
  76. {
  77. uint16_t xlen=_packedData.readLE16(currentOffset);
  78. currentOffset+=uint32_t(xlen)+2;
  79. }
  80. auto skipString=[&]()
  81. {
  82. uint8_t ch;
  83. do {
  84. ch=_packedData.read8(currentOffset);
  85. currentOffset++;
  86. } while (ch);
  87. };
  88. if (flags&8) skipString(); // FNAME
  89. if (flags&16) skipString(); // FCOMMENT
  90. if (flags&2) currentOffset+=2; // FHCRC, not using that since it is only for header
  91. _packedOffset=currentOffset;
  92. if (OverflowCheck::sum(currentOffset,8U)>_packedData.size()) throw InvalidFormatError();
  93. if (_exactSizeKnown)
  94. {
  95. _packedSize=_packedData.size();
  96. _rawSize=_packedData.readLE32(_packedData.size()-4);
  97. if (!_rawSize) throw InvalidFormatError();
  98. }
  99. _type=Type::GZIP;
  100. }
  101. DEFLATEDecompressor::DEFLATEDecompressor(uint32_t hdr,uint32_t recursionLevel,const Buffer &packedData,std::shared_ptr<XPKDecompressor::State> &state,bool verify) :
  102. XPKDecompressor(recursionLevel),
  103. _packedData(packedData)
  104. {
  105. if (!detectZLib())
  106. {
  107. _packedSize=packedData.size();
  108. _packedOffset=0;
  109. _type=Type::Raw;
  110. }
  111. }
  112. DEFLATEDecompressor::DEFLATEDecompressor(const Buffer &packedData,size_t packedSize,size_t rawSize,bool isZlib,bool verify,bool deflate64) :
  113. _packedData(packedData),
  114. _deflate64(deflate64)
  115. {
  116. _packedSize=packedSize;
  117. if (_packedSize>_packedData.size()) throw InvalidFormatError();
  118. if (isZlib)
  119. {
  120. // if it is not real zlib-stream fail.
  121. if (!detectZLib()) throw InvalidFormatError();
  122. } else {
  123. // raw stream
  124. _packedOffset=0;
  125. _rawSize=rawSize;
  126. _type=Type::Raw;
  127. }
  128. }
  129. DEFLATEDecompressor::~DEFLATEDecompressor()
  130. {
  131. // nothing needed
  132. }
  133. const std::string &DEFLATEDecompressor::getName() const noexcept
  134. {
  135. static std::string names[3]={
  136. "gzip: Deflate",
  137. "zlib: Deflate",
  138. "raw: Deflate/Deflate64"};
  139. return names[static_cast<uint32_t>(_type)];
  140. }
  141. const std::string &DEFLATEDecompressor::getSubName() const noexcept
  142. {
  143. static std::string name="XPK-GZIP: Deflate";
  144. return name;
  145. }
  146. size_t DEFLATEDecompressor::getPackedSize() const noexcept
  147. {
  148. // no way to know before decompressing
  149. return _packedSize;
  150. }
  151. size_t DEFLATEDecompressor::getRawSize() const noexcept
  152. {
  153. // same thing, decompression needed first
  154. return _rawSize;
  155. }
  156. void DEFLATEDecompressor::decompressImpl(Buffer &rawData,bool verify)
  157. {
  158. size_t packedSize=_packedSize?_packedSize:_packedData.size();
  159. size_t rawSize=_rawSize?_rawSize:rawData.size();
  160. ForwardInputStream inputStream(_packedData,_packedOffset,packedSize);
  161. LSBBitReader<ForwardInputStream> bitReader(inputStream);
  162. auto readBits=[&](uint32_t count)->uint32_t
  163. {
  164. return bitReader.readBits8(count);
  165. };
  166. auto readBit=[&]()->uint32_t
  167. {
  168. return bitReader.readBits8(1);
  169. };
  170. ForwardOutputStream outputStream(rawData,0,rawSize);
  171. bool final;
  172. do {
  173. final=readBit();
  174. uint8_t blockType=readBits(2);
  175. if (!blockType)
  176. {
  177. bitReader.reset();
  178. uint16_t len=inputStream.readByte();
  179. len|=uint16_t(inputStream.readByte())<<8;
  180. uint16_t nlen=inputStream.readByte();
  181. nlen|=uint16_t(inputStream.readByte())<<8;
  182. if (len!=(nlen^0xffffU)) throw DecompressionError();
  183. outputStream.produce(inputStream.consume(len),len);
  184. } else if (blockType==1 || blockType==2) {
  185. typedef HuffmanDecoder<int32_t> DEFLATEDecoder;
  186. DEFLATEDecoder llDecoder;
  187. DEFLATEDecoder distanceDecoder;
  188. if (blockType==1)
  189. {
  190. for (uint32_t i=0;i<24;i++) llDecoder.insert(HuffmanCode<int32_t>{7,i,int32_t(i+256)});
  191. for (uint32_t i=0;i<144;i++) llDecoder.insert(HuffmanCode<int32_t>{8,i+0x30,int32_t(i)});
  192. for (uint32_t i=0;i<8;i++) llDecoder.insert(HuffmanCode<int32_t>{8,i+0xc0,int32_t(i+280)});
  193. for (uint32_t i=0;i<112;i++) llDecoder.insert(HuffmanCode<int32_t>{9,i+0x190,int32_t(i+144)});
  194. for (uint32_t i=0;i<32;i++) distanceDecoder.insert(HuffmanCode<int32_t>{5,i,int32_t(i)});
  195. } else {
  196. uint32_t hlit=readBits(5)+257;
  197. // lets just error here, it is simpler
  198. if (hlit>=287) throw DecompressionError();
  199. uint32_t hdist=readBits(5)+1;
  200. uint32_t hclen=readBits(4)+4;
  201. uint8_t lengthTable[19];
  202. for (uint32_t i=0;i<19;i++) lengthTable[i]=0;
  203. static const uint8_t lengthTableOrder[19]={
  204. 16,17,18, 0, 8, 7, 9, 6,
  205. 10, 5,11, 4,12, 3,13, 2,
  206. 14, 1,15};
  207. for (uint32_t i=0;i<hclen;i++) lengthTable[lengthTableOrder[i]]=readBits(3);
  208. DEFLATEDecoder bitLengthDecoder;
  209. bitLengthDecoder.createOrderlyHuffmanTable(lengthTable,19); // 19 and not hclen due to reordering
  210. // can the previous code flow from ll to distance table?
  211. // specification does not say and treats the two almost as combined.
  212. // So let previous code flow
  213. uint8_t llTableBits[286];
  214. uint8_t distanceTableBits[32];
  215. uint8_t prevValue=0;
  216. uint32_t i=0;
  217. while (i<hlit+hdist)
  218. {
  219. auto insert=[&](uint8_t value)
  220. {
  221. if (i>=hlit+hdist) throw DecompressionError();
  222. if (i>=hlit) distanceTableBits[i-hlit]=value;
  223. else llTableBits[i]=value;
  224. prevValue=value;
  225. i++;
  226. };
  227. int32_t code=bitLengthDecoder.decode(readBit);
  228. if (code<16) {
  229. insert(code);
  230. } else switch (code) {
  231. case 16:
  232. if (i)
  233. {
  234. uint32_t count=readBits(2)+3;
  235. for (uint32_t j=0;j<count;j++) insert(prevValue);
  236. } else throw DecompressionError();
  237. break;
  238. case 17:
  239. for (uint32_t count=readBits(3)+3;count;count--) insert(0);
  240. break;
  241. case 18:
  242. for (uint32_t count=readBits(7)+11;count;count--) insert(0);
  243. break;
  244. default:
  245. throw DecompressionError();
  246. }
  247. }
  248. llDecoder.createOrderlyHuffmanTable(llTableBits,hlit);
  249. distanceDecoder.createOrderlyHuffmanTable(distanceTableBits,hdist);
  250. }
  251. // and now decode
  252. for (;;)
  253. {
  254. int32_t code=llDecoder.decode(readBit);
  255. if (code<256) {
  256. outputStream.writeByte(code);
  257. } else if (code==256) {
  258. break;
  259. } else {
  260. static const uint32_t lengthAdditions[29]={
  261. 3,4,5,6,7,8,9,10,
  262. 11,13,15,17,
  263. 19,23,27,31,
  264. 35,43,51,59,
  265. 67,83,99,115,
  266. 131,163,195,227,
  267. 258};
  268. static const uint32_t lengthBits[29]={
  269. 0,0,0,0,0,0,0,0,
  270. 1,1,1,1,2,2,2,2,
  271. 3,3,3,3,4,4,4,4,
  272. 5,5,5,5,
  273. 0};
  274. uint32_t count=(_deflate64&&code==285)?readBits(16)+3:(readBits(lengthBits[code-257])+lengthAdditions[code-257]);
  275. int32_t distCode=distanceDecoder.decode(readBit);
  276. if (distCode<0 || distCode>(_deflate64?31:29)) throw DecompressionError();
  277. static const uint32_t distanceAdditions[32]={
  278. 1,2,3,4,5,7,9,13,
  279. 0x11,0x19,0x21,0x31,0x41,0x61,0x81,0xc1,
  280. 0x101,0x181,0x201,0x301,0x401,0x601,0x801,0xc01,
  281. 0x1001,0x1801,0x2001,0x3001,0x4001,0x6001,
  282. 0x8001,0xc001};
  283. static const uint32_t distanceBits[32]={
  284. 0,0,0,0,1,1,2,2,
  285. 3,3,4,4,5,5,6,6,
  286. 7,7,8,8,9,9,10,10,
  287. 11,11,12,12,13,13,
  288. 14,14};
  289. uint32_t distance=readBits(distanceBits[distCode])+distanceAdditions[distCode];
  290. outputStream.copy(distance,count);
  291. }
  292. }
  293. } else {
  294. throw DecompressionError();
  295. }
  296. } while (!final);
  297. if (!_rawSize) _rawSize=outputStream.getOffset();
  298. if (_type==Type::GZIP)
  299. {
  300. if (OverflowCheck::sum(inputStream.getOffset(),8U)>packedSize) throw DecompressionError();
  301. if (!_packedSize)
  302. _packedSize=inputStream.getOffset()+8;
  303. } else if (_type==Type::ZLib) {
  304. if (OverflowCheck::sum(inputStream.getOffset(),4U)>packedSize) throw DecompressionError();
  305. if (!_packedSize)
  306. _packedSize=inputStream.getOffset()+4;
  307. } else {
  308. if (!_packedSize)
  309. _packedSize=inputStream.getOffset();
  310. }
  311. if (_rawSize!=outputStream.getOffset()) throw DecompressionError();
  312. if (verify)
  313. {
  314. if (_type==Type::GZIP)
  315. {
  316. uint32_t crc=_packedData.readLE32(inputStream.getOffset());
  317. if (CRC32(rawData,0,_rawSize,0)!=crc) throw VerificationError();
  318. } else if (_type==Type::ZLib) {
  319. uint32_t adler=_packedData.readBE32(inputStream.getOffset());
  320. if (Adler32(rawData,0,_rawSize)!=adler) throw VerificationError();
  321. }
  322. }
  323. }
  324. void DEFLATEDecompressor::decompressImpl(Buffer &rawData,const Buffer &previousData,bool verify)
  325. {
  326. decompressImpl(rawData,verify);
  327. }
  328. }