sshzlib.c 40 KB

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