sshzlib.c 37 KB

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