sshzlib.c 38 KB

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