sshzlib.c 38 KB

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