home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip52.zip / funzip.c < prev    next >
C/C++ Source or Header  |  1996-04-29  |  16KB  |  456 lines

  1. /* funzip.c -- put in the public domain by Mark Adler */
  2.  
  3. #define VERSION "3.9 of 30 April 1996"
  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.  */
  73.  
  74.  
  75. /*
  76.  
  77.    All funzip does is take a zip file from stdin and decompress the
  78.    first entry to stdout.  The entry has to be either deflated or
  79.    stored.  If the entry is encrypted, then the decryption password
  80.    must be supplied on the command line as the first argument.
  81.  
  82.    funzip needs to be linked with inflate.o and crypt.o compiled from
  83.    the unzip source.  If decryption is desired, the full version of
  84.    crypt.c (and crypt.h) from zcrypt21.zip or later must be used.
  85.  
  86.  */
  87.  
  88. #define FUNZIP
  89. #define UNZIP_INTERNAL
  90. #include "unzip.h"
  91. #include "crypt.h"
  92. #include "ttyio.h"
  93.  
  94. #ifdef EBCDIC
  95. #  undef EBCDIC                 /* don't need ebcdic[] */
  96. #endif
  97. #include "tables.h"             /* crc_32_tab[] */
  98.  
  99. #ifndef USE_ZLIB  /* zlib's function is called inflate(), too */
  100. #  define UZinflate inflate
  101. #endif
  102.  
  103. /* PKZIP header definitions */
  104. #define ZIPMAG 0x4b50           /* two-byte zip lead-in */
  105. #define LOCREM 0x0403           /* remaining two bytes in zip signature */
  106. #define LOCSIG 0x04034b50L      /* full signature */
  107. #define LOCFLG 4                /* offset of bit flag */
  108. #define  CRPFLG 1               /*  bit for encrypted entry */
  109. #define  EXTFLG 8               /*  bit for extended local header */
  110. #define LOCHOW 6                /* offset of compression method */
  111. #define LOCTIM 8                /* file mod time (for decryption) */
  112. #define LOCCRC 12               /* offset of crc */
  113. #define LOCSIZ 16               /* offset of compressed size */
  114. #define LOCLEN 20               /* offset of uncompressed length */
  115. #define LOCFIL 24               /* offset of file name field length */
  116. #define LOCEXT 26               /* offset of extra field length */
  117. #define LOCHDR 28               /* size of local header, including LOCREM */
  118. #define EXTHDR 16               /* size of extended local header, inc sig */
  119.  
  120. /* GZIP header definitions */
  121. #define GZPMAG 0x8b1f           /* two-byte gzip lead-in */
  122. #define GZPHOW 0                /* offset of method number */
  123. #define GZPFLG 1                /* offset of gzip flags */
  124. #define  GZPMUL 2               /* bit for multiple-part gzip file */
  125. #define  GZPISX 4               /* bit for extra field present */
  126. #define  GZPISF 8               /* bit for filename present */
  127. #define  GZPISC 16              /* bit for comment present */
  128. #define  GZPISE 32              /* bit for encryption */
  129. #define GZPTIM 2                /* offset of Unix file modification time */
  130. #define GZPEXF 6                /* offset of extra flags */
  131. #define GZPCOS 7                /* offset of operating system compressed on */
  132. #define GZPHDR 8                /* length of minimal gzip header */
  133.  
  134. /* Macros for getting two-byte and four-byte header values */
  135. #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
  136. #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
  137.  
  138. /* Function prototypes */
  139. void err OF((int, char *));
  140. void main OF((int, char **));
  141.  
  142. /* Globals */
  143. FILE *out;                      /* output file (*in moved to G struct) */
  144. ulg outsiz;                     /* total bytes written to out */
  145. int encrypted;                  /* flag to turn on decryption */
  146.  
  147. /* Masks for inflate.c */
  148. ush near mask_bits[] = {
  149.     0x0000,
  150.     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  151.     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  152. };
  153.  
  154.  
  155. #ifdef USE_ZLIB
  156.  
  157. int fillinbuf(__G)
  158. __GDEF
  159. /* Fill input buffer for pull-model inflate() in zlib.  Return the number of
  160.  * bytes in inbuf. */
  161. {
  162. /*   GRR: check return value from fread(): same as read()?  check errno? */
  163.   if ((G.incnt = fread((char *)G.inbuf, 1, INBUFSIZ, G.in)) <= 0)
  164.     return 0;
  165.   G.inptr = G.inbuf;
  166.  
  167. #ifdef CRYPT
  168.   if (encrypted) {
  169.     uch *p;
  170.     int n;
  171.  
  172.     for (n = G.incnt, p = G.inptr;  n--;  p++)
  173.       zdecode(*p);
  174.   }
  175. #endif /* CRYPT */
  176.  
  177.   return G.incnt;
  178.  
  179. }
  180.  
  181. #endif /* USE_ZLIB */
  182.  
  183.  
  184. #if (!defined(USE_ZLIB) || defined(USE_OWN_CRCTAB))
  185. #ifdef USE_ZLIB
  186. uLongf *get_crc_table()
  187. {
  188.   return (uLongf *)crc_32_tab;
  189. }
  190. #else /* !USE_ZLIB */
  191. ulg near *get_crc_table()
  192. {
  193.   return crc_32_tab;
  194. }
  195. #endif /* ?USE_ZLIB */
  196. #endif /* !USE_ZLIB || USE_OWN_CRCTAB */
  197.  
  198.  
  199. void err(n, m)
  200. int n;
  201. char *m;
  202. /* Exit on error with a message and a code */
  203. {
  204.   Info(slide, 1, ((char *)slide, "funzip error: %s\n", m));
  205.   DESTROYGLOBALS()
  206.   exit(n);
  207. }
  208.  
  209.  
  210. int flush(w)    /* used by inflate.c (FLUSH macro) */
  211. ulg w;          /* number of bytes to flush */
  212. {
  213.   G.crc32val = crc32(G.crc32val, slide, (extent)w);
  214.   if (fwrite((char *)slide,1,(extent)w,out) != (extent)w && !PIPE_ERROR)
  215.     err(9, "out of space on stdout");
  216.   outsiz += w;
  217.   return 0;
  218. }
  219.  
  220.  
  221. void main(argc, argv)
  222. int argc;
  223. char **argv;
  224. /* Given a zip file on stdin, decompress the first entry to stdout. */
  225. {
  226.   ush n;
  227.   uch h[LOCHDR];                /* first local header (GZPHDR < LOCHDR) */
  228.   int g = 0;                    /* true if gzip format */
  229. #ifdef CRYPT
  230.   char *s = " [-password]";
  231.   char *p;                      /* password */
  232. #else /* !CRYPT */
  233.   char *s = "";
  234. #endif /* ?CRYPT */
  235.   CONSTRUCTGLOBALS();
  236.  
  237.   /* skip executable name */
  238.   argc--;
  239.   argv++;
  240.  
  241. #ifdef CRYPT
  242.   /* get the command line password, if any */
  243.   p = (char *)NULL;
  244.   if (argc && **argv == '-')
  245.   {
  246.     argc--;
  247.     p = 1 + *argv++;
  248.   }
  249. #endif /* CRYPT */
  250.  
  251. #ifdef MALLOC_WORK
  252.   G.area.Slide = (uch *)calloc(8193, sizeof(short)+sizeof(char)+sizeof(char));
  253. #endif
  254.  
  255.   /* if no file argument and stdin not redirected, give the user help */
  256.   if (argc == 0 && isatty(0))
  257.   {
  258.     Info(slide, 1, ((char *)slide, "fUnZip (filter UnZip), version %s\n",
  259.       VERSION));
  260.     Info(slide, 1, ((char *)slide, "usage: ... | funzip%s | ...\n", s));
  261.     Info(slide, 1, ((char *)slide, "       ... | funzip%s > outfile\n", s));
  262.     Info(slide, 1, ((char *)slide, "       funzip%s infile.zip > outfile\n",s));
  263.     Info(slide, 1, ((char *)slide, "       funzip%s infile.gz > outfile\n", s));
  264.     Info(slide, 1, ((char *)slide, "Extracts to stdout the gzip file or first\
  265.  zip entry of stdin or the given file.\n"));
  266.     DESTROYGLOBALS()
  267.     exit(3);
  268.   }
  269.  
  270.   /* prepare to be a binary filter */
  271.   if (argc)
  272.   {
  273.     if ((G.in = fopen(*argv, FOPR)) == (FILE *)NULL)
  274.       err(2, "cannot find input file");
  275.   }
  276.   else
  277.   {
  278. #ifdef DOS_H68_OS2_W32
  279. #ifdef __HIGHC__
  280.     setmode(stdin, _BINARY);
  281. #else
  282.     setmode(0, O_BINARY);  /* some buggy C libraries require BOTH setmode() */
  283. #endif                     /*  call AND the fdopen() in binary mode :-( */
  284. #endif /* DOS_H68_OS2_W32 */
  285.  
  286. #ifdef RISCOS
  287.     G.in = stdin;
  288. #else
  289.     if ((G.in = fdopen(0, FOPR)) == (FILE *)NULL)
  290.       err(2, "cannot find stdin");
  291. #endif
  292.   }
  293.  
  294. #ifdef DOS_H68_OS2_W32
  295. #ifdef __HIGHC__
  296.   setmode(stdout, _BINARY);
  297. #else
  298.   setmode(1, O_BINARY);
  299. #endif
  300. #endif /* DOS_H68_OS2_W32 */
  301.  
  302. #ifdef RISCOS
  303.   out = stdout;
  304. #else
  305.   if ((out = fdopen(1, FOPW)) == (FILE *)NULL)
  306.     err(2, "cannot write to stdout");
  307. #endif
  308.  
  309.   /* read local header, check validity, and skip name and extra fields */
  310.   n = getc(G.in);  n |= getc(G.in) << 8;
  311.   if (n == ZIPMAG)
  312.   {
  313.     if (fread((char *)h, 1, LOCHDR, G.in) != LOCHDR || SH(h) != LOCREM)
  314.       err(3, "invalid zip file");
  315.     if (SH(h + LOCHOW) != STORED && SH(h + LOCHOW) != DEFLATED)
  316.       err(3, "first entry not deflated or stored--can't funzip");
  317.     for (n = SH(h + LOCFIL); n--; ) g = getc(G.in);
  318.     for (n = SH(h + LOCEXT); n--; ) g = getc(G.in);
  319.     g = 0;
  320.     encrypted = h[LOCFLG] & CRPFLG;
  321.   }
  322.   else if (n == GZPMAG)
  323.   {
  324.     if (fread((char *)h, 1, GZPHDR, G.in) != GZPHDR)
  325.       err(3, "invalid gzip file");
  326.     if (h[GZPHOW] != DEFLATED)
  327.       err(3, "gzip file not deflated");
  328.     if (h[GZPFLG] & GZPMUL)
  329.       err(3, "cannot handle multi-part gzip files");
  330.     if (h[GZPFLG] & GZPISX)
  331.     {
  332.       n = getc(G.in);  n |= getc(G.in) << 8;
  333.       while (n--) g = getc(G.in);
  334.     }
  335.     if (h[GZPFLG] & GZPISF)
  336.       while ((g = getc(G.in)) != 0 && g != EOF) ;
  337.     if (h[GZPFLG] & GZPISC)
  338.       while ((g = getc(G.in)) != 0 && g != EOF) ;
  339.     g = 1;
  340.     encrypted = h[GZPFLG] & GZPISE;
  341.   }
  342.   else
  343.     err(3, "input not a zip or gzip file");
  344.  
  345.   /* if entry encrypted, decrypt and validate encryption header */
  346.   if (encrypted)
  347. #ifdef CRYPT
  348.     {
  349.       ush i, e;
  350.  
  351.       if (p == (char *)NULL)
  352.         if ((p = (char *)malloc(PWLEN+1)) == (char *)NULL)
  353.           err(1, "out of memory");
  354.         else if ((p = getp("Enter password: ", p, PWLEN+1)) == (char *)NULL)
  355.           err(1, "no tty to prompt for password");
  356. #if (defined(USE_ZLIB) && !defined(USE_OWN_CRCTAB))
  357.       /* initialize crc_32_tab pointer for decryption */
  358.       crc_32_tab = (ulg near *)get_crc_table();
  359. #endif
  360.       init_keys(p);
  361.       for (i = 0; i < RAND_HEAD_LEN; i++)
  362.         e = NEXTBYTE;
  363.       if (e != (ush)(h[LOCFLG] & EXTFLG ? h[LOCTIM + 1] : h[LOCCRC + 3]))
  364.         err(3, "incorrect password for first entry");
  365.     }
  366. #else /* !CRYPT */
  367.     err(3, "cannot decrypt entry (need to recompile with full crypt.c)");
  368. #endif /* ?CRYPT */
  369.  
  370.   /* prepare output buffer and crc */
  371.   G.outptr = slide;
  372.   G.outcnt = 0L;
  373.   outsiz = 0L;
  374.   G.crc32val = CRCVAL_INITIAL;
  375.  
  376.   /* decompress */
  377.   if (g || h[LOCHOW])
  378.   {                             /* deflated entry */
  379.     int r;
  380.  
  381. #ifdef USE_ZLIB
  382.     /* need to allocate and prepare input buffer */
  383.     if ((G.inbuf = (uch *)malloc(INBUFSIZ)) == (uch *)NULL)
  384.        err(1, "out of memory");
  385. #endif /* USE_ZLIB */
  386.     if ((r = UZinflate(__G)) != 0)
  387.       if (r == 3)
  388.         err(1, "out of memory");
  389.       else
  390.         err(4, "invalid compressed data--format violated");
  391.     inflate_free(__G);
  392.   }
  393.   else
  394.   {                             /* stored entry */
  395.     register ulg n;
  396.  
  397.     n = LG(h + LOCLEN);
  398.     if (n != LG(h + LOCSIZ) - (encrypted ? RAND_HEAD_LEN : 0)) {
  399.       Info(slide, 1, ((char *)slide, "len %ld, siz %ld\n", n, LG(h + LOCSIZ)));
  400.       err(4, "invalid compressed data--length mismatch");
  401.     }
  402.     while (n--) {
  403.       ush c = getc(G.in);
  404. #ifdef CRYPT
  405.       if (encrypted)
  406.         zdecode(c);
  407. #endif
  408.       *G.outptr++ = (uch)c;
  409.       if (++G.outcnt == WSIZE)    /* do FlushOutput() */
  410.       {
  411.         G.crc32val = crc32(G.crc32val, slide, (extent)G.outcnt);
  412.         if (fwrite((char *)slide, 1,(extent)G.outcnt,out) != (extent)G.outcnt
  413.             && !PIPE_ERROR)
  414.           err(9, "out of space on stdout");
  415.         outsiz += G.outcnt;
  416.         G.outptr = slide;
  417.         G.outcnt = 0L;
  418.       }
  419.     }
  420.   }
  421.   if (G.outcnt)   /* flush one last time; no need to reset G.outptr/outcnt */
  422.   {
  423.     G.crc32val = crc32(G.crc32val, slide, (extent)G.outcnt);
  424.     if (fwrite((char *)slide, 1,(extent)G.outcnt,out) != (extent)G.outcnt
  425.         && !PIPE_ERROR)
  426.       err(9, "out of space on stdout");
  427.     outsiz += G.outcnt;
  428.   }
  429.   fflush(out);
  430.  
  431.   /* if extended header, get it */
  432.   if (g)
  433.   {
  434.     if (fread((char *)h + LOCCRC, 1, 8, G.in) != 8)
  435.       err(3, "gzip file ended prematurely");
  436.   }
  437.   else
  438.     if ((h[LOCFLG] & EXTFLG) &&
  439.         fread((char *)h + LOCCRC - 4, 1, EXTHDR, G.in) != EXTHDR)
  440.       err(3, "zip file ended prematurely");
  441.  
  442.   /* validate decompression */
  443.   if (LG(h + LOCCRC) != G.crc32val)
  444.     err(4, "invalid compressed data--crc error");
  445.   if (LG((g ? (h + LOCSIZ) : (h + LOCLEN))) != outsiz)
  446.     err(4, "invalid compressed data--length error");
  447.  
  448.   /* check if there are more entries */
  449.   if (!g && fread((char *)h, 1, 4, G.in) == 4 && LG(h) == LOCSIG)
  450.     Info(slide, 1, ((char *)slide,
  451.       "funzip warning: zip file has more than one entry--rest ignored\n"));
  452.  
  453.   DESTROYGLOBALS()
  454.   exit(0);
  455. }
  456.