sshzlib.c 39 KB

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