home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip531.zip / funzip.c < prev    next >
C/C++ Source or Header  |  1997-05-22  |  16KB  |  464 lines

  1. /* funzip.c -- put in the public domain by Mark Adler */
  2.  
  3. #define VERSION "3.92 of 31 May 1997"
  4.  
  5.  
  6. /* You can do whatever you like with this source file, though I would
  7.    prefer that if you modify it and redistribute it that you include
  8.    comments to that effect with your name and the date.  Thank you.
  9.  
  10.    History:
  11.    vers     date          who           what
  12.    ----   ---------  --------------  ------------------------------------
  13.    1.0    13 Aug 92  M. Adler        really simple unzip filter.
  14.    1.1    13 Aug 92  M. Adler        cleaned up somewhat, give help if
  15.                                      stdin not redirected, warn if more
  16.                                      zip file entries after the first.
  17.    1.2    15 Aug 92  M. Adler        added check of lengths for stored
  18.                                      entries, added more help.
  19.    1.3    16 Aug 92  M. Adler        removed redundant #define's, added
  20.                                      decryption.
  21.    1.4    27 Aug 92  G. Roelofs      added exit(0).
  22.    1.5     1 Sep 92  K. U. Rommel    changed read/write modes for OS/2.
  23.    1.6     6 Sep 92  G. Roelofs      modified to use dummy crypt.c and
  24.                                      crypt.h instead of -DCRYPT.
  25.    1.7    23 Sep 92  G. Roelofs      changed to use DOS_OS2; included
  26.                                      crypt.c under MS-DOS.
  27.    1.8     9 Oct 92  M. Adler        improved inflation error msgs.
  28.    1.9    17 Oct 92  G. Roelofs      changed ULONG/UWORD/byte to ulg/ush/uch;
  29.                                      renamed inflate_entry() to inflate();
  30.                                      adapted to use new, in-place zdecode.
  31.    2.0    22 Oct 92  M. Adler        allow filename argument, prompt for
  32.                                      passwords and don't echo, still allow
  33.                                      command-line password entry, but as an
  34.                                      option.
  35.    2.1    23 Oct 92  J-l. Gailly     fixed crypt/store bug,
  36.                      G. Roelofs      removed crypt.c under MS-DOS, fixed
  37.                                      decryption check to compare single byte.
  38.    2.2    28 Oct 92  G. Roelofs      removed declaration of key.
  39.    2.3    14 Dec 92  M. Adler        replaced fseek (fails on stdin for SCO
  40.                                      Unix V.3.2.4).  added quietflg for
  41.                                      inflate.c.
  42.    3.0    11 May 93  M. Adler        added gzip support
  43.    3.1     9 Jul 93  K. U. Rommel    fixed OS/2 pipe bug (PIPE_ERROR)
  44.    3.2     4 Sep 93  G. Roelofs      moved crc_32_tab[] to tables.h; used FOPx
  45.                                      from unzip.h; nuked OUTB macro and outbuf;
  46.                                      replaced flush(); inlined FlushOutput();
  47.                                      renamed decrypt to encrypted
  48.    3.3    29 Sep 93  G. Roelofs      replaced ReadByte() with NEXTBYTE macro;
  49.                                      revised (restored?) flush(); added FUNZIP
  50.    3.4    21 Oct 93  G. Roelofs      renamed quietflg to qflag; changed outcnt,
  51.                      H. Gessau       second updcrc() arg and flush() arg to ulg;
  52.                                      added inflate_free(); added "g =" to null
  53.                                      getc(in) to avoid compiler warnings
  54.    3.5    31 Oct 93  H. Gessau       changed DOS_OS2 to DOS_NT_OS2
  55.    3.6     6 Dec 93  H. Gessau       added "near" to mask_bits[]
  56.    3.7     9 Dec 93  G. Roelofs      added extent typecasts to fwrite() checks
  57.    3.8    28 Jan 94  GRR/JlG         initialized g variable in main() for gcc
  58.    3.81   22 Feb 94  M. Hanning-Lee  corrected usage message
  59.    3.82   27 Feb 94  G. Roelofs      added some typecasts to avoid warnings
  60.    3.83   22 Jul 94  G. Roelofs      changed fprintf to macro for DLLs
  61.     -      2 Aug 94  -               public release with UnZip 5.11
  62.     -     28 Aug 94  -               public release with UnZip 5.12
  63.    3.84    1 Oct 94  K. U. Rommel    changes for Metaware High C
  64.    3.85   29 Oct 94  G. Roelofs      changed fprintf macro to Info
  65.    3.86    7 May 95  K. Davis        RISCOS patches;
  66.                      P. Kienitz      Amiga patches
  67.    3.87   12 Aug 95  G. Roelofs      inflate_free(), DESTROYGLOBALS fixes
  68.    3.88    4 Sep 95  C. Spieler      reordered macro to work around MSC 5.1 bug
  69.    3.89   22 Nov 95  PK/CS           ifdef'd out updcrc() for ASM_CRC
  70.    3.9    17 Dec 95  G. Roelofs      modified for USE_ZLIB (new fillinbuf())
  71.     -     30 Apr 96  -               public release with UnZip 5.2
  72.    3.91   17 Aug 96  G. Roelofs      main() -> return int (Peter Seebach)
  73.    3.92   13 Apr 97  G. Roelofs      minor cosmetic fixes to messages
  74.     -     22 Apr 97  -               public release with UnZip 5.3
  75.     -     31 May 97  -               public release with UnZip 5.31
  76.  */
  77.  
  78.  
  79. /*
  80.  
  81.    All funzip does is take a zipfile from stdin and decompress the
  82.    first entry to stdout.  The entry has to be either deflated or
  83.    stored.  If the entry is encrypted, then the decryption password
  84.    must be supplied on the command line as the first argument.
  85.  
  86.    funzip needs to be linked with inflate.o and crypt.o compiled from
  87.    the unzip source.  If decryption is desired, the full version of
  88.    crypt.c (and crypt.h) from zcrypt21.zip or later must be used.
  89.  
  90.  */
  91.  
  92. #define FUNZIP
  93. #define UNZIP_INTERNAL
  94. #include "unzip.h"
  95. #include "crypt.h"
  96. #include "ttyio.h"
  97.  
  98. #ifdef EBCDIC
  99. #  undef EBCDIC                 /* don't need ebcdic[] */
  100. #endif
  101. #include "tables.h"             /* crc_32_tab[] */
  102.  
  103. #ifndef USE_ZLIB  /* zlib's function is called inflate(), too */
  104. #  define UZinflate inflate
  105. #endif
  106.  
  107. /* PKZIP header definitions */
  108. #define ZIPMAG 0x4b50           /* two-byte zip lead-in */
  109. #define LOCREM 0x0403           /* remaining two bytes in zip signature */
  110. #define LOCSIG 0x04034b50L      /* full signature */
  111. #define LOCFLG 4                /* offset of bit flag */
  112. #define  CRPFLG 1               /*  bit for encrypted entry */
  113. #define  EXTFLG 8               /*  bit for extended local header */
  114. #define LOCHOW 6                /* offset of compression method */
  115. #define LOCTIM 8                /* file mod time (for decryption) */
  116. #define LOCCRC 12               /* offset of crc */
  117. #define LOCSIZ 16               /* offset of compressed size */
  118. #define LOCLEN 20               /* offset of uncompressed length */
  119. #define LOCFIL 24               /* offset of file name field length */
  120. #define LOCEXT 26               /* offset of extra field length */
  121. #define LOCHDR 28               /* size of local header, including LOCREM */
  122. #define EXTHDR 16               /* size of extended local header, inc sig */
  123.  
  124. /* GZIP header definitions */
  125. #define GZPMAG 0x8b1f           /* two-byte gzip lead-in */
  126. #define GZPHOW 0                /* offset of method number */
  127. #define GZPFLG 1                /* offset of gzip flags */
  128. #define  GZPMUL 2               /* bit for multiple-part gzip file */
  129. #define  GZPISX 4               /* bit for extra field present */
  130. #define  GZPISF 8               /* bit for filename present */
  131. #define  GZPISC 16              /* bit for comment present */
  132. #define  GZPISE 32              /* bit for encryption */
  133. #define GZPTIM 2                /* offset of Unix file modification time */
  134. #define GZPEXF 6                /* offset of extra flags */
  135. #define GZPCOS 7                /* offset of operating system compressed on */
  136. #define GZPHDR 8                /* length of minimal gzip header */
  137.  
  138. /* Macros for getting two-byte and four-byte header values */
  139. #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
  140. #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
  141.  
  142. /* Function prototypes */
  143. void err OF((int, char *));
  144. int main OF((int, char **));
  145.  
  146. /* Globals */
  147. FILE *out;                      /* output file (*in moved to G struct) */
  148. ulg outsiz;                     /* total bytes written to out */
  149. int encrypted;                  /* flag to turn on decryption */
  150.  
  151. /* Masks for inflate.c */
  152. ZCONST ush near mask_bits[] = {
  153.     0x0000,
  154.     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  155.     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  156. };
  157.  
  158.  
  159. #ifdef USE_ZLIB
  160.  
  161. int fillinbuf(__G)
  162. __GDEF
  163. /* Fill input buffer for pull-model inflate() in zlib.  Return the number of
  164.  * bytes in inbuf. */
  165. {
  166. /*   GRR: check return value from fread(): same as read()?  check errno? */
  167.   if ((G.incnt = fread((char *)G.inbuf, 1, INBUFSIZ, G.in)) <= 0)
  168.     return 0;
  169.   G.inptr = G.inbuf;
  170.  
  171. #if CRYPT
  172.   if (encrypted) {
  173.     uch *p;
  174.     int n;
  175.  
  176.     for (n = G.incnt, p = G.inptr;  n--;  p++)
  177.       zdecode(*p);
  178.   }
  179. #endif /* CRYPT */
  180.  
  181.   return G.incnt;
  182.  
  183. }
  184.  
  185. #endif /* USE_ZLIB */
  186.  
  187.  
  188. #if (!defined(USE_ZLIB) || defined(USE_OWN_CRCTAB))
  189. #ifdef USE_ZLIB
  190. uLongf *get_crc_table()
  191. {
  192.   return (uLongf *)crc_32_tab;
  193. }
  194. #else /* !USE_ZLIB */
  195. ulg near *get_crc_table()
  196. {
  197.   return crc_32_tab;
  198. }
  199. #endif /* ?USE_ZLIB */
  200. #endif /* !USE_ZLIB || USE_OWN_CRCTAB */
  201.  
  202.  
  203. void err(n, m)
  204. int n;
  205. char *m;
  206. /* Exit on error with a message and a code */
  207. {
  208.   Info(slide, 1, ((char *)slide, "funzip error: %s\n", m));
  209.   DESTROYGLOBALS()
  210.   EXIT(n);
  211. }
  212.  
  213.  
  214. int flush(w)    /* used by inflate.c (FLUSH macro) */
  215. ulg w;          /* number of bytes to flush */
  216. {
  217.   G.crc32val = crc32(G.crc32val, slide, (extent)w);
  218.   if (fwrite((char *)slide,1,(extent)w,out) != (extent)w && !PIPE_ERROR)
  219.     err(9, "out of space on stdout");
  220.   outsiz += w;
  221.   return 0;
  222. }
  223.  
  224.  
  225. int main(argc, argv)
  226. int argc;
  227. char **argv;
  228. /* Given a zipfile on stdin, decompress the first entry to stdout. */
  229. {
  230.   ush n;
  231.   uch h[LOCHDR];                /* first local header (GZPHDR < LOCHDR) */
  232.   int g = 0;                    /* true if gzip format */
  233. #if CRYPT
  234.   char *s = " [-password]";
  235.   char *p;                      /* password */
  236. #else /* !CRYPT */
  237.   char *s = "";
  238. #endif /* ?CRYPT */
  239.   CONSTRUCTGLOBALS();
  240.  
  241.   /* skip executable name */
  242.   argc--;
  243.   argv++;
  244.  
  245. #if CRYPT
  246.   /* get the command line password, if any */
  247.   p = (char *)NULL;
  248.   if (argc && **argv == '-')
  249.   {
  250.     argc--;
  251.     p = 1 + *argv++;
  252.   }
  253. #endif /* CRYPT */
  254.  
  255. #ifdef MALLOC_WORK
  256.   G.area.Slide = (uch *)calloc(8193, sizeof(short)+sizeof(char)+sizeof(char));
  257. #endif
  258.  
  259.   /* if no file argument and stdin not redirected, give the user help */
  260.   if (argc == 0 && isatty(0))
  261.   {
  262.     Info(slide, 1, ((char *)slide, "fUnZip (filter UnZip), version %s\n",
  263.       VERSION));
  264.     Info(slide, 1, ((char *)slide, "usage: ... | funzip%s | ...\n", s));
  265.     Info(slide, 1, ((char *)slide, "       ... | funzip%s > outfile\n", s));
  266.     Info(slide, 1, ((char *)slide, "       funzip%s infile.zip > outfile\n",s));
  267.     Info(slide, 1, ((char *)slide, "       funzip%s infile.gz > outfile\n", s));
  268.     Info(slide, 1, ((char *)slide, "Extracts to stdout the gzip file or first\
  269.  zip entry of stdin or the given file.\n"));
  270.     DESTROYGLOBALS()
  271.     EXIT(3);
  272.   }
  273.  
  274.   /* prepare to be a binary filter */
  275.   if (argc)
  276.   {
  277.     if ((G.in = fopen(*argv, FOPR)) == (FILE *)NULL)
  278.       err(2, "cannot find input file");
  279.   }
  280.   else
  281.   {
  282. #ifdef DOS_H68_OS2_W32
  283. #ifdef __HIGHC__
  284.     setmode(stdin, _BINARY);
  285. #else
  286.     setmode(0, O_BINARY);  /* some buggy C libraries require BOTH setmode() */
  287. #endif                     /*  call AND the fdopen() in binary mode :-( */
  288. #endif /* DOS_H68_OS2_W32 */
  289.  
  290. #ifdef RISCOS
  291.     G.in = stdin;
  292. #else
  293.     if ((G.in = fdopen(0, FOPR)) == (FILE *)NULL)
  294.       err(2, "cannot find stdin");
  295. #endif
  296.   }
  297.  
  298. #ifdef DOS_H68_OS2_W32
  299. #ifdef __HIGHC__
  300.   setmode(stdout, _BINARY);
  301. #else
  302.   setmode(1, O_BINARY);
  303. #endif
  304. #endif /* DOS_H68_OS2_W32 */
  305.  
  306. #ifdef RISCOS
  307.   out = stdout;
  308. #else
  309.   if ((out = fdopen(1, FOPW)) == (FILE *)NULL)
  310.     err(2, "cannot write to stdout");
  311. #endif
  312.  
  313.   /* read local header, check validity, and skip name and extra fields */
  314.   n = getc(G.in);  n |= getc(G.in) << 8;
  315.   if (n == ZIPMAG)
  316.   {
  317.     if (fread((char *)h, 1, LOCHDR, G.in) != LOCHDR || SH(h) != LOCREM)
  318.       err(3, "invalid zipfile");
  319.     if (SH(h + LOCHOW) != STORED && SH(h + LOCHOW) != DEFLATED)
  320.       err(3, "first entry not deflated or stored--can't funzip");
  321.     for (n = SH(h + LOCFIL); n--; ) g = getc(G.in);
  322.     for (n = SH(h + LOCEXT); n--; ) g = getc(G.in);
  323.     g = 0;
  324.     encrypted = h[LOCFLG] & CRPFLG;
  325.   }
  326.   else if (n == GZPMAG)
  327.   {
  328.     if (fread((char *)h, 1, GZPHDR, G.in) != GZPHDR)
  329.       err(3, "invalid gzip file");
  330.     if (h[GZPHOW] != DEFLATED)
  331.       err(3, "gzip file not deflated");
  332.     if (h[GZPFLG] & GZPMUL)
  333.       err(3, "cannot handle multi-part gzip files");
  334.     if (h[GZPFLG] & GZPISX)
  335.     {
  336.       n = getc(G.in);  n |= getc(G.in) << 8;
  337.       while (n--) g = getc(G.in);
  338.     }
  339.     if (h[GZPFLG] & GZPISF)
  340.       while ((g = getc(G.in)) != 0 && g != EOF) ;
  341.     if (h[GZPFLG] & GZPISC)
  342.       while ((g = getc(G.in)) != 0 && g != EOF) ;
  343.     g = 1;
  344.     encrypted = h[GZPFLG] & GZPISE;
  345.   }
  346.   else
  347.     err(3, "input not a zip or gzip file");
  348.  
  349.   /* if entry encrypted, decrypt and validate encryption header */
  350.   if (encrypted)
  351. #if CRYPT
  352.     {
  353.       ush i, e;
  354.  
  355.       if (p == (char *)NULL)
  356.         if ((p = (char *)malloc(PWLEN+1)) == (char *)NULL)
  357.           err(1, "out of memory");
  358.         else if ((p = getp("Enter password: ", p, PWLEN+1)) == (char *)NULL)
  359.           err(1, "no tty to prompt for password");
  360. #if (defined(USE_ZLIB) && !defined(USE_OWN_CRCTAB))
  361.       /* initialize crc_32_tab pointer for decryption */
  362.       crc_32_tab = (ulg near *)get_crc_table();
  363. #endif
  364.       init_keys(p);
  365.       for (i = 0; i < RAND_HEAD_LEN; i++)
  366.         e = NEXTBYTE;
  367.       if (e != (ush)(h[LOCFLG] & EXTFLG ? h[LOCTIM + 1] : h[LOCCRC + 3]))
  368.         err(3, "incorrect password for first entry");
  369.     }
  370. #else /* !CRYPT */
  371.     err(3, "cannot decrypt entry (need to recompile with full crypt.c)");
  372. #endif /* ?CRYPT */
  373.  
  374.   /* prepare output buffer and crc */
  375.   G.outptr = slide;
  376.   G.outcnt = 0L;
  377.   outsiz = 0L;
  378.   G.crc32val = CRCVAL_INITIAL;
  379.  
  380.   /* decompress */
  381.   if (g || h[LOCHOW])
  382.   {                             /* deflated entry */
  383.     int r;
  384.  
  385. #ifdef USE_ZLIB
  386.     /* need to allocate and prepare input buffer */
  387.     if ((G.inbuf = (uch *)malloc(INBUFSIZ)) == (uch *)NULL)
  388.        err(1, "out of memory");
  389. #endif /* USE_ZLIB */
  390.     if ((r = UZinflate(__G)) != 0)
  391.       if (r == 3)
  392.         err(1, "out of memory");
  393.       else
  394.         err(4, "invalid compressed data--format violated");
  395.     inflate_free(__G);
  396.   }
  397.   else
  398.   {                             /* stored entry */
  399.     register ulg n;
  400.  
  401.     n = LG(h + LOCLEN);
  402. #if CRYPT
  403.     if (n != LG(h + LOCSIZ) - (encrypted ? RAND_HEAD_LEN : 0)) {
  404. #else
  405.     if (n != LG(h + LOCSIZ)) {
  406. #endif
  407.       Info(slide, 1, ((char *)slide, "len %ld, siz %ld\n", n, LG(h + LOCSIZ)));
  408.       err(4, "invalid compressed data--length mismatch");
  409.     }
  410.     while (n--) {
  411.       ush c = getc(G.in);
  412. #if CRYPT
  413.       if (encrypted)
  414.         zdecode(c);
  415. #endif
  416.       *G.outptr++ = (uch)c;
  417.       if (++G.outcnt == WSIZE)    /* do FlushOutput() */
  418.       {
  419.         G.crc32val = crc32(G.crc32val, slide, (extent)G.outcnt);
  420.         if (fwrite((char *)slide, 1,(extent)G.outcnt,out) != (extent)G.outcnt
  421.             && !PIPE_ERROR)
  422.           err(9, "out of space on stdout");
  423.         outsiz += G.outcnt;
  424.         G.outptr = slide;
  425.         G.outcnt = 0L;
  426.       }
  427.     }
  428.   }
  429.   if (G.outcnt)   /* flush one last time; no need to reset G.outptr/outcnt */
  430.   {
  431.     G.crc32val = crc32(G.crc32val, slide, (extent)G.outcnt);
  432.     if (fwrite((char *)slide, 1,(extent)G.outcnt,out) != (extent)G.outcnt
  433.         && !PIPE_ERROR)
  434.       err(9, "out of space on stdout");
  435.     outsiz += G.outcnt;
  436.   }
  437.   fflush(out);
  438.  
  439.   /* if extended header, get it */
  440.   if (g)
  441.   {
  442.     if (fread((char *)h + LOCCRC, 1, 8, G.in) != 8)
  443.       err(3, "gzip file ended prematurely");
  444.   }
  445.   else
  446.     if ((h[LOCFLG] & EXTFLG) &&
  447.         fread((char *)h + LOCCRC - 4, 1, EXTHDR, G.in) != EXTHDR)
  448.       err(3, "zipfile ended prematurely");
  449.  
  450.   /* validate decompression */
  451.   if (LG(h + LOCCRC) != G.crc32val)
  452.     err(4, "invalid compressed data--crc error");
  453.   if (LG((g ? (h + LOCSIZ) : (h + LOCLEN))) != outsiz)
  454.     err(4, "invalid compressed data--length error");
  455.  
  456.   /* check if there are more entries */
  457.   if (!g && fread((char *)h, 1, 4, G.in) == 4 && LG(h) == LOCSIG)
  458.     Info(slide, 1, ((char *)slide,
  459.       "funzip warning: zipfile has more than one entry--rest ignored\n"));
  460.  
  461.   DESTROYGLOBALS()
  462.   RETURN (0);
  463. }
  464.