gzio.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /* gzio.c -- IO on .gz files
  2. * Copyright (C) 1995-1996 Jean-loup Gailly.
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. */
  5. /* $Id: gzio.c,v 1.14 1996/07/24 13:41:01 me Exp $ */
  6. #include <stdio.h>
  7. #include "zutil.h"
  8. struct internal_state {int dummy;}; /* for buggy compilers */
  9. #define Z_BUFSIZE 4096
  10. #define ALLOC(size) malloc(size)
  11. #define TRYFREE(p) {if (p) free(p);}
  12. static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
  13. /* gzip flag byte */
  14. #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
  15. #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
  16. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  17. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  18. #define COMMENT 0x10 /* bit 4 set: file comment present */
  19. #define RESERVED 0xE0 /* bits 5..7: reserved */
  20. typedef struct gz_stream {
  21. z_stream stream;
  22. int z_err; /* error code for last stream operation */
  23. int z_eof; /* set if end of input file */
  24. FILE *file; /* .gz file */
  25. Byte *inbuf; /* input buffer */
  26. Byte *outbuf; /* output buffer */
  27. uLong crc; /* crc32 of uncompressed data */
  28. char *msg; /* error message */
  29. char *path; /* path name for debugging only */
  30. int transparent; /* 1 if input file is not a .gz file */
  31. char mode; /* 'w' or 'r' */
  32. } gz_stream;
  33. local gzFile gz_open OF((const char *path, const char *mode, int fd));
  34. local int get_byte OF((gz_stream *s));
  35. local void check_header OF((gz_stream *s));
  36. local int destroy OF((gz_stream *s));
  37. local void putLong OF((FILE *file, uLong x));
  38. local uLong getLong OF((gz_stream *s));
  39. /* ===========================================================================
  40. Opens a gzip (.gz) file for reading or writing. The mode parameter
  41. is as in fopen ("rb" or "wb"). The file is given either by file descriptor
  42. or path name (if fd == -1).
  43. gz_open return NULL if the file could not be opened or if there was
  44. insufficient memory to allocate the (de)compression state; errno
  45. can be checked to distinguish the two cases (if errno is zero, the
  46. zlib error is Z_MEM_ERROR).
  47. */
  48. local gzFile gz_open (path, mode, fd)
  49. const char *path;
  50. const char *mode;
  51. int fd;
  52. {
  53. int err;
  54. int level = Z_DEFAULT_COMPRESSION; /* compression level */
  55. char *p = (char*)mode;
  56. gz_stream *s;
  57. char fmode[80]; /* copy of mode, without the compression level */
  58. char *m = fmode;
  59. if (!path || !mode) return Z_NULL;
  60. s = (gz_stream *)ALLOC(sizeof(gz_stream));
  61. if (!s) return Z_NULL;
  62. s->stream.zalloc = (alloc_func)0;
  63. s->stream.zfree = (free_func)0;
  64. s->stream.opaque = (voidpf)0;
  65. s->stream.next_in = s->inbuf = Z_NULL;
  66. s->stream.next_out = s->outbuf = Z_NULL;
  67. s->stream.avail_in = s->stream.avail_out = 0;
  68. s->file = NULL;
  69. s->z_err = Z_OK;
  70. s->z_eof = 0;
  71. s->crc = crc32(0L, Z_NULL, 0);
  72. s->msg = NULL;
  73. s->transparent = 0;
  74. s->path = (char*)ALLOC(strlen(path)+1);
  75. if (s->path == NULL) {
  76. return destroy(s), (gzFile)Z_NULL;
  77. }
  78. strcpy(s->path, path); /* do this early for debugging */
  79. s->mode = '\0';
  80. do {
  81. if (*p == 'r') s->mode = 'r';
  82. if (*p == 'w' || *p == 'a') s->mode = 'w';
  83. if (*p >= '0' && *p <= '9') {
  84. level = *p - '0';
  85. } else {
  86. *m++ = *p; /* copy the mode */
  87. }
  88. } while (*p++ && m != fmode + sizeof(fmode));
  89. if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
  90. if (s->mode == 'w') {
  91. err = deflateInit2(&(s->stream), level,
  92. Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, 0);
  93. /* windowBits is passed < 0 to suppress zlib header */
  94. s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
  95. if (err != Z_OK || s->outbuf == Z_NULL) {
  96. return destroy(s), (gzFile)Z_NULL;
  97. }
  98. } else {
  99. err = inflateInit2(&(s->stream), -MAX_WBITS);
  100. s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
  101. if (err != Z_OK || s->inbuf == Z_NULL) {
  102. return destroy(s), (gzFile)Z_NULL;
  103. }
  104. }
  105. s->stream.avail_out = Z_BUFSIZE;
  106. errno = 0;
  107. s->file = fd < 0 ? FOPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
  108. if (s->file == NULL) {
  109. return destroy(s), (gzFile)Z_NULL;
  110. }
  111. if (s->mode == 'w') {
  112. /* Write a very simple .gz header:
  113. */
  114. fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
  115. Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
  116. } else {
  117. check_header(s); /* skip the .gz header */
  118. }
  119. return (gzFile)s;
  120. }
  121. /* ===========================================================================
  122. Opens a gzip (.gz) file for reading or writing.
  123. */
  124. gzFile gzopen (path, mode)
  125. const char *path;
  126. const char *mode;
  127. {
  128. return gz_open (path, mode, -1);
  129. }
  130. /* ===========================================================================
  131. Associate a gzFile with the file descriptor fd. fd is not dup'ed here
  132. to mimic the behavio(u)r of fdopen.
  133. */
  134. gzFile gzdopen (fd, mode)
  135. int fd;
  136. const char *mode;
  137. {
  138. char name[20];
  139. if (fd < 0) return (gzFile)Z_NULL;
  140. sprintf(name, "<fd:%d>", fd); /* for debugging */
  141. return gz_open (name, mode, fd);
  142. }
  143. /* ===========================================================================
  144. Read a byte from a gz_stream; update next_in and avail_in. Return EOF
  145. for end of file.
  146. IN assertion: the stream s has been sucessfully opened for reading.
  147. */
  148. local int get_byte(s)
  149. gz_stream *s;
  150. {
  151. if (s->z_eof) return EOF;
  152. if (s->stream.avail_in == 0) {
  153. errno = 0;
  154. s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  155. if (s->stream.avail_in == 0) {
  156. s->z_eof = 1;
  157. if (ferror(s->file)) s->z_err = Z_ERRNO;
  158. return EOF;
  159. }
  160. s->stream.next_in = s->inbuf;
  161. }
  162. s->stream.avail_in--;
  163. return *(s->stream.next_in)++;
  164. }
  165. /* ===========================================================================
  166. Check the gzip header of a gz_stream opened for reading. Set the stream
  167. mode to transparent if the gzip magic header is not present; set s->err
  168. to Z_DATA_ERROR if the magic header is present but the rest of the header
  169. is incorrect.
  170. IN assertion: the stream s has already been created sucessfully;
  171. s->stream.avail_in is zero for the first time, but may be non-zero
  172. for concatenated .gz files.
  173. */
  174. local void check_header(s)
  175. gz_stream *s;
  176. {
  177. int method; /* method byte */
  178. int flags; /* flags byte */
  179. uInt len;
  180. int c;
  181. /* Check the gzip magic header */
  182. for (len = 0; len < 2; len++) {
  183. c = get_byte(s);
  184. if (c != gz_magic[len]) {
  185. s->transparent = 1;
  186. if (c != EOF) s->stream.avail_in++, s->stream.next_in--;
  187. s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
  188. return;
  189. }
  190. }
  191. method = get_byte(s);
  192. flags = get_byte(s);
  193. if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
  194. s->z_err = Z_DATA_ERROR;
  195. return;
  196. }
  197. /* Discard time, xflags and OS code: */
  198. for (len = 0; len < 6; len++) (void)get_byte(s);
  199. if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
  200. len = (uInt)get_byte(s);
  201. len += ((uInt)get_byte(s))<<8;
  202. /* len is garbage if EOF but the loop below will quit anyway */
  203. while (len-- != 0 && get_byte(s) != EOF) ;
  204. }
  205. if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
  206. while ((c = get_byte(s)) != 0 && c != EOF) ;
  207. }
  208. if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
  209. while ((c = get_byte(s)) != 0 && c != EOF) ;
  210. }
  211. if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
  212. for (len = 0; len < 2; len++) (void)get_byte(s);
  213. }
  214. s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
  215. }
  216. /* ===========================================================================
  217. * Cleanup then free the given gz_stream. Return a zlib error code.
  218. Try freeing in the reverse order of allocations.
  219. */
  220. local int destroy (s)
  221. gz_stream *s;
  222. {
  223. int err = Z_OK;
  224. if (!s) return Z_STREAM_ERROR;
  225. TRYFREE(s->msg);
  226. if (s->stream.state != NULL) {
  227. if (s->mode == 'w') {
  228. err = deflateEnd(&(s->stream));
  229. } else if (s->mode == 'r') {
  230. err = inflateEnd(&(s->stream));
  231. }
  232. }
  233. if (s->file != NULL && fclose(s->file)) {
  234. err = Z_ERRNO;
  235. }
  236. if (s->z_err < 0) err = s->z_err;
  237. TRYFREE(s->inbuf);
  238. TRYFREE(s->outbuf);
  239. TRYFREE(s->path);
  240. TRYFREE(s);
  241. return err;
  242. }
  243. /* ===========================================================================
  244. Reads the given number of uncompressed bytes from the compressed file.
  245. gzread returns the number of bytes actually read (0 for end of file).
  246. */
  247. int gzread (file, buf, len)
  248. gzFile file;
  249. voidp buf;
  250. unsigned len;
  251. {
  252. gz_stream *s = (gz_stream*)file;
  253. Bytef *start = buf; /* starting point for crc computation */
  254. Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
  255. if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
  256. if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
  257. if (s->z_err == Z_STREAM_END) return 0; /* EOF */
  258. s->stream.next_out = next_out = buf;
  259. s->stream.avail_out = len;
  260. while (s->stream.avail_out != 0) {
  261. if (s->transparent) {
  262. /* Copy first the lookahead bytes: */
  263. uInt n = s->stream.avail_in;
  264. if (n > s->stream.avail_out) n = s->stream.avail_out;
  265. if (n > 0) {
  266. zmemcpy(s->stream.next_out, s->stream.next_in, n);
  267. next_out += n;
  268. s->stream.next_out = next_out;
  269. s->stream.next_in += n;
  270. s->stream.avail_out -= n;
  271. s->stream.avail_in -= n;
  272. }
  273. if (s->stream.avail_out > 0) {
  274. s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out,
  275. s->file);
  276. }
  277. return (int)(len - s->stream.avail_out);
  278. }
  279. if (s->stream.avail_in == 0 && !s->z_eof) {
  280. errno = 0;
  281. s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  282. if (s->stream.avail_in == 0) {
  283. s->z_eof = 1;
  284. if (ferror(s->file)) {
  285. s->z_err = Z_ERRNO;
  286. break;
  287. }
  288. }
  289. s->stream.next_in = s->inbuf;
  290. }
  291. s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
  292. if (s->z_err == Z_STREAM_END) {
  293. /* Check CRC and original size */
  294. s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  295. start = s->stream.next_out;
  296. if (getLong(s) != s->crc || getLong(s) != s->stream.total_out) {
  297. s->z_err = Z_DATA_ERROR;
  298. } else {
  299. /* Check for concatenated .gz files: */
  300. check_header(s);
  301. if (s->z_err == Z_OK) {
  302. inflateReset(&(s->stream));
  303. s->crc = crc32(0L, Z_NULL, 0);
  304. }
  305. }
  306. }
  307. if (s->z_err != Z_OK || s->z_eof) break;
  308. }
  309. s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  310. return (int)(len - s->stream.avail_out);
  311. }
  312. /* ===========================================================================
  313. Writes the given number of uncompressed bytes into the compressed file.
  314. gzwrite returns the number of bytes actually written (0 in case of error).
  315. */
  316. int gzwrite (file, buf, len)
  317. gzFile file;
  318. const voidp buf;
  319. unsigned len;
  320. {
  321. gz_stream *s = (gz_stream*)file;
  322. if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  323. s->stream.next_in = buf;
  324. s->stream.avail_in = len;
  325. while (s->stream.avail_in != 0) {
  326. if (s->stream.avail_out == 0) {
  327. s->stream.next_out = s->outbuf;
  328. if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
  329. s->z_err = Z_ERRNO;
  330. break;
  331. }
  332. s->stream.avail_out = Z_BUFSIZE;
  333. }
  334. s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
  335. if (s->z_err != Z_OK) break;
  336. }
  337. s->crc = crc32(s->crc, buf, len);
  338. return (int)(len - s->stream.avail_in);
  339. }
  340. /* ===========================================================================
  341. Flushes all pending output into the compressed file. The parameter
  342. flush is as in the deflate() function.
  343. gzflush should be called only when strictly necessary because it can
  344. degrade compression.
  345. */
  346. int gzflush (file, flush)
  347. gzFile file;
  348. int flush;
  349. {
  350. uInt len;
  351. int done = 0;
  352. gz_stream *s = (gz_stream*)file;
  353. if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  354. s->stream.avail_in = 0; /* should be zero already anyway */
  355. for (;;) {
  356. len = Z_BUFSIZE - s->stream.avail_out;
  357. if (len != 0) {
  358. if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
  359. s->z_err = Z_ERRNO;
  360. return Z_ERRNO;
  361. }
  362. s->stream.next_out = s->outbuf;
  363. s->stream.avail_out = Z_BUFSIZE;
  364. }
  365. if (done) break;
  366. s->z_err = deflate(&(s->stream), flush);
  367. /* deflate has finished flushing only when it hasn't used up
  368. * all the available space in the output buffer:
  369. */
  370. done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
  371. if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
  372. }
  373. fflush(s->file);
  374. return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
  375. }
  376. /* ===========================================================================
  377. Outputs a long in LSB order to the given file
  378. */
  379. local void putLong (file, x)
  380. FILE *file;
  381. uLong x;
  382. {
  383. int n;
  384. for (n = 0; n < 4; n++) {
  385. fputc((int)(x & 0xff), file);
  386. x >>= 8;
  387. }
  388. }
  389. /* ===========================================================================
  390. Reads a long in LSB order from the given gz_stream. Sets
  391. */
  392. local uLong getLong (s)
  393. gz_stream *s;
  394. {
  395. uLong x = (uLong)get_byte(s);
  396. int c;
  397. x += ((uLong)get_byte(s))<<8;
  398. x += ((uLong)get_byte(s))<<16;
  399. c = get_byte(s);
  400. if (c == EOF) s->z_err = Z_DATA_ERROR;
  401. x += ((uLong)c)<<24;
  402. return x;
  403. }
  404. /* ===========================================================================
  405. Flushes all pending output if necessary, closes the compressed file
  406. and deallocates all the (de)compression state.
  407. */
  408. int gzclose (file)
  409. gzFile file;
  410. {
  411. int err;
  412. gz_stream *s = (gz_stream*)file;
  413. if (s == NULL) return Z_STREAM_ERROR;
  414. if (s->mode == 'w') {
  415. err = gzflush (file, Z_FINISH);
  416. if (err != Z_OK) return destroy(file);
  417. putLong (s->file, s->crc);
  418. putLong (s->file, s->stream.total_in);
  419. }
  420. return destroy(file);
  421. }
  422. /* ===========================================================================
  423. Returns the error message for the last error which occured on the
  424. given compressed file. errnum is set to zlib error number. If an
  425. error occured in the file system and not in the compression library,
  426. errnum is set to Z_ERRNO and the application may consult errno
  427. to get the exact error code.
  428. */
  429. const char* gzerror (file, errnum)
  430. gzFile file;
  431. int *errnum;
  432. {
  433. char *m;
  434. gz_stream *s = (gz_stream*)file;
  435. if (s == NULL) {
  436. *errnum = Z_STREAM_ERROR;
  437. return (const char*)ERR_MSG(Z_STREAM_ERROR);
  438. }
  439. *errnum = s->z_err;
  440. if (*errnum == Z_OK) return (const char*)"";
  441. m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
  442. if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
  443. TRYFREE(s->msg);
  444. s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
  445. strcpy(s->msg, s->path);
  446. strcat(s->msg, ": ");
  447. strcat(s->msg, m);
  448. return (const char*)s->msg;
  449. }