SSHZLIB.C 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. /*
  2. * Zlib (RFC1950 / RFC1951) compression for PuTTY.
  3. *
  4. * There will no doubt be criticism of my decision to reimplement
  5. * Zlib compression from scratch instead of using the existing zlib
  6. * code. People will cry `reinventing the wheel'; they'll claim
  7. * that the `fundamental basis of OSS' is code reuse; they'll want
  8. * to see a really good reason for me having chosen not to use the
  9. * existing code.
  10. *
  11. * Well, here are my reasons. Firstly, I don't want to link the
  12. * whole of zlib into the PuTTY binary; PuTTY is justifiably proud
  13. * of its small size and I think zlib contains a lot of unnecessary
  14. * baggage for the kind of compression that SSH requires.
  15. *
  16. * Secondly, I also don't like the alternative of using zlib.dll.
  17. * Another thing PuTTY is justifiably proud of is its ease of
  18. * installation, and the last thing I want to do is to start
  19. * mandating DLLs. Not only that, but there are two _kinds_ of
  20. * zlib.dll kicking around, one with C calling conventions on the
  21. * exported functions and another with WINAPI conventions, and
  22. * there would be a significant danger of getting the wrong one.
  23. *
  24. * Thirdly, there seems to be a difference of opinion on the IETF
  25. * secsh mailing list about the correct way to round off a
  26. * compressed packet and start the next. In particular, there's
  27. * some talk of switching to a mechanism zlib isn't currently
  28. * capable of supporting (see below for an explanation). Given that
  29. * sort of uncertainty, I thought it might be better to have code
  30. * that will support even the zlib-incompatible worst case.
  31. *
  32. * Fourthly, it's a _second implementation_. Second implementations
  33. * are fundamentally a Good Thing in standardisation efforts. The
  34. * difference of opinion mentioned above has arisen _precisely_
  35. * because there has been only one zlib implementation and
  36. * everybody has used it. I don't intend that this should happen
  37. * again.
  38. */
  39. #include <stdlib.h>
  40. #include <assert.h>
  41. #ifdef ZLIB_STANDALONE
  42. /*
  43. * This module also makes a handy zlib decoding tool for when
  44. * you're picking apart Zip files or PDFs or PNGs. If you compile
  45. * it with ZLIB_STANDALONE defined, it builds on its own and
  46. * becomes a command-line utility.
  47. *
  48. * Therefore, here I provide a self-contained implementation of the
  49. * macros required from the rest of the PuTTY sources.
  50. */
  51. #define snew(type) ( (type *) malloc(sizeof(type)) )
  52. #define snewn(n, type) ( (type *) malloc((n) * sizeof(type)) )
  53. #define sresize(x, n, type) ( (type *) realloc((x), (n) * sizeof(type)) )
  54. #define sfree(x) ( free((x)) )
  55. #else
  56. #include "ssh.h"
  57. #endif
  58. #ifndef FALSE
  59. #define FALSE 0
  60. #define TRUE (!FALSE)
  61. #endif
  62. /* ----------------------------------------------------------------------
  63. * Basic LZ77 code. This bit is designed modularly, so it could be
  64. * ripped out and used in a different LZ77 compressor. Go to it,
  65. * and good luck :-)
  66. */
  67. struct LZ77InternalContext;
  68. struct LZ77Context {
  69. struct LZ77InternalContext *ictx;
  70. void *userdata;
  71. void (*literal) (struct LZ77Context * ctx, unsigned char c);
  72. void (*match) (struct LZ77Context * ctx, int distance, int len);
  73. };
  74. /*
  75. * Initialise the private fields of an LZ77Context. It's up to the
  76. * user to initialise the public fields.
  77. */
  78. static int lz77_init(struct LZ77Context *ctx);
  79. /*
  80. * Supply data to be compressed. Will update the private fields of
  81. * the LZ77Context, and will call literal() and match() to output.
  82. * If `compress' is FALSE, it will never emit a match, but will
  83. * instead call literal() for everything.
  84. */
  85. static void lz77_compress(struct LZ77Context *ctx,
  86. unsigned char *data, int len, int compress);
  87. /*
  88. * Modifiable parameters.
  89. */
  90. #define WINSIZE 32768 /* window size. Must be power of 2! */
  91. #define HASHMAX 2039 /* one more than max hash value */
  92. #define MAXMATCH 32 /* how many matches we track */
  93. #define HASHCHARS 3 /* how many chars make a hash */
  94. /*
  95. * This compressor takes a less slapdash approach than the
  96. * gzip/zlib one. Rather than allowing our hash chains to fall into
  97. * disuse near the far end, we keep them doubly linked so we can
  98. * _find_ the far end, and then every time we add a new byte to the
  99. * window (thus rolling round by one and removing the previous
  100. * byte), we can carefully remove the hash chain entry.
  101. */
  102. #define INVALID -1 /* invalid hash _and_ invalid offset */
  103. struct WindowEntry {
  104. short next, prev; /* array indices within the window */
  105. short hashval;
  106. };
  107. struct HashEntry {
  108. short first; /* window index of first in chain */
  109. };
  110. struct Match {
  111. int distance, len;
  112. };
  113. struct LZ77InternalContext {
  114. struct WindowEntry win[WINSIZE];
  115. unsigned char data[WINSIZE];
  116. int winpos;
  117. struct HashEntry hashtab[HASHMAX];
  118. unsigned char pending[HASHCHARS];
  119. int npending;
  120. };
  121. static int lz77_hash(unsigned char *data)
  122. {
  123. return (257 * data[0] + 263 * data[1] + 269 * data[2]) % HASHMAX;
  124. }
  125. static int lz77_init(struct LZ77Context *ctx)
  126. {
  127. struct LZ77InternalContext *st;
  128. int i;
  129. st = snew(struct LZ77InternalContext);
  130. if (!st)
  131. return 0;
  132. ctx->ictx = st;
  133. for (i = 0; i < WINSIZE; i++)
  134. st->win[i].next = st->win[i].prev = st->win[i].hashval = INVALID;
  135. for (i = 0; i < HASHMAX; i++)
  136. st->hashtab[i].first = INVALID;
  137. st->winpos = 0;
  138. st->npending = 0;
  139. return 1;
  140. }
  141. static void lz77_advance(struct LZ77InternalContext *st,
  142. unsigned char c, int hash)
  143. {
  144. int off;
  145. /*
  146. * Remove the hash entry at winpos from the tail of its chain,
  147. * or empty the chain if it's the only thing on the chain.
  148. */
  149. if (st->win[st->winpos].prev != INVALID) {
  150. st->win[st->win[st->winpos].prev].next = INVALID;
  151. } else if (st->win[st->winpos].hashval != INVALID) {
  152. st->hashtab[st->win[st->winpos].hashval].first = INVALID;
  153. }
  154. /*
  155. * Create a new entry at winpos and add it to the head of its
  156. * hash chain.
  157. */
  158. st->win[st->winpos].hashval = hash;
  159. st->win[st->winpos].prev = INVALID;
  160. off = st->win[st->winpos].next = st->hashtab[hash].first;
  161. st->hashtab[hash].first = st->winpos;
  162. if (off != INVALID)
  163. st->win[off].prev = st->winpos;
  164. st->data[st->winpos] = c;
  165. /*
  166. * Advance the window pointer.
  167. */
  168. st->winpos = (st->winpos + 1) & (WINSIZE - 1);
  169. }
  170. #define CHARAT(k) ( (k)<0 ? st->data[(st->winpos+k)&(WINSIZE-1)] : data[k] )
  171. static void lz77_compress(struct LZ77Context *ctx,
  172. unsigned char *data, int len, int compress)
  173. {
  174. struct LZ77InternalContext *st = ctx->ictx;
  175. int i, hash, distance, off, nmatch, matchlen, advance;
  176. struct Match defermatch, matches[MAXMATCH];
  177. int deferchr;
  178. /*
  179. * Add any pending characters from last time to the window. (We
  180. * might not be able to.)
  181. */
  182. for (i = 0; i < st->npending; i++) {
  183. unsigned char foo[HASHCHARS];
  184. int j;
  185. if (len + st->npending - i < HASHCHARS) {
  186. /* Update the pending array. */
  187. for (j = i; j < st->npending; j++)
  188. st->pending[j - i] = st->pending[j];
  189. break;
  190. }
  191. for (j = 0; j < HASHCHARS; j++)
  192. foo[j] = (i + j < st->npending ? st->pending[i + j] :
  193. data[i + j - st->npending]);
  194. lz77_advance(st, foo[0], lz77_hash(foo));
  195. }
  196. st->npending -= i;
  197. defermatch.distance = 0; /* appease compiler */
  198. defermatch.len = 0;
  199. deferchr = '\0';
  200. while (len > 0) {
  201. /* Don't even look for a match, if we're not compressing. */
  202. if (compress && len >= HASHCHARS) {
  203. /*
  204. * Hash the next few characters.
  205. */
  206. hash = lz77_hash(data);
  207. /*
  208. * Look the hash up in the corresponding hash chain and see
  209. * what we can find.
  210. */
  211. nmatch = 0;
  212. for (off = st->hashtab[hash].first;
  213. off != INVALID; off = st->win[off].next) {
  214. /* distance = 1 if off == st->winpos-1 */
  215. /* distance = WINSIZE if off == st->winpos */
  216. distance =
  217. WINSIZE - (off + WINSIZE - st->winpos) % WINSIZE;
  218. for (i = 0; i < HASHCHARS; i++)
  219. if (CHARAT(i) != CHARAT(i - distance))
  220. break;
  221. if (i == HASHCHARS) {
  222. matches[nmatch].distance = distance;
  223. matches[nmatch].len = 3;
  224. if (++nmatch >= MAXMATCH)
  225. break;
  226. }
  227. }
  228. } else {
  229. nmatch = 0;
  230. hash = INVALID;
  231. }
  232. if (nmatch > 0) {
  233. /*
  234. * We've now filled up matches[] with nmatch potential
  235. * matches. Follow them down to find the longest. (We
  236. * assume here that it's always worth favouring a
  237. * longer match over a shorter one.)
  238. */
  239. matchlen = HASHCHARS;
  240. while (matchlen < len) {
  241. int j;
  242. for (i = j = 0; i < nmatch; i++) {
  243. if (CHARAT(matchlen) ==
  244. CHARAT(matchlen - matches[i].distance)) {
  245. matches[j++] = matches[i];
  246. }
  247. }
  248. if (j == 0)
  249. break;
  250. matchlen++;
  251. nmatch = j;
  252. }
  253. /*
  254. * We've now got all the longest matches. We favour the
  255. * shorter distances, which means we go with matches[0].
  256. * So see if we want to defer it or throw it away.
  257. */
  258. matches[0].len = matchlen;
  259. if (defermatch.len > 0) {
  260. if (matches[0].len > defermatch.len + 1) {
  261. /* We have a better match. Emit the deferred char,
  262. * and defer this match. */
  263. ctx->literal(ctx, (unsigned char) deferchr);
  264. defermatch = matches[0];
  265. deferchr = data[0];
  266. advance = 1;
  267. } else {
  268. /* We don't have a better match. Do the deferred one. */
  269. ctx->match(ctx, defermatch.distance, defermatch.len);
  270. advance = defermatch.len - 1;
  271. defermatch.len = 0;
  272. }
  273. } else {
  274. /* There was no deferred match. Defer this one. */
  275. defermatch = matches[0];
  276. deferchr = data[0];
  277. advance = 1;
  278. }
  279. } else {
  280. /*
  281. * We found no matches. Emit the deferred match, if
  282. * any; otherwise emit a literal.
  283. */
  284. if (defermatch.len > 0) {
  285. ctx->match(ctx, defermatch.distance, defermatch.len);
  286. advance = defermatch.len - 1;
  287. defermatch.len = 0;
  288. } else {
  289. ctx->literal(ctx, data[0]);
  290. advance = 1;
  291. }
  292. }
  293. /*
  294. * Now advance the position by `advance' characters,
  295. * keeping the window and hash chains consistent.
  296. */
  297. while (advance > 0) {
  298. if (len >= HASHCHARS) {
  299. lz77_advance(st, *data, lz77_hash(data));
  300. } else {
  301. st->pending[st->npending++] = *data;
  302. }
  303. data++;
  304. len--;
  305. advance--;
  306. }
  307. }
  308. }
  309. /* ----------------------------------------------------------------------
  310. * Zlib compression. We always use the static Huffman tree option.
  311. * Mostly this is because it's hard to scan a block in advance to
  312. * work out better trees; dynamic trees are great when you're
  313. * compressing a large file under no significant time constraint,
  314. * but when you're compressing little bits in real time, things get
  315. * hairier.
  316. *
  317. * I suppose it's possible that I could compute Huffman trees based
  318. * on the frequencies in the _previous_ block, as a sort of
  319. * heuristic, but I'm not confident that the gain would balance out
  320. * having to transmit the trees.
  321. */
  322. struct Outbuf {
  323. unsigned char *outbuf;
  324. int outlen, outsize;
  325. unsigned long outbits;
  326. int noutbits;
  327. int firstblock;
  328. int comp_disabled;
  329. };
  330. static void outbits(struct Outbuf *out, unsigned long bits, int nbits)
  331. {
  332. assert(out->noutbits + nbits <= 32);
  333. out->outbits |= bits << out->noutbits;
  334. out->noutbits += nbits;
  335. while (out->noutbits >= 8) {
  336. if (out->outlen >= out->outsize) {
  337. out->outsize = out->outlen + 64;
  338. out->outbuf = sresize(out->outbuf, out->outsize, unsigned char);
  339. }
  340. out->outbuf[out->outlen++] = (unsigned char) (out->outbits & 0xFF);
  341. out->outbits >>= 8;
  342. out->noutbits -= 8;
  343. }
  344. }
  345. static const unsigned char mirrorbytes[256] = {
  346. 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
  347. 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
  348. 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
  349. 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
  350. 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
  351. 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
  352. 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
  353. 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
  354. 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
  355. 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
  356. 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
  357. 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
  358. 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
  359. 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
  360. 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
  361. 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
  362. 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
  363. 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
  364. 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
  365. 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
  366. 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
  367. 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
  368. 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
  369. 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
  370. 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
  371. 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
  372. 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
  373. 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
  374. 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
  375. 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
  376. 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
  377. 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
  378. };
  379. typedef struct {
  380. short code, extrabits;
  381. int min, max;
  382. } coderecord;
  383. static const coderecord lencodes[] = {
  384. {257, 0, 3, 3},
  385. {258, 0, 4, 4},
  386. {259, 0, 5, 5},
  387. {260, 0, 6, 6},
  388. {261, 0, 7, 7},
  389. {262, 0, 8, 8},
  390. {263, 0, 9, 9},
  391. {264, 0, 10, 10},
  392. {265, 1, 11, 12},
  393. {266, 1, 13, 14},
  394. {267, 1, 15, 16},
  395. {268, 1, 17, 18},
  396. {269, 2, 19, 22},
  397. {270, 2, 23, 26},
  398. {271, 2, 27, 30},
  399. {272, 2, 31, 34},
  400. {273, 3, 35, 42},
  401. {274, 3, 43, 50},
  402. {275, 3, 51, 58},
  403. {276, 3, 59, 66},
  404. {277, 4, 67, 82},
  405. {278, 4, 83, 98},
  406. {279, 4, 99, 114},
  407. {280, 4, 115, 130},
  408. {281, 5, 131, 162},
  409. {282, 5, 163, 194},
  410. {283, 5, 195, 226},
  411. {284, 5, 227, 257},
  412. {285, 0, 258, 258},
  413. };
  414. static const coderecord distcodes[] = {
  415. {0, 0, 1, 1},
  416. {1, 0, 2, 2},
  417. {2, 0, 3, 3},
  418. {3, 0, 4, 4},
  419. {4, 1, 5, 6},
  420. {5, 1, 7, 8},
  421. {6, 2, 9, 12},
  422. {7, 2, 13, 16},
  423. {8, 3, 17, 24},
  424. {9, 3, 25, 32},
  425. {10, 4, 33, 48},
  426. {11, 4, 49, 64},
  427. {12, 5, 65, 96},
  428. {13, 5, 97, 128},
  429. {14, 6, 129, 192},
  430. {15, 6, 193, 256},
  431. {16, 7, 257, 384},
  432. {17, 7, 385, 512},
  433. {18, 8, 513, 768},
  434. {19, 8, 769, 1024},
  435. {20, 9, 1025, 1536},
  436. {21, 9, 1537, 2048},
  437. {22, 10, 2049, 3072},
  438. {23, 10, 3073, 4096},
  439. {24, 11, 4097, 6144},
  440. {25, 11, 6145, 8192},
  441. {26, 12, 8193, 12288},
  442. {27, 12, 12289, 16384},
  443. {28, 13, 16385, 24576},
  444. {29, 13, 24577, 32768},
  445. };
  446. static void zlib_literal(struct LZ77Context *ectx, unsigned char c)
  447. {
  448. struct Outbuf *out = (struct Outbuf *) ectx->userdata;
  449. if (out->comp_disabled) {
  450. /*
  451. * We're in an uncompressed block, so just output the byte.
  452. */
  453. outbits(out, c, 8);
  454. return;
  455. }
  456. if (c <= 143) {
  457. /* 0 through 143 are 8 bits long starting at 00110000. */
  458. outbits(out, mirrorbytes[0x30 + c], 8);
  459. } else {
  460. /* 144 through 255 are 9 bits long starting at 110010000. */
  461. outbits(out, 1 + 2 * mirrorbytes[0x90 - 144 + c], 9);
  462. }
  463. }
  464. static void zlib_match(struct LZ77Context *ectx, int distance, int len)
  465. {
  466. const coderecord *d, *l;
  467. int i, j, k;
  468. struct Outbuf *out = (struct Outbuf *) ectx->userdata;
  469. assert(!out->comp_disabled);
  470. while (len > 0) {
  471. int thislen;
  472. /*
  473. * We can transmit matches of lengths 3 through 258
  474. * inclusive. So if len exceeds 258, we must transmit in
  475. * several steps, with 258 or less in each step.
  476. *
  477. * Specifically: if len >= 261, we can transmit 258 and be
  478. * sure of having at least 3 left for the next step. And if
  479. * len <= 258, we can just transmit len. But if len == 259
  480. * or 260, we must transmit len-3.
  481. */
  482. thislen = (len > 260 ? 258 : len <= 258 ? len : len - 3);
  483. len -= thislen;
  484. /*
  485. * Binary-search to find which length code we're
  486. * transmitting.
  487. */
  488. i = -1;
  489. j = sizeof(lencodes) / sizeof(*lencodes);
  490. while (1) {
  491. assert(j - i >= 2);
  492. k = (j + i) / 2;
  493. if (thislen < lencodes[k].min)
  494. j = k;
  495. else if (thislen > lencodes[k].max)
  496. i = k;
  497. else {
  498. l = &lencodes[k];
  499. break; /* found it! */
  500. }
  501. }
  502. /*
  503. * Transmit the length code. 256-279 are seven bits
  504. * starting at 0000000; 280-287 are eight bits starting at
  505. * 11000000.
  506. */
  507. if (l->code <= 279) {
  508. outbits(out, mirrorbytes[(l->code - 256) * 2], 7);
  509. } else {
  510. outbits(out, mirrorbytes[0xc0 - 280 + l->code], 8);
  511. }
  512. /*
  513. * Transmit the extra bits.
  514. */
  515. if (l->extrabits)
  516. outbits(out, thislen - l->min, l->extrabits);
  517. /*
  518. * Binary-search to find which distance code we're
  519. * transmitting.
  520. */
  521. i = -1;
  522. j = sizeof(distcodes) / sizeof(*distcodes);
  523. while (1) {
  524. assert(j - i >= 2);
  525. k = (j + i) / 2;
  526. if (distance < distcodes[k].min)
  527. j = k;
  528. else if (distance > distcodes[k].max)
  529. i = k;
  530. else {
  531. d = &distcodes[k];
  532. break; /* found it! */
  533. }
  534. }
  535. /*
  536. * Transmit the distance code. Five bits starting at 00000.
  537. */
  538. outbits(out, mirrorbytes[d->code * 8], 5);
  539. /*
  540. * Transmit the extra bits.
  541. */
  542. if (d->extrabits)
  543. outbits(out, distance - d->min, d->extrabits);
  544. }
  545. }
  546. void *zlib_compress_init(void)
  547. {
  548. struct Outbuf *out;
  549. struct LZ77Context *ectx = snew(struct LZ77Context);
  550. lz77_init(ectx);
  551. ectx->literal = zlib_literal;
  552. ectx->match = zlib_match;
  553. out = snew(struct Outbuf);
  554. out->outbits = out->noutbits = 0;
  555. out->firstblock = 1;
  556. out->comp_disabled = FALSE;
  557. ectx->userdata = out;
  558. return ectx;
  559. }
  560. void zlib_compress_cleanup(void *handle)
  561. {
  562. struct LZ77Context *ectx = (struct LZ77Context *)handle;
  563. sfree(ectx->userdata);
  564. sfree(ectx->ictx);
  565. sfree(ectx);
  566. }
  567. /*
  568. * Turn off actual LZ77 analysis for one block, to facilitate
  569. * construction of a precise-length IGNORE packet. Returns the
  570. * length adjustment (which is only valid for packets < 65536
  571. * bytes, but that seems reasonable enough).
  572. */
  573. static int zlib_disable_compression(void *handle)
  574. {
  575. struct LZ77Context *ectx = (struct LZ77Context *)handle;
  576. struct Outbuf *out = (struct Outbuf *) ectx->userdata;
  577. int n;
  578. out->comp_disabled = TRUE;
  579. n = 0;
  580. /*
  581. * If this is the first block, we will start by outputting two
  582. * header bytes, and then three bits to begin an uncompressed
  583. * block. This will cost three bytes (because we will start on
  584. * a byte boundary, this is certain).
  585. */
  586. if (out->firstblock) {
  587. n = 3;
  588. } else {
  589. /*
  590. * Otherwise, we will output seven bits to close the
  591. * previous static block, and _then_ three bits to begin an
  592. * uncompressed block, and then flush the current byte.
  593. * This may cost two bytes or three, depending on noutbits.
  594. */
  595. n += (out->noutbits + 10) / 8;
  596. }
  597. /*
  598. * Now we output four bytes for the length / ~length pair in
  599. * the uncompressed block.
  600. */
  601. n += 4;
  602. return n;
  603. }
  604. int zlib_compress_block(void *handle, unsigned char *block, int len,
  605. unsigned char **outblock, int *outlen)
  606. {
  607. struct LZ77Context *ectx = (struct LZ77Context *)handle;
  608. struct Outbuf *out = (struct Outbuf *) ectx->userdata;
  609. int in_block;
  610. out->outbuf = NULL;
  611. out->outlen = out->outsize = 0;
  612. /*
  613. * If this is the first block, output the Zlib (RFC1950) header
  614. * bytes 78 9C. (Deflate compression, 32K window size, default
  615. * algorithm.)
  616. */
  617. if (out->firstblock) {
  618. outbits(out, 0x9C78, 16);
  619. out->firstblock = 0;
  620. in_block = FALSE;
  621. } else
  622. in_block = TRUE;
  623. if (out->comp_disabled) {
  624. if (in_block)
  625. outbits(out, 0, 7); /* close static block */
  626. while (len > 0) {
  627. int blen = (len < 65535 ? len : 65535);
  628. /*
  629. * Start a Deflate (RFC1951) uncompressed block. We
  630. * transmit a zero bit (BFINAL=0), followed by two more
  631. * zero bits (BTYPE=00). Of course these are in the
  632. * wrong order (00 0), not that it matters.
  633. */
  634. outbits(out, 0, 3);
  635. /*
  636. * Output zero bits to align to a byte boundary.
  637. */
  638. if (out->noutbits)
  639. outbits(out, 0, 8 - out->noutbits);
  640. /*
  641. * Output the block length, and then its one's
  642. * complement. They're little-endian, so all we need to
  643. * do is pass them straight to outbits() with bit count
  644. * 16.
  645. */
  646. outbits(out, blen, 16);
  647. outbits(out, blen ^ 0xFFFF, 16);
  648. /*
  649. * Do the `compression': we need to pass the data to
  650. * lz77_compress so that it will be taken into account
  651. * for subsequent (distance,length) pairs. But
  652. * lz77_compress is passed FALSE, which means it won't
  653. * actually find (or even look for) any matches; so
  654. * every character will be passed straight to
  655. * zlib_literal which will spot out->comp_disabled and
  656. * emit in the uncompressed format.
  657. */
  658. lz77_compress(ectx, block, blen, FALSE);
  659. len -= blen;
  660. block += blen;
  661. }
  662. outbits(out, 2, 3); /* open new block */
  663. } else {
  664. if (!in_block) {
  665. /*
  666. * Start a Deflate (RFC1951) fixed-trees block. We
  667. * transmit a zero bit (BFINAL=0), followed by a zero
  668. * bit and a one bit (BTYPE=01). Of course these are in
  669. * the wrong order (01 0).
  670. */
  671. outbits(out, 2, 3);
  672. }
  673. /*
  674. * Do the compression.
  675. */
  676. lz77_compress(ectx, block, len, TRUE);
  677. /*
  678. * End the block (by transmitting code 256, which is
  679. * 0000000 in fixed-tree mode), and transmit some empty
  680. * blocks to ensure we have emitted the byte containing the
  681. * last piece of genuine data. There are three ways we can
  682. * do this:
  683. *
  684. * - Minimal flush. Output end-of-block and then open a
  685. * new static block. This takes 9 bits, which is
  686. * guaranteed to flush out the last genuine code in the
  687. * closed block; but allegedly zlib can't handle it.
  688. *
  689. * - Zlib partial flush. Output EOB, open and close an
  690. * empty static block, and _then_ open the new block.
  691. * This is the best zlib can handle.
  692. *
  693. * - Zlib sync flush. Output EOB, then an empty
  694. * _uncompressed_ block (000, then sync to byte
  695. * boundary, then send bytes 00 00 FF FF). Then open the
  696. * new block.
  697. *
  698. * For the moment, we will use Zlib partial flush.
  699. */
  700. outbits(out, 0, 7); /* close block */
  701. outbits(out, 2, 3 + 7); /* empty static block */
  702. outbits(out, 2, 3); /* open new block */
  703. }
  704. out->comp_disabled = FALSE;
  705. *outblock = out->outbuf;
  706. *outlen = out->outlen;
  707. return 1;
  708. }
  709. /* ----------------------------------------------------------------------
  710. * Zlib decompression. Of course, even though our compressor always
  711. * uses static trees, our _decompressor_ has to be capable of
  712. * handling dynamic trees if it sees them.
  713. */
  714. /*
  715. * The way we work the Huffman decode is to have a table lookup on
  716. * the first N bits of the input stream (in the order they arrive,
  717. * of course, i.e. the first bit of the Huffman code is in bit 0).
  718. * Each table entry lists the number of bits to consume, plus
  719. * either an output code or a pointer to a secondary table.
  720. */
  721. struct zlib_table;
  722. struct zlib_tableentry;
  723. struct zlib_tableentry {
  724. unsigned char nbits;
  725. short code;
  726. struct zlib_table *nexttable;
  727. };
  728. struct zlib_table {
  729. int mask; /* mask applied to input bit stream */
  730. struct zlib_tableentry *table;
  731. };
  732. #define MAXCODELEN 16
  733. #define MAXSYMS 288
  734. /*
  735. * Build a single-level decode table for elements
  736. * [minlength,maxlength) of the provided code/length tables, and
  737. * recurse to build subtables.
  738. */
  739. static struct zlib_table *zlib_mkonetab(int *codes, unsigned char *lengths,
  740. int nsyms,
  741. int pfx, int pfxbits, int bits)
  742. {
  743. struct zlib_table *tab = snew(struct zlib_table);
  744. int pfxmask = (1 << pfxbits) - 1;
  745. int nbits, i, j, code;
  746. tab->table = snewn(1 << bits, struct zlib_tableentry);
  747. tab->mask = (1 << bits) - 1;
  748. for (code = 0; code <= tab->mask; code++) {
  749. tab->table[code].code = -1;
  750. tab->table[code].nbits = 0;
  751. tab->table[code].nexttable = NULL;
  752. }
  753. for (i = 0; i < nsyms; i++) {
  754. if (lengths[i] <= pfxbits || (codes[i] & pfxmask) != pfx)
  755. continue;
  756. code = (codes[i] >> pfxbits) & tab->mask;
  757. for (j = code; j <= tab->mask; j += 1 << (lengths[i] - pfxbits)) {
  758. tab->table[j].code = i;
  759. nbits = lengths[i] - pfxbits;
  760. if (tab->table[j].nbits < nbits)
  761. tab->table[j].nbits = nbits;
  762. }
  763. }
  764. for (code = 0; code <= tab->mask; code++) {
  765. if (tab->table[code].nbits <= bits)
  766. continue;
  767. /* Generate a subtable. */
  768. tab->table[code].code = -1;
  769. nbits = tab->table[code].nbits - bits;
  770. if (nbits > 7)
  771. nbits = 7;
  772. tab->table[code].nbits = bits;
  773. tab->table[code].nexttable = zlib_mkonetab(codes, lengths, nsyms,
  774. pfx | (code << pfxbits),
  775. pfxbits + bits, nbits);
  776. }
  777. return tab;
  778. }
  779. /*
  780. * Build a decode table, given a set of Huffman tree lengths.
  781. */
  782. static struct zlib_table *zlib_mktable(unsigned char *lengths,
  783. int nlengths)
  784. {
  785. int count[MAXCODELEN], startcode[MAXCODELEN], codes[MAXSYMS];
  786. int code, maxlen;
  787. int i, j;
  788. /* Count the codes of each length. */
  789. maxlen = 0;
  790. for (i = 1; i < MAXCODELEN; i++)
  791. count[i] = 0;
  792. for (i = 0; i < nlengths; i++) {
  793. count[lengths[i]]++;
  794. if (maxlen < lengths[i])
  795. maxlen = lengths[i];
  796. }
  797. /* Determine the starting code for each length block. */
  798. code = 0;
  799. for (i = 1; i < MAXCODELEN; i++) {
  800. startcode[i] = code;
  801. code += count[i];
  802. code <<= 1;
  803. }
  804. /* Determine the code for each symbol. Mirrored, of course. */
  805. for (i = 0; i < nlengths; i++) {
  806. code = startcode[lengths[i]]++;
  807. codes[i] = 0;
  808. for (j = 0; j < lengths[i]; j++) {
  809. codes[i] = (codes[i] << 1) | (code & 1);
  810. code >>= 1;
  811. }
  812. }
  813. /*
  814. * Now we have the complete list of Huffman codes. Build a
  815. * table.
  816. */
  817. return zlib_mkonetab(codes, lengths, nlengths, 0, 0,
  818. maxlen < 9 ? maxlen : 9);
  819. }
  820. static int zlib_freetable(struct zlib_table **ztab)
  821. {
  822. struct zlib_table *tab;
  823. int code;
  824. if (ztab == NULL)
  825. return -1;
  826. if (*ztab == NULL)
  827. return 0;
  828. tab = *ztab;
  829. for (code = 0; code <= tab->mask; code++)
  830. if (tab->table[code].nexttable != NULL)
  831. zlib_freetable(&tab->table[code].nexttable);
  832. sfree(tab->table);
  833. tab->table = NULL;
  834. sfree(tab);
  835. *ztab = NULL;
  836. return (0);
  837. }
  838. struct zlib_decompress_ctx {
  839. struct zlib_table *staticlentable, *staticdisttable;
  840. struct zlib_table *currlentable, *currdisttable, *lenlentable;
  841. enum {
  842. START, OUTSIDEBLK,
  843. TREES_HDR, TREES_LENLEN, TREES_LEN, TREES_LENREP,
  844. INBLK, GOTLENSYM, GOTLEN, GOTDISTSYM,
  845. UNCOMP_LEN, UNCOMP_NLEN, UNCOMP_DATA
  846. } state;
  847. int sym, hlit, hdist, hclen, lenptr, lenextrabits, lenaddon, len,
  848. lenrep;
  849. int uncomplen;
  850. unsigned char lenlen[19];
  851. unsigned char lengths[286 + 32];
  852. unsigned long bits;
  853. int nbits;
  854. unsigned char window[WINSIZE];
  855. int winpos;
  856. unsigned char *outblk;
  857. int outlen, outsize;
  858. };
  859. void *zlib_decompress_init(void)
  860. {
  861. struct zlib_decompress_ctx *dctx = snew(struct zlib_decompress_ctx);
  862. unsigned char lengths[288];
  863. memset(lengths, 8, 144);
  864. memset(lengths + 144, 9, 256 - 144);
  865. memset(lengths + 256, 7, 280 - 256);
  866. memset(lengths + 280, 8, 288 - 280);
  867. dctx->staticlentable = zlib_mktable(lengths, 288);
  868. memset(lengths, 5, 32);
  869. dctx->staticdisttable = zlib_mktable(lengths, 32);
  870. dctx->state = START; /* even before header */
  871. dctx->currlentable = dctx->currdisttable = dctx->lenlentable = NULL;
  872. dctx->bits = 0;
  873. dctx->nbits = 0;
  874. dctx->winpos = 0;
  875. return dctx;
  876. }
  877. void zlib_decompress_cleanup(void *handle)
  878. {
  879. struct zlib_decompress_ctx *dctx = (struct zlib_decompress_ctx *)handle;
  880. if (dctx->currlentable && dctx->currlentable != dctx->staticlentable)
  881. zlib_freetable(&dctx->currlentable);
  882. if (dctx->currdisttable && dctx->currdisttable != dctx->staticdisttable)
  883. zlib_freetable(&dctx->currdisttable);
  884. if (dctx->lenlentable)
  885. zlib_freetable(&dctx->lenlentable);
  886. zlib_freetable(&dctx->staticlentable);
  887. zlib_freetable(&dctx->staticdisttable);
  888. sfree(dctx);
  889. }
  890. static int zlib_huflookup(unsigned long *bitsp, int *nbitsp,
  891. struct zlib_table *tab)
  892. {
  893. unsigned long bits = *bitsp;
  894. int nbits = *nbitsp;
  895. while (1) {
  896. struct zlib_tableentry *ent;
  897. ent = &tab->table[bits & tab->mask];
  898. if (ent->nbits > nbits)
  899. return -1; /* not enough data */
  900. bits >>= ent->nbits;
  901. nbits -= ent->nbits;
  902. if (ent->code == -1)
  903. tab = ent->nexttable;
  904. else {
  905. *bitsp = bits;
  906. *nbitsp = nbits;
  907. return ent->code;
  908. }
  909. if (!tab) {
  910. /*
  911. * There was a missing entry in the table, presumably
  912. * due to an invalid Huffman table description, and the
  913. * subsequent data has attempted to use the missing
  914. * entry. Return a decoding failure.
  915. */
  916. return -2;
  917. }
  918. }
  919. }
  920. static void zlib_emit_char(struct zlib_decompress_ctx *dctx, int c)
  921. {
  922. dctx->window[dctx->winpos] = c;
  923. dctx->winpos = (dctx->winpos + 1) & (WINSIZE - 1);
  924. if (dctx->outlen >= dctx->outsize) {
  925. dctx->outsize = dctx->outlen + 512;
  926. dctx->outblk = sresize(dctx->outblk, dctx->outsize, unsigned char);
  927. }
  928. dctx->outblk[dctx->outlen++] = c;
  929. }
  930. #define EATBITS(n) ( dctx->nbits -= (n), dctx->bits >>= (n) )
  931. int zlib_decompress_block(void *handle, unsigned char *block, int len,
  932. unsigned char **outblock, int *outlen)
  933. {
  934. struct zlib_decompress_ctx *dctx = (struct zlib_decompress_ctx *)handle;
  935. const coderecord *rec;
  936. int code, blktype, rep, dist, nlen, header;
  937. static const unsigned char lenlenmap[] = {
  938. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  939. };
  940. dctx->outblk = snewn(256, unsigned char);
  941. dctx->outsize = 256;
  942. dctx->outlen = 0;
  943. while (len > 0 || dctx->nbits > 0) {
  944. while (dctx->nbits < 24 && len > 0) {
  945. dctx->bits |= (*block++) << dctx->nbits;
  946. dctx->nbits += 8;
  947. len--;
  948. }
  949. switch (dctx->state) {
  950. case START:
  951. /* Expect 16-bit zlib header. */
  952. if (dctx->nbits < 16)
  953. goto finished; /* done all we can */
  954. /*
  955. * The header is stored as a big-endian 16-bit integer,
  956. * in contrast to the general little-endian policy in
  957. * the rest of the format :-(
  958. */
  959. header = (((dctx->bits & 0xFF00) >> 8) |
  960. ((dctx->bits & 0x00FF) << 8));
  961. EATBITS(16);
  962. /*
  963. * Check the header:
  964. *
  965. * - bits 8-11 should be 1000 (Deflate/RFC1951)
  966. * - bits 12-15 should be at most 0111 (window size)
  967. * - bit 5 should be zero (no dictionary present)
  968. * - we don't care about bits 6-7 (compression rate)
  969. * - bits 0-4 should be set up to make the whole thing
  970. * a multiple of 31 (checksum).
  971. */
  972. if ((header & 0x0F00) != 0x0800 ||
  973. (header & 0xF000) > 0x7000 ||
  974. (header & 0x0020) != 0x0000 ||
  975. (header % 31) != 0)
  976. goto decode_error;
  977. dctx->state = OUTSIDEBLK;
  978. break;
  979. case OUTSIDEBLK:
  980. /* Expect 3-bit block header. */
  981. if (dctx->nbits < 3)
  982. goto finished; /* done all we can */
  983. EATBITS(1);
  984. blktype = dctx->bits & 3;
  985. EATBITS(2);
  986. if (blktype == 0) {
  987. int to_eat = dctx->nbits & 7;
  988. dctx->state = UNCOMP_LEN;
  989. EATBITS(to_eat); /* align to byte boundary */
  990. } else if (blktype == 1) {
  991. dctx->currlentable = dctx->staticlentable;
  992. dctx->currdisttable = dctx->staticdisttable;
  993. dctx->state = INBLK;
  994. } else if (blktype == 2) {
  995. dctx->state = TREES_HDR;
  996. }
  997. break;
  998. case TREES_HDR:
  999. /*
  1000. * Dynamic block header. Five bits of HLIT, five of
  1001. * HDIST, four of HCLEN.
  1002. */
  1003. if (dctx->nbits < 5 + 5 + 4)
  1004. goto finished; /* done all we can */
  1005. dctx->hlit = 257 + (dctx->bits & 31);
  1006. EATBITS(5);
  1007. dctx->hdist = 1 + (dctx->bits & 31);
  1008. EATBITS(5);
  1009. dctx->hclen = 4 + (dctx->bits & 15);
  1010. EATBITS(4);
  1011. dctx->lenptr = 0;
  1012. dctx->state = TREES_LENLEN;
  1013. memset(dctx->lenlen, 0, sizeof(dctx->lenlen));
  1014. break;
  1015. case TREES_LENLEN:
  1016. if (dctx->nbits < 3)
  1017. goto finished;
  1018. while (dctx->lenptr < dctx->hclen && dctx->nbits >= 3) {
  1019. dctx->lenlen[lenlenmap[dctx->lenptr++]] =
  1020. (unsigned char) (dctx->bits & 7);
  1021. EATBITS(3);
  1022. }
  1023. if (dctx->lenptr == dctx->hclen) {
  1024. dctx->lenlentable = zlib_mktable(dctx->lenlen, 19);
  1025. dctx->state = TREES_LEN;
  1026. dctx->lenptr = 0;
  1027. }
  1028. break;
  1029. case TREES_LEN:
  1030. if (dctx->lenptr >= dctx->hlit + dctx->hdist) {
  1031. dctx->currlentable = zlib_mktable(dctx->lengths, dctx->hlit);
  1032. dctx->currdisttable = zlib_mktable(dctx->lengths + dctx->hlit,
  1033. dctx->hdist);
  1034. zlib_freetable(&dctx->lenlentable);
  1035. dctx->lenlentable = NULL;
  1036. dctx->state = INBLK;
  1037. break;
  1038. }
  1039. code =
  1040. zlib_huflookup(&dctx->bits, &dctx->nbits, dctx->lenlentable);
  1041. if (code == -1)
  1042. goto finished;
  1043. if (code == -2)
  1044. goto decode_error;
  1045. if (code < 16)
  1046. dctx->lengths[dctx->lenptr++] = code;
  1047. else {
  1048. dctx->lenextrabits = (code == 16 ? 2 : code == 17 ? 3 : 7);
  1049. dctx->lenaddon = (code == 18 ? 11 : 3);
  1050. dctx->lenrep = (code == 16 && dctx->lenptr > 0 ?
  1051. dctx->lengths[dctx->lenptr - 1] : 0);
  1052. dctx->state = TREES_LENREP;
  1053. }
  1054. break;
  1055. case TREES_LENREP:
  1056. if (dctx->nbits < dctx->lenextrabits)
  1057. goto finished;
  1058. rep =
  1059. dctx->lenaddon +
  1060. (dctx->bits & ((1 << dctx->lenextrabits) - 1));
  1061. EATBITS(dctx->lenextrabits);
  1062. while (rep > 0 && dctx->lenptr < dctx->hlit + dctx->hdist) {
  1063. dctx->lengths[dctx->lenptr] = dctx->lenrep;
  1064. dctx->lenptr++;
  1065. rep--;
  1066. }
  1067. dctx->state = TREES_LEN;
  1068. break;
  1069. case INBLK:
  1070. code =
  1071. zlib_huflookup(&dctx->bits, &dctx->nbits, dctx->currlentable);
  1072. if (code == -1)
  1073. goto finished;
  1074. if (code == -2)
  1075. goto decode_error;
  1076. if (code < 256)
  1077. zlib_emit_char(dctx, code);
  1078. else if (code == 256) {
  1079. dctx->state = OUTSIDEBLK;
  1080. if (dctx->currlentable != dctx->staticlentable) {
  1081. zlib_freetable(&dctx->currlentable);
  1082. dctx->currlentable = NULL;
  1083. }
  1084. if (dctx->currdisttable != dctx->staticdisttable) {
  1085. zlib_freetable(&dctx->currdisttable);
  1086. dctx->currdisttable = NULL;
  1087. }
  1088. } else if (code < 286) { /* static tree can give >285; ignore */
  1089. dctx->state = GOTLENSYM;
  1090. dctx->sym = code;
  1091. }
  1092. break;
  1093. case GOTLENSYM:
  1094. rec = &lencodes[dctx->sym - 257];
  1095. if (dctx->nbits < rec->extrabits)
  1096. goto finished;
  1097. dctx->len =
  1098. rec->min + (dctx->bits & ((1 << rec->extrabits) - 1));
  1099. EATBITS(rec->extrabits);
  1100. dctx->state = GOTLEN;
  1101. break;
  1102. case GOTLEN:
  1103. code =
  1104. zlib_huflookup(&dctx->bits, &dctx->nbits,
  1105. dctx->currdisttable);
  1106. if (code == -1)
  1107. goto finished;
  1108. if (code == -2)
  1109. goto decode_error;
  1110. dctx->state = GOTDISTSYM;
  1111. dctx->sym = code;
  1112. break;
  1113. case GOTDISTSYM:
  1114. rec = &distcodes[dctx->sym];
  1115. if (dctx->nbits < rec->extrabits)
  1116. goto finished;
  1117. dist = rec->min + (dctx->bits & ((1 << rec->extrabits) - 1));
  1118. EATBITS(rec->extrabits);
  1119. dctx->state = INBLK;
  1120. while (dctx->len--)
  1121. zlib_emit_char(dctx, dctx->window[(dctx->winpos - dist) &
  1122. (WINSIZE - 1)]);
  1123. break;
  1124. case UNCOMP_LEN:
  1125. /*
  1126. * Uncompressed block. We expect to see a 16-bit LEN.
  1127. */
  1128. if (dctx->nbits < 16)
  1129. goto finished;
  1130. dctx->uncomplen = dctx->bits & 0xFFFF;
  1131. EATBITS(16);
  1132. dctx->state = UNCOMP_NLEN;
  1133. break;
  1134. case UNCOMP_NLEN:
  1135. /*
  1136. * Uncompressed block. We expect to see a 16-bit NLEN,
  1137. * which should be the one's complement of the previous
  1138. * LEN.
  1139. */
  1140. if (dctx->nbits < 16)
  1141. goto finished;
  1142. nlen = dctx->bits & 0xFFFF;
  1143. EATBITS(16);
  1144. if (dctx->uncomplen == 0)
  1145. dctx->state = OUTSIDEBLK; /* block is empty */
  1146. else
  1147. dctx->state = UNCOMP_DATA;
  1148. break;
  1149. case UNCOMP_DATA:
  1150. if (dctx->nbits < 8)
  1151. goto finished;
  1152. zlib_emit_char(dctx, dctx->bits & 0xFF);
  1153. EATBITS(8);
  1154. if (--dctx->uncomplen == 0)
  1155. dctx->state = OUTSIDEBLK; /* end of uncompressed block */
  1156. break;
  1157. }
  1158. }
  1159. finished:
  1160. *outblock = dctx->outblk;
  1161. *outlen = dctx->outlen;
  1162. return 1;
  1163. decode_error:
  1164. sfree(dctx->outblk);
  1165. *outblock = dctx->outblk = NULL;
  1166. *outlen = 0;
  1167. return 0;
  1168. }
  1169. #ifdef ZLIB_STANDALONE
  1170. #include <stdio.h>
  1171. #include <string.h>
  1172. int main(int argc, char **argv)
  1173. {
  1174. unsigned char buf[16], *outbuf;
  1175. int ret, outlen;
  1176. void *handle;
  1177. int noheader = FALSE, opts = TRUE;
  1178. char *filename = NULL;
  1179. FILE *fp;
  1180. while (--argc) {
  1181. char *p = *++argv;
  1182. if (p[0] == '-' && opts) {
  1183. if (!strcmp(p, "-d"))
  1184. noheader = TRUE;
  1185. else if (!strcmp(p, "--"))
  1186. opts = FALSE; /* next thing is filename */
  1187. else {
  1188. fprintf(stderr, "unknown command line option '%s'\n", p);
  1189. return 1;
  1190. }
  1191. } else if (!filename) {
  1192. filename = p;
  1193. } else {
  1194. fprintf(stderr, "can only handle one filename\n");
  1195. return 1;
  1196. }
  1197. }
  1198. handle = zlib_decompress_init();
  1199. if (noheader) {
  1200. /*
  1201. * Provide missing zlib header if -d was specified.
  1202. */
  1203. zlib_decompress_block(handle, "\x78\x9C", 2, &outbuf, &outlen);
  1204. assert(outlen == 0);
  1205. }
  1206. if (filename)
  1207. fp = fopen(filename, "rb");
  1208. else
  1209. fp = stdin;
  1210. if (!fp) {
  1211. assert(filename);
  1212. fprintf(stderr, "unable to open '%s'\n", filename);
  1213. return 1;
  1214. }
  1215. while (1) {
  1216. ret = fread(buf, 1, sizeof(buf), fp);
  1217. if (ret <= 0)
  1218. break;
  1219. zlib_decompress_block(handle, buf, ret, &outbuf, &outlen);
  1220. if (outbuf) {
  1221. if (outlen)
  1222. fwrite(outbuf, 1, outlen, stdout);
  1223. sfree(outbuf);
  1224. } else {
  1225. fprintf(stderr, "decoding error\n");
  1226. return 1;
  1227. }
  1228. }
  1229. zlib_decompress_cleanup(handle);
  1230. if (filename)
  1231. fclose(fp);
  1232. return 0;
  1233. }
  1234. #else
  1235. const struct ssh_compress ssh_zlib = {
  1236. "zlib",
  1237. zlib_compress_init,
  1238. zlib_compress_cleanup,
  1239. zlib_compress_block,
  1240. zlib_decompress_init,
  1241. zlib_decompress_cleanup,
  1242. zlib_decompress_block,
  1243. zlib_disable_compression,
  1244. "zlib (RFC1950)"
  1245. };
  1246. #endif