home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume8 / unzip_gs / unzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-09-23  |  39.3 KB  |  1,657 lines

  1.  
  2. /*
  3.  * Copyright 1989 Samuel H. Smith;  All rights reserved
  4.  *
  5.  * Do not distribute modified versions without my permission.
  6.  * Do not remove or alter this notice or any other copyright notice.
  7.  * If you use this in your own program you must distribute source code.
  8.  * Do not use any of this in a commercial product.
  9.  *
  10.  */
  11.  
  12. /*
  13.  * UnZip - A simple zipfile extract utility
  14.  *
  15.  * To compile:
  16.  *      tcc -B -O -Z -G -mc unzip.c    ;turbo C 2.0, compact model
  17.  *    cl /O /AC /G0 /W3 -c unzip.    ;msc 5.1, compact model
  18.  *    cc -O -DOLDC -Dunix {-DHIGH_LOW} {-DSHORTC} -c unzip.c    ;unix pcc
  19.  *
  20.  * Port to Unix and MSC (i.e. "portable version") by George M. Sipe
  21.  * (rebel!george).
  22.  *
  23.  */
  24.  
  25. #define VERSION  \
  26.     "UnZip:  Zipfile Extract v2.0.1 of 09-16-89;  (C) 1989 Samuel H. Smith"
  27.  
  28. #ifdef    SHORTC
  29. #define    compressed_size        cmpr_sz
  30. #define    extract_zipfile        ext_zip
  31. #define    filename        fn
  32. #define    follower        flwr
  33. #define    hsize_array_byte    hsz_a_byte
  34. #define    last_mod_file_date    mod_fdate
  35. #define    lit_tree_present    lt_present
  36. #define    maxcodemax        mx_cd_mx
  37. #define    number_disk_with_start_central_directory ndwsc
  38. #define    process_central_file_header pcfhdr
  39. #define    process_end_central_dir    pecdir
  40. #define    process_headers        proc_hdrs
  41. #define    total_entries_central_dir tecdir
  42. #define    version_made_by        v_made_by
  43. #define    LoadTrees        LdTrees
  44. #endif    /* SHORTC */
  45.  
  46. typedef unsigned char byte;    /* code assumes UNSIGNED bytes */
  47. typedef long longint;        /* sizeof must be 4 bytes */
  48. typedef unsigned short word;    /* sizeof must be 2 bytes */
  49. typedef char boolean;
  50.  
  51. #define STRSIZ 256
  52.  
  53. #include <stdio.h>
  54.  /* this is your standard header for all C compiles */
  55.  
  56. #ifndef    OLDC
  57. #include <stdlib.h>
  58.  /* this include defines various standard library prototypes */
  59. #define    VOIDARG    void        /* function definitions support (void) */
  60. #else
  61. #include <ctype.h>
  62. #define    VOIDARG            /* function definitions support () only */
  63. #endif    /* OLDC */
  64.  
  65.  
  66. /*
  67.  * SEE HOST OPERATING SYSTEM SPECIFICS SECTION STARTING NEAR LINE 180
  68.  *
  69.  */
  70.  
  71.  
  72. /* ----------------------------------------------------------- */
  73. /*
  74.  * Zipfile layout declarations
  75.  *
  76.  */
  77.  
  78. typedef longint signature_type;
  79.  
  80.  
  81. #define LOCAL_FILE_HEADER_SIGNATURE  0x04034b50L
  82.  
  83.  
  84. typedef struct local_file_header {
  85.     word version_needed_to_extract;
  86.         word general_purpose_bit_flag;
  87.     word compression_method;
  88.     word last_mod_file_time;
  89.     word last_mod_file_date;
  90.     longint crc32;
  91.     longint compressed_size;
  92.         longint uncompressed_size;
  93.     word filename_length;
  94.     word extra_field_length;
  95. } local_file_header;
  96.  
  97.  
  98. #define CENTRAL_FILE_HEADER_SIGNATURE  0x02014b50L
  99.  
  100.  
  101. typedef struct central_directory_file_header {
  102.     word version_made_by;
  103.     word version_needed_to_extract;
  104.     word general_purpose_bit_flag;
  105.     word compression_method;
  106.     word last_mod_file_time;
  107.     word last_mod_file_date;
  108.     longint crc32;
  109.     longint compressed_size;
  110.     longint uncompressed_size;
  111.     word filename_length;
  112.     word extra_field_length;
  113.     word file_comment_length;
  114.     word disk_number_start;
  115.     word internal_file_attributes;
  116.     longint external_file_attributes;
  117.     longint relative_offset_local_header;
  118. } central_directory_file_header;
  119.  
  120.  
  121. #define END_CENTRAL_DIR_SIGNATURE  0x06054b50L
  122.  
  123.  
  124. typedef struct end_central_dir_record {
  125.     word number_this_disk;
  126. #ifndef    TURBOC
  127.     word num_disk_with_start_cent_dir;
  128.     word tot_ents_cent_dir_on_this_disk;
  129. #else
  130.     word number_disk_with_start_central_directory;
  131.     word total_entries_central_dir_on_this_disk;
  132. #endif    /* TURBOC */
  133.     word total_entries_central_dir;
  134.     longint size_central_directory;
  135.     longint offset_start_central_directory;
  136.     word zipfile_comment_length;
  137. } end_central_dir_record;
  138.  
  139.  
  140.  
  141. /* ----------------------------------------------------------- */
  142. /*
  143.  * input file variables
  144.  *
  145.  */
  146.  
  147. #define INBUFSIZ 0x2000
  148. byte *inbuf;            /* input file buffer - any size is legal */
  149. byte *inptr;
  150.  
  151. int incnt;
  152. unsigned bitbuf;
  153. int bits_left;
  154. boolean zipeof;
  155.  
  156. int zipfd;
  157. char zipfn[STRSIZ];
  158. local_file_header lrec;
  159.  
  160. #ifdef    HIGH_LOW
  161. int w0, w1;            /* word translation indices */
  162. int li0, li1, li2, li3;        /* long int translation indices */
  163. #endif    /* HIGH_LOW */
  164.  
  165.  
  166. /* ----------------------------------------------------------- */
  167. /*
  168.  * output stream variables
  169.  *
  170.  */
  171.  
  172. #define OUTBUFSIZ 0x2000        /* must be 0x2000 or larger for unImplode */
  173. byte *outbuf;                   /* buffer for rle look-back */
  174. byte *outptr;
  175.  
  176. longint outpos;            /* absolute position in outfile */
  177. int outcnt;            /* current position in outbuf */
  178.  
  179. int outfd;
  180. char filename[STRSIZ];
  181. char extra[STRSIZ];
  182.  
  183. #define DLE 144
  184.  
  185.  
  186. /* ----------------------------------------------------------- */
  187. /*
  188.  * shrink/reduce working storage
  189.  *
  190.  */
  191.  
  192. int factor;
  193. byte followers[256][64];
  194. byte Slen[256];
  195.  
  196. #define max_bits 13
  197. #define init_bits 9
  198. #define hsize 8192
  199. #define first_ent 257
  200. #define clear 256
  201.  
  202. typedef int hsize_array_integer[hsize+1];
  203. typedef byte hsize_array_byte[hsize+1];
  204.  
  205. hsize_array_integer prefix_of;
  206. hsize_array_byte suffix_of;
  207. hsize_array_byte stack;
  208.  
  209. int codesize;
  210. int maxcode;
  211. int free_ent;
  212. int maxcodemax;
  213. int offset;
  214. int sizex;
  215.  
  216.  
  217.  
  218. /* ============================================================= */
  219. /*
  220.  * Host operating system details
  221.  *
  222.  */
  223.  
  224. #include <string.h>
  225.  /* this include defines strcpy, strcmp, etc. */
  226.  
  227. #ifndef    TURBOC
  228. #include <sys/types.h>
  229.  /*
  230.   * this include file defines
  231.   *        dev_t (* device type *)
  232.   * as used in the sys/utime.h and sys/stat.h header files below
  233.   */
  234.  
  235. #ifndef    OLDC
  236. #include <sys/utime.h>
  237.  /*
  238.   * this include file defines
  239.   *        struct utimbuf (* utime buffer structure *)
  240.   *        utime()        (* utime function *)
  241.   * as used in the set_file_time() function defined below
  242.   */
  243. #endif    /* !OLDC */
  244. #endif    /* !TURBOC */
  245.  
  246. #ifndef    TURBOC
  247. #include <time.h>
  248. struct ftime {
  249.     unsigned ft_tsec: 5;    /* two seconds */
  250.     unsigned ft_min: 6;    /* minutes */
  251.     unsigned ft_hour: 5;    /* hours */
  252.     unsigned ft_day: 5;    /* days */
  253.     unsigned ft_month: 4;    /* months */
  254.     unsigned ft_year: 7;    /* years  - 1980 */
  255. };
  256. #endif    /* TURBOC */
  257. #ifndef    OLDC
  258. #include <io.h>
  259. #else
  260. #include <sys/file.h>
  261. #ifdef    L_SET
  262. #define    SEEK_SET    L_SET
  263. #else
  264. #define    SEEK_SET    0
  265. #endif    /* L_SET */
  266. #endif    /* OLDC */
  267.  /*
  268.   * this include file defines
  269.   *             struct ftime ...        (* file time/date stamp info *)
  270.   *             int setftime (int handle, struct ftime *ftimep);
  271.   *             #define SEEK_CUR  1     (* lseek() modes *)
  272.   *             #define SEEK_END  2
  273.   *             #define SEEK_SET  0
  274.   */
  275.  
  276. #include <fcntl.h>
  277. #ifndef    O_BINARY
  278. #define    O_BINARY    0
  279. #endif    /* O_BINARY */
  280.  /*
  281.   * this include file defines
  282.   *             #define O_BINARY 0x8000  (* no cr-lf translation *)
  283.   * as used in the open() standard function
  284.   */
  285.  
  286. #include <sys/stat.h>
  287.  /*
  288.   * this include file defines
  289.   *             #define S_IREAD 0x0100  (* owner may read *)
  290.   *             #define S_IWRITE 0x0080 (* owner may write *)
  291.   * as used in the creat() standard function
  292.   */
  293.  
  294. /* #undef HIGH_LOW - define externally */
  295.  /*
  296.   * change 'undef' to 'define' if your machine stores high order bytes in
  297.   * lower addresses.
  298.   */
  299.  
  300. void set_file_time(VOIDARG)
  301.  /*
  302.   * set the output file date/time stamp according to information from the
  303.   * zipfile directory record for this file 
  304.   */
  305. {
  306.     union {
  307.                 struct ftime ft;        /* system file time record */
  308.         struct {
  309.                         word ztime;     /* date and time words */
  310.                         word zdate;     /* .. same format as in .ZIP file */
  311.         } zt;
  312.     } td;
  313.  
  314.     /*
  315.      * set output file date and time - this is optional and can be
  316.      * deleted if your compiler does not easily support setftime() 
  317.      */
  318. #ifdef    TURBOC
  319.     td.zt.ztime = lrec.last_mod_file_time;
  320.     td.zt.zdate = lrec.last_mod_file_date;
  321.  
  322.     setftime(outfd, &td.ft);
  323. #else
  324.  
  325. #define leap(y)     (((y) % 4 == 0 && (y) % 100 != 0) || (y) % 400 == 0)
  326. #define nleap(y) (((y) - 1969) / 4 - ((y) - 1901) / 100 + ((y) - 1601) / 400)
  327.  
  328.     static char month_lengths[] =
  329.         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  330.     int day_of_year, year;
  331. #ifndef    OLDC
  332.     struct utimbuf times;
  333. #else
  334.     struct utimbuf {
  335.         time_t actime;        /* file accessed time */
  336.         time_t modtime;        /* file updated time */
  337.     } times;
  338. #endif    /* OLDC */
  339.  
  340.     /*
  341.      * this is the standard Unix implementation (also fully
  342.      * compatible with MSC)
  343.      */
  344.  
  345.     close(outfd);
  346.     td.zt.ztime = lrec.last_mod_file_time;
  347.     td.zt.zdate = lrec.last_mod_file_date;
  348.     year = td.ft.ft_year + 1980;
  349.     if (td.ft.ft_month < 1 || td.ft.ft_month > 12 || td.ft.ft_day < 1
  350.         || td.ft.ft_day > month_lengths[td.ft.ft_month-1]
  351.         && !(td.ft.ft_month == 2 && td.ft.ft_day == 29 && leap (year))
  352.         || td.ft.ft_hour > 23 || td.ft.ft_min > 59 ||
  353.         td.ft.ft_tsec*2 > 59)
  354.         return;
  355.     day_of_year = td.ft.ft_day - 1;
  356.     if (td.ft.ft_month > 2 && leap(year)) ++day_of_year;
  357.     while (--td.ft.ft_month > 0)
  358.         day_of_year += month_lengths[td.ft.ft_month - 1];
  359.     times.modtime = (86400 * (long)(day_of_year + 365 * (year - 1970) 
  360.         + nleap (year)) + 3600 * (td.ft.ft_hour-1) + 60 * td.ft.ft_min
  361.         + td.ft.ft_tsec*2);
  362. #ifdef    HAVE_TZ
  363.     tzset();
  364.     times.modtime += timezone;
  365. #endif    /* HAVE_TZ */
  366.     times.actime = times.modtime;
  367.     utime(filename, ×);
  368. #endif    /* !TURBOC */
  369. }
  370.  
  371.  
  372. int create_output_file(VOIDARG)
  373.  /* return non-0 if creat failed */
  374. {
  375.     /* create the output file with READ and WRITE permissions */
  376.     outfd = creat(filename, S_IWRITE | S_IREAD | S_IREAD >> 3
  377.             | S_IREAD >> 6);
  378.     if (outfd < 1) {
  379.         printf("Can't create output: %s\n", filename);
  380.         return 1;
  381.     }
  382.  
  383.     /*
  384.      * close the newly created file and reopen it in BINARY mode to
  385.      * disable all CR/LF translations 
  386.      */
  387.     close(outfd);
  388.     outfd = open(filename, O_RDWR | O_BINARY);
  389.  
  390.     /* write a single byte at EOF to pre-allocate the file */
  391. #ifdef    tx
  392.     fsetsize(outfd, lrec.uncompressed_size);
  393. #endif    /* tx */
  394.         lseek(outfd, lrec.uncompressed_size - 1L, SEEK_SET);
  395.     write(outfd, "?", 1);
  396.     lseek(outfd, 0L, SEEK_SET);
  397.     return 0;
  398. }
  399.  
  400.  
  401. int open_input_file(VOIDARG)
  402.  /* return non-0 if creat failed */
  403. {
  404.     /*
  405.      * open the zipfile for reading and in BINARY mode to prevent cr/lf
  406.      * translation, which would corrupt the bitstreams 
  407.      */
  408.  
  409.     zipfd = open(zipfn, O_RDONLY | O_BINARY);
  410.     if (zipfd < 1) {
  411.         printf("Can't open input file: %s\n", zipfn);
  412.         return (1);
  413.     }
  414.     return 0;
  415. }
  416.  
  417.  
  418. #ifdef HIGH_LOW
  419.  
  420. #ifndef    OLDC
  421. void swap_bytes(word *wordp)
  422. #else
  423. void swap_bytes(wordp)
  424. word *wordp;
  425. #endif    /* OLDC */
  426.  /* convert intel style 'short int' variable to host format */
  427. {
  428.     char *charp = (char *) wordp;
  429.     char temp[2];
  430.  
  431.     temp[0] = charp[w0];
  432.     temp[1] = charp[w1];
  433.     charp[0] = temp[0];
  434.     charp[1] = temp[1];
  435. }
  436.  
  437. #ifndef    OLDC
  438. void swap_lbytes(longint *longp)
  439. #else
  440. void swap_lbytes(longp)
  441. longint *longp;
  442. #endif    /* OLDC */
  443.  /* convert intel style 'long' variable to host format */
  444. {
  445.     char *charp = (char *) longp;
  446.     char temp[4];
  447.  
  448.     temp[0] = charp[li0];
  449.     temp[1] = charp[li1];
  450.     temp[2] = charp[li2];
  451.     temp[3] = charp[li3];
  452.     charp[0] = temp[0];
  453.     charp[1] = temp[1];
  454.     charp[2] = temp[2];
  455.     charp[3] = temp[3];
  456. }
  457.  
  458. #endif    /* HIGH_LOW */
  459.  
  460.  
  461.  
  462. /* ============================================================= */
  463.  
  464. int FillBuffer(VOIDARG)
  465.  /* fill input buffer if possible */
  466. {
  467.     int readsize;
  468.  
  469.         if (lrec.compressed_size <= 0)
  470.         return incnt = 0;
  471.  
  472.         if (lrec.compressed_size > INBUFSIZ)
  473.         readsize = INBUFSIZ;
  474.     else
  475.                 readsize = (int) lrec.compressed_size;
  476.     incnt = read(zipfd, inbuf, readsize);
  477.  
  478.         lrec.compressed_size -= incnt;
  479.     inptr = inbuf;
  480.     return incnt--;
  481. }
  482.  
  483. #ifndef    OLDC
  484. int ReadByte(unsigned *x)
  485. #else
  486. int ReadByte(x)
  487. unsigned *x;
  488. #endif    /* OLDC */
  489.  /* read a byte; return 8 if byte available, 0 if not */
  490. {
  491.     if (incnt-- == 0)
  492.         if (FillBuffer() == 0)
  493.             return 0;
  494.  
  495.     *x = *inptr++;
  496.     return 8;
  497. }
  498.  
  499.  
  500. /* ------------------------------------------------------------- */
  501. static unsigned mask_bits[] =
  502.         {0,     0x0001, 0x0003, 0x0007, 0x000f,
  503.                 0x001f, 0x003f, 0x007f, 0x00ff,
  504.                 0x01ff, 0x03ff, 0x07ff, 0x0fff,
  505.                 0x1fff, 0x3fff, 0x7fff, 0xffff
  506.         };
  507.  
  508.  
  509. #ifndef    OLDC
  510. int FillBitBuffer(register int bits)
  511. #else
  512. int FillBitBuffer(bits)
  513. register int bits;
  514. #endif    /* OLDC */
  515.  /* read a byte; return 8 if byte available, 0 if not */
  516. {
  517.     /* get the bits that are left and read the next word */
  518.     unsigned temp;
  519.         register int result = bitbuf;
  520.     int sbits = bits_left;
  521.     bits -= bits_left;
  522.  
  523.     /* read next word of input */
  524.     bits_left = ReadByte(&bitbuf);
  525.     bits_left += ReadByte(&temp);
  526.     bitbuf |= (temp << 8);
  527.     if (bits_left == 0)
  528.         zipeof = 1;
  529.  
  530.     /* get the remaining bits */
  531.         result = result | (int) ((bitbuf & mask_bits[bits]) << sbits);
  532.         bitbuf >>= bits;
  533.         bits_left -= bits;
  534.         return result;
  535. }
  536.  
  537. #define READBIT(nbits,zdest,ztype) \
  538.     { if (nbits <= bits_left) \
  539.         { zdest = ztype(bitbuf & mask_bits[nbits]); \
  540.         bitbuf >>= nbits; bits_left -= nbits; } \
  541.     else zdest = ztype(FillBitBuffer(nbits));}
  542.  
  543. /*
  544.  * macro READBIT(nbits,zdest,ztype)
  545.  *  {
  546.  *      if (nbits <= bits_left) {
  547.  *          zdest = ztype(bitbuf & mask_bits[nbits]);
  548.  *          bitbuf >>= nbits;
  549.  *          bits_left -= nbits;
  550.  *      } else
  551.  *          zdest = ztype(FillBitBuffer(nbits));
  552.  *  }
  553.  *
  554.  */
  555.  
  556.  
  557. /* ------------------------------------------------------------- */
  558.  
  559. #include "crc32.h"
  560.  
  561.  
  562. /* ------------------------------------------------------------- */
  563.  
  564. void FlushOutput(VOIDARG)
  565.  /* flush contents of output buffer */
  566. {
  567.     UpdateCRC(outbuf, outcnt);
  568.     write(outfd, outbuf, outcnt);
  569.     outpos += outcnt;
  570.     outcnt = 0;
  571.     outptr = outbuf;
  572. }
  573.  
  574. #define OUTB(intc) { *outptr++=intc; if (++outcnt==OUTBUFSIZ) FlushOutput(); }
  575.  
  576. /*
  577.  *  macro OUTB(intc)
  578.  *  {
  579.  *      *outptr++=intc;
  580.  *      if (++outcnt==OUTBUFSIZ)
  581.  *          FlushOutput();
  582.  *  }
  583.  *
  584.  */
  585.  
  586.  
  587. /* ----------------------------------------------------------- */
  588.  
  589. void LoadFollowers(VOIDARG)
  590. {
  591.         register int x;
  592.         register int i;
  593.  
  594.     for (x = 255; x >= 0; x--) {
  595.                 READBIT(6,Slen[x],(byte));
  596.         for (i = 0; i < Slen[x]; i++) {
  597.                         READBIT(8,followers[x][i],(byte));
  598.         }
  599.     }
  600. }
  601.  
  602.  
  603. /* ----------------------------------------------------------- */
  604. /*
  605.  * The Reducing algorithm is actually a combination of two
  606.  * distinct algorithms.  The first algorithm compresses repeated
  607.  * byte sequences, and the second algorithm takes the compressed
  608.  * stream from the first algorithm and applies a probabilistic
  609.  * compression method.
  610.  */
  611.  
  612. int L_table[] = {0, 0x7f, 0x3f, 0x1f, 0x0f};
  613.  
  614. int D_shift[] = {0, 0x07, 0x06, 0x05, 0x04};
  615. int D_mask[]  = {0, 0x01, 0x03, 0x07, 0x0f};
  616.  
  617. int B_table[] = {8, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5,
  618.          5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6,
  619.          6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  620.          6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  621.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  622.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  623.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  624.          7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  625.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  626.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  627.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  628.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  629.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  630.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  631.          8, 8, 8, 8};
  632.  
  633. /* ----------------------------------------------------------- */
  634.  
  635. void unReduce(VOIDARG)
  636.  /* expand probablisticly reduced data */
  637. {
  638.         register int lchar;
  639.         int nchar;
  640.         int ExState;
  641.         int V;
  642.         int Len;
  643.  
  644.         factor = lrec.compression_method - 1;
  645.     ExState = 0;
  646.     lchar = 0;
  647.     LoadFollowers();
  648.  
  649.         while (((outpos+outcnt) < lrec.uncompressed_size) && (!zipeof)) {
  650.         if (Slen[lchar] == 0)
  651.                         READBIT(8,nchar,(int))      /* ; */
  652.                 else
  653.         {
  654.                         READBIT(1,nchar,(int));
  655.                         if (nchar != 0)
  656.                                 READBIT(8,nchar,(int))      /* ; */
  657.                         else
  658.             {
  659.                                 int follower;
  660.                                 int bitsneeded = B_table[Slen[lchar]];
  661.                                 READBIT(bitsneeded,follower,(int));
  662.                                 nchar = followers[lchar][follower];
  663.             }
  664.         }
  665.  
  666.         /* expand the resulting byte */
  667.         switch (ExState) {
  668.  
  669.         case 0:
  670.                         if (nchar != DLE)
  671.                                 OUTB((byte) nchar) /*;*/
  672.             else
  673.                 ExState = 1;
  674.             break;
  675.  
  676.         case 1:
  677.                         if (nchar != 0) {
  678.                                 V = nchar;
  679.                 Len = V & L_table[factor];
  680.                 if (Len == L_table[factor])
  681.                     ExState = 2;
  682.                 else
  683.                     ExState = 3;
  684.             }
  685.             else {
  686.                                 OUTB(DLE);
  687.                 ExState = 0;
  688.             }
  689.             break;
  690.  
  691.                 case 2: {
  692.                                 Len += nchar;
  693.                 ExState = 3;
  694.             }
  695.             break;
  696.  
  697.                 case 3: {
  698.                 register int i = Len + 3;
  699.                 int offset = (((V >> D_shift[factor]) &
  700.                                           D_mask[factor]) << 8) + nchar + 1;
  701.                                 longint op = (outpos+outcnt) - offset;
  702.  
  703.                 /* special case- before start of file */
  704.                 while ((op < 0L) && (i > 0)) {
  705.                     OUTB(0);
  706.                     op++;
  707.                     i--;
  708.                 }
  709.  
  710.                 /* normal copy of data from output buffer */
  711.                 {
  712.                     register int ix = (int) (op % OUTBUFSIZ);
  713.  
  714.                                         /* do a block memory copy if possible */
  715.                                         if ( ((ix    +i) < OUTBUFSIZ) &&
  716.                                              ((outcnt+i) < OUTBUFSIZ) ) {
  717.                                                 memcpy(outptr,&outbuf[ix],i);
  718.                                                 outptr += i;
  719.                                                 outcnt += i;
  720.                                         }
  721.  
  722.                                         /* otherwise copy byte by byte */
  723.                                         else while (i--) {
  724.                                                 OUTB(outbuf[ix]);
  725.                                                 if (++ix >= OUTBUFSIZ)
  726.                                                         ix = 0;
  727.                                         }
  728.                                 }
  729.  
  730.                 ExState = 0;
  731.             }
  732.             break;
  733.         }
  734.  
  735.                 /* store character for next iteration */
  736.                 lchar = nchar;
  737.         }
  738. }
  739.  
  740.  
  741. /* ------------------------------------------------------------- */
  742. /*
  743.  * Shrinking is a Dynamic Ziv-Lempel-Welch compression algorithm
  744.  * with partial clearing.
  745.  *
  746.  */
  747.  
  748. void partial_clear(VOIDARG)
  749. {
  750.         register int pr;
  751.         register int cd;
  752.  
  753.     /* mark all nodes as potentially unused */
  754.     for (cd = first_ent; cd < free_ent; cd++)
  755.         prefix_of[cd] |= 0x8000;
  756.  
  757.     /* unmark those that are used by other nodes */
  758.     for (cd = first_ent; cd < free_ent; cd++) {
  759.         pr = prefix_of[cd] & 0x7fff;    /* reference to another node? */
  760.                 if (pr >= first_ent)            /* flag node as referenced */
  761.             prefix_of[pr] &= 0x7fff;
  762.     }
  763.  
  764.     /* clear the ones that are still marked */
  765.     for (cd = first_ent; cd < free_ent; cd++)
  766.         if ((prefix_of[cd] & 0x8000) != 0)
  767.             prefix_of[cd] = -1;
  768.  
  769.     /* find first cleared node as next free_ent */
  770.         cd = first_ent;
  771.         while ((cd < maxcodemax) && (prefix_of[cd] != -1))
  772.                 cd++;
  773.         free_ent = cd;
  774. }
  775.  
  776.  
  777. /* ------------------------------------------------------------- */
  778.  
  779. void unShrink(VOIDARG)
  780. {
  781. #define  GetCode(dest) READBIT(codesize,dest,(int))
  782.  
  783.     register int code;
  784.     register int stackp;
  785.     int finchar;
  786.     int oldcode;
  787.     int incode;
  788.  
  789.  
  790.     /* decompress the file */
  791.     maxcodemax = 1 << max_bits;
  792.     codesize = init_bits;
  793.     maxcode = (1 << codesize) - 1;
  794.     free_ent = first_ent;
  795.     offset = 0;
  796.     sizex = 0;
  797.  
  798.     for (code = maxcodemax; code > 255; code--)
  799.         prefix_of[code] = -1;
  800.  
  801.     for (code = 255; code >= 0; code--) {
  802.         prefix_of[code] = 0;
  803.         suffix_of[code] = (byte) code;
  804.     }
  805.  
  806.     GetCode(oldcode);
  807.     if (zipeof)
  808.         return;
  809.     finchar = oldcode;
  810.  
  811.         OUTB((byte) finchar);
  812.  
  813.         stackp = hsize;
  814.  
  815.     while (!zipeof) {
  816.         GetCode(code);
  817.         if (zipeof)
  818.             return;
  819.  
  820.         while (code == clear) {
  821.             GetCode(code);
  822.             switch (code) {
  823.  
  824.             case 1:{
  825.                     codesize++;
  826.                     if (codesize == max_bits)
  827.                         maxcode = maxcodemax;
  828.                     else
  829.                         maxcode = (1 << codesize) - 1;
  830.                 }
  831.                 break;
  832.  
  833.             case 2:
  834.                 partial_clear();
  835.                 break;
  836.             }
  837.  
  838.             GetCode(code);
  839.             if (zipeof)
  840.                 return;
  841.         }
  842.  
  843.  
  844.         /* special case for KwKwK string */
  845.         incode = code;
  846.         if (prefix_of[code] == -1) {
  847.                         stack[--stackp] = (byte) finchar;
  848.             code = oldcode;
  849.         }
  850.  
  851.  
  852.         /* generate output characters in reverse order */
  853.         while (code >= first_ent) {
  854.                         stack[--stackp] = suffix_of[code];
  855.             code = prefix_of[code];
  856.         }
  857.  
  858.         finchar = suffix_of[code];
  859.                 stack[--stackp] = (byte) finchar;
  860.  
  861.  
  862.                 /* and put them out in forward order, block copy */
  863.                 if ((hsize-stackp+outcnt) < OUTBUFSIZ) {
  864.                         memcpy(outptr,&stack[stackp],hsize-stackp);
  865.                         outptr += hsize-stackp;
  866.                         outcnt += hsize-stackp;
  867.                         stackp = hsize;
  868.                 }
  869.  
  870.                 /* output byte by byte if we can't go by blocks */
  871.                 else while (stackp < hsize)
  872.                         OUTB(stack[stackp++]);
  873.  
  874.  
  875.         /* generate new entry */
  876.         code = free_ent;
  877.         if (code < maxcodemax) {
  878.             prefix_of[code] = oldcode;
  879.             suffix_of[code] = (byte) finchar;
  880.  
  881.             do
  882.                 code++;
  883.             while ((code < maxcodemax) && (prefix_of[code] != -1));
  884.  
  885.             free_ent = code;
  886.         }
  887.  
  888.         /* remember previous code */
  889.         oldcode = incode;
  890.     }
  891.  
  892. }
  893.  
  894.  
  895. /* ------------------------------------------------------------- */ 
  896. /*
  897.  * Imploding
  898.  * ---------
  899.  *
  900.  * The Imploding algorithm is actually a combination of two distinct
  901.  * algorithms.  The first algorithm compresses repeated byte sequences
  902.  * using a sliding dictionary.  The second algorithm is used to compress
  903.  * the encoding of the sliding dictionary ouput, using multiple
  904.  * Shannon-Fano trees.
  905.  *
  906.  */ 
  907.  
  908. #define maxSF 256
  909.  
  910.    typedef struct sf_entry { 
  911.                  word         Code; 
  912.                  byte         Value; 
  913.                  byte         BitLength; 
  914.               } sf_entry; 
  915.  
  916.    typedef struct sf_tree {   /* a shannon-fano tree */ 
  917.       sf_entry     entry[maxSF];
  918.       int          entries;
  919.       int          MaxLength;
  920.    } sf_tree; 
  921.  
  922.    typedef sf_tree      *sf_treep; 
  923.  
  924.    sf_tree      lit_tree; 
  925.    sf_tree      length_tree; 
  926.    sf_tree      distance_tree; 
  927.    boolean      lit_tree_present; 
  928.    boolean      eightK_dictionary; 
  929.    int          minimum_match_length;
  930.    int          dict_bits;
  931.  
  932.  
  933. #ifndef    OLDC
  934. void SortLengths(sf_tree *tree)
  935. #else
  936. void SortLengths(tree)
  937. sf_tree *tree;
  938. #endif    /* OLDC */
  939.   /* Sort the Bit Lengths in ascending order, while retaining the order
  940.     of the original lengths stored in the file */ 
  941.    int          x;
  942.    int          gap;
  943.    sf_entry     t; 
  944.    boolean      noswaps;
  945.    int          a, b;
  946.  
  947.    gap = tree->entries / 2; 
  948.  
  949.    do { 
  950.       do { 
  951.          noswaps = 1;
  952.          for (x = 0; x <= (tree->entries - 1) - gap; x++) 
  953.          { 
  954.             a = tree->entry[x].BitLength; 
  955.             b = tree->entry[x + gap].BitLength; 
  956.             if ((a > b) || ((a == b) && (tree->entry[x].Value > tree->entry[x + gap].Value))) 
  957.             { 
  958.                t = tree->entry[x]; 
  959.                tree->entry[x] = tree->entry[x + gap]; 
  960.                tree->entry[x + gap] = t; 
  961.                noswaps = 0;
  962.             } 
  963.          } 
  964.       }  while (!noswaps);
  965.  
  966.       gap = gap / 2; 
  967.    }  while (gap > 0);
  968.  
  969.  
  970. /* ----------------------------------------------------------- */ 
  971.  
  972. #ifndef    OLDC
  973. void ReadLengths(sf_tree *tree)
  974. #else
  975. void ReadLengths(tree)
  976. sf_tree *tree;
  977. #endif    /* OLDC */
  978.    int          treeBytes;
  979.    int          i;
  980.    int          num, len;
  981.  
  982.   /* get number of bytes in compressed tree */
  983.    READBIT(8,treeBytes,(int));
  984.    treeBytes++; 
  985.    i = 0; 
  986.  
  987.    tree->MaxLength = 0;
  988.  
  989.  /* High 4 bits: Number of values at this bit length + 1. (1 - 16)
  990.     Low  4 bits: Bit Length needed to represent value + 1. (1 - 16) */
  991.    while (treeBytes > 0)
  992.    {
  993.       READBIT(4,len,(int)); len++;
  994.       READBIT(4,num,(int)); num++;
  995.  
  996.       while (num > 0)
  997.       {
  998.          if (len > tree->MaxLength)
  999.             tree->MaxLength = len;
  1000.          tree->entry[i].BitLength = (byte) len;
  1001.          tree->entry[i].Value = (byte) i;
  1002.          i++;
  1003.          num--;
  1004.       }
  1005.  
  1006.       treeBytes--;
  1007.    } 
  1008.  
  1009.  
  1010. /* ----------------------------------------------------------- */ 
  1011.  
  1012. #ifndef    OLDC
  1013. void GenerateTrees(sf_tree *tree)
  1014. #else
  1015. void GenerateTrees(tree)
  1016. sf_tree *tree;
  1017. #endif    /* OLDC */
  1018.      /* Generate the Shannon-Fano trees */ 
  1019.    word         Code;
  1020.    int          CodeIncrement;
  1021.    int          LastBitLength;
  1022.    int          i;
  1023.  
  1024.  
  1025.    Code = 0;
  1026.    CodeIncrement = 0; 
  1027.    LastBitLength = 0; 
  1028.  
  1029.    i = tree->entries - 1;   /* either 255 or 63 */ 
  1030.    while (i >= 0) 
  1031.    { 
  1032.       Code += CodeIncrement; 
  1033.       if (tree->entry[i].BitLength != (byte) LastBitLength) 
  1034.       { 
  1035.          LastBitLength = tree->entry[i].BitLength; 
  1036.          CodeIncrement = 1 << (16 - LastBitLength); 
  1037.       } 
  1038.  
  1039.       tree->entry[i].Code = Code; 
  1040.       i--; 
  1041.    } 
  1042.  
  1043.  
  1044. /* ----------------------------------------------------------- */ 
  1045.  
  1046. #ifndef    OLDC
  1047. void ReverseBits(sf_tree *tree)
  1048. #else
  1049. void ReverseBits(tree)
  1050. sf_tree *tree;
  1051. #endif    /* OLDC */
  1052.  /* Reverse the order of all the bits in the above ShannonCode[]
  1053.     vector, so that the most significant bit becomes the least
  1054.     significant bit. For example, the value 0x1234 (hex) would become
  1055.     0x2C48 (hex). */ 
  1056.    int          i;
  1057.    word         mask;
  1058.    word         revb;
  1059.    word         v;
  1060.    word         o;
  1061.    int          b;
  1062.  
  1063.  
  1064.    for (i = 0; i <= tree->entries - 1; i++) 
  1065.    { 
  1066.         /* get original code */ 
  1067.       o = tree->entry[i].Code; 
  1068.  
  1069.         /* reverse each bit */ 
  1070.       mask = 0x0001;
  1071.       revb = 0x8000;
  1072.       v = 0;
  1073.       for (b = 0; b <= 15; b++) 
  1074.       { 
  1075.            /* if bit set in mask, then substitute reversed bit */ 
  1076.          if ((o & mask) != 0) 
  1077.             v = v | revb; 
  1078.  
  1079.            /* advance to next bit */ 
  1080.          revb = (revb >> 1);
  1081.          mask = (mask << 1);
  1082.       } 
  1083.  
  1084.         /* store reversed bits */ 
  1085.       tree->entry[i].Code = v; 
  1086.    } 
  1087.  
  1088.  
  1089. /* ----------------------------------------------------------- */ 
  1090.  
  1091. #ifndef    OLDC
  1092. void LoadTree(sf_tree *tree, int treesize)
  1093. #else
  1094. void LoadTree(tree, treesize)
  1095. sf_tree *tree;
  1096. int treesize;
  1097. #endif    /* OLDC */
  1098.      /* allocate and load a shannon-fano tree from the compressed file */ 
  1099.    tree->entries = treesize; 
  1100.    ReadLengths(tree); 
  1101.    SortLengths(tree); 
  1102.    GenerateTrees(tree); 
  1103.    ReverseBits(tree); 
  1104.  
  1105.  
  1106. /* ----------------------------------------------------------- */ 
  1107.  
  1108. #ifndef    OLDC
  1109. void LoadTrees(void)
  1110. #else
  1111. void LoadTrees()
  1112. #endif    /* OLDC */
  1113.    /* bit 1... */
  1114.    eightK_dictionary = (boolean) ((lrec.general_purpose_bit_flag & 0x02) != 0);
  1115.    /* bit 2... */
  1116.    lit_tree_present = (boolean) ((lrec.general_purpose_bit_flag & 0x04) != 0);
  1117.  
  1118.    if (eightK_dictionary) 
  1119.       dict_bits = 7;
  1120.    else 
  1121.       dict_bits = 6; 
  1122.  
  1123.    if (lit_tree_present) 
  1124.    { 
  1125.       minimum_match_length = 3; 
  1126.       LoadTree(&lit_tree,256); 
  1127.    } 
  1128.    else 
  1129.       minimum_match_length = 2; 
  1130.  
  1131.    LoadTree(&length_tree,64); 
  1132.    LoadTree(&distance_tree,64); 
  1133.  
  1134.  
  1135. /* ----------------------------------------------------------- */ 
  1136.  
  1137. #ifndef    OLDC
  1138. void ReadTree(sf_tree *tree, int *dest)
  1139. #else
  1140. void ReadTree(tree, dest)
  1141. sf_tree *tree;
  1142. int *dest;
  1143. #endif    /* OLDC */
  1144.      /* read next byte using a shannon-fano tree */ 
  1145.    int          bits = 0;
  1146.    word         cv = 0;
  1147.    int          cur = 0;
  1148.    int          b;
  1149.  
  1150.    *dest = -1;   /* in case of error */ 
  1151.  
  1152.    for (;;)
  1153.    { 
  1154.       READBIT(1,b,(int));
  1155.       cv = cv | (b << bits);
  1156.       bits++; 
  1157.  
  1158.       /* this is a very poor way of decoding shannon-fano.  two quicker
  1159.          methods come to mind:
  1160.             a) arrange the tree as a huffman-style binary tree with
  1161.                a "leaf" indicator at each node,
  1162.          and
  1163.             b) take advantage of the fact that s-f codes are at most 8
  1164.                bits long and alias unused codes for all bits following
  1165.                the "leaf" bit.
  1166.       */
  1167.  
  1168.       while (tree->entry[cur].BitLength < (byte) bits) 
  1169.       { 
  1170.          cur++; 
  1171.          if (cur >= tree->entries) 
  1172.             return; /* data error */
  1173.       } 
  1174.  
  1175.       while (tree->entry[cur].BitLength == (byte) bits) 
  1176.       { 
  1177.          if (tree->entry[cur].Code == cv) 
  1178.          { 
  1179.             *dest = tree->entry[cur].Value; 
  1180.             return; 
  1181.          } 
  1182.  
  1183.          cur++; 
  1184.          if (cur >= tree->entries) 
  1185.             return; /* data error */
  1186.       } 
  1187.    } 
  1188.  
  1189.  
  1190. /* ----------------------------------------------------------- */ 
  1191.  
  1192. #ifndef    OLDC
  1193. void unImplode(void)
  1194. #else
  1195. void unImplode()
  1196. #endif    /* OLDC */
  1197.      /* expand imploded data */ 
  1198.  
  1199.    int          lout;
  1200.    longint      op;
  1201.    int          Length;
  1202.    int          Distance;
  1203.  
  1204.    LoadTrees(); 
  1205.  
  1206.    while ((!zipeof) && ((outpos+outcnt) < lrec.uncompressed_size))
  1207.    { 
  1208.       READBIT(1,lout,(int));
  1209.  
  1210.       if (lout != 0)   /* encoded data is literal data */ 
  1211.       { 
  1212.          if (lit_tree_present)  /* use Literal Shannon-Fano tree */
  1213.             ReadTree(&lit_tree,&lout);
  1214.          else 
  1215.             READBIT(8,lout,(int));
  1216.  
  1217.          OUTB((byte) lout);
  1218.       } 
  1219.       else             /* encoded data is sliding dictionary match */
  1220.       {                
  1221.          READBIT(dict_bits,lout,(int));
  1222.          Distance = lout; 
  1223.  
  1224.          ReadTree(&distance_tree,&lout); 
  1225.          Distance |= (lout << dict_bits);
  1226.          /* using the Distance Shannon-Fano tree, read and decode the
  1227.             upper 6 bits of the Distance value */ 
  1228.  
  1229.          ReadTree(&length_tree,&Length); 
  1230.          /* using the Length Shannon-Fano tree, read and decode the
  1231.             Length value */
  1232.  
  1233.          Length += minimum_match_length; 
  1234.          if (Length == (63 + minimum_match_length)) 
  1235.          { 
  1236.             READBIT(8,lout,(int));
  1237.             Length += lout; 
  1238.          } 
  1239.  
  1240.         /* move backwards Distance+1 bytes in the output stream, and copy
  1241.           Length characters from this position to the output stream.
  1242.           (if this position is before the start of the output stream,
  1243.           then assume that all the data before the start of the output
  1244.           stream is filled with zeros) */ 
  1245.  
  1246.          op = (outpos+outcnt) - Distance - 1L;
  1247.  
  1248.           /* special case- before start of file */
  1249.           while ((op < 0L) && (Length > 0)) {
  1250.                   OUTB(0);
  1251.                   op++;
  1252.                   Length--;
  1253.           }
  1254.  
  1255.           /* normal copy of data from output buffer */
  1256.           {
  1257.                   register int ix = (int) (op % OUTBUFSIZ);
  1258.  
  1259.                   /* do a block memory copy if possible */
  1260.                   if ( ((ix    +Length) < OUTBUFSIZ) &&
  1261.                        ((outcnt+Length) < OUTBUFSIZ) ) {
  1262.                           memcpy(outptr,&outbuf[ix],Length);
  1263.                           outptr += Length;
  1264.                           outcnt += Length;
  1265.                   }
  1266.  
  1267.                   /* otherwise copy byte by byte */
  1268.                   else while (Length--) {
  1269.                           OUTB(outbuf[ix]);
  1270.                           if (++ix >= OUTBUFSIZ)
  1271.                                   ix = 0;
  1272.                   }
  1273.          }
  1274.       } 
  1275.    } 
  1276.  
  1277.  
  1278.  
  1279. /* ---------------------------------------------------------- */
  1280.  
  1281. void extract_member(VOIDARG)
  1282. {
  1283.         unsigned b;
  1284.  
  1285.     bits_left = 0;
  1286.     bitbuf = 0;
  1287.     incnt = 0;
  1288.     outpos = 0L;
  1289.     outcnt = 0;
  1290.     outptr = outbuf;
  1291.     zipeof = 0;
  1292.     crc32val = 0xFFFFFFFFL;
  1293.  
  1294.  
  1295.     /* create the output file with READ and WRITE permissions */
  1296.     if (create_output_file())
  1297.         exit(1);
  1298.  
  1299.         switch (lrec.compression_method) {
  1300.  
  1301.     case 0:        /* stored */
  1302.         {
  1303.             printf(" Extracting: %-12s ", filename);
  1304.             while (ReadByte(&b))
  1305.                 OUTB((byte) b);
  1306.         }
  1307.         break;
  1308.  
  1309.         case 1: {
  1310.             printf("UnShrinking: %-12s ", filename);
  1311.             unShrink();
  1312.         }
  1313.         break;
  1314.  
  1315.     case 2:
  1316.     case 3:
  1317.     case 4:
  1318.         case 5: {
  1319.             printf("  Expanding: %-12s ", filename);
  1320.             unReduce();
  1321.         }
  1322.         break;
  1323.  
  1324.         case 6: {
  1325.                         printf("  Exploding: %-12s ", filename);
  1326.                         unImplode();
  1327.         }
  1328.         break;
  1329.  
  1330.         default:
  1331.         printf("Unknown compression method.");
  1332.     }
  1333.  
  1334.  
  1335.     /* write the last partial buffer, if any */
  1336.     if (outcnt > 0) {
  1337.         UpdateCRC(outbuf, outcnt);
  1338.         write(outfd, outbuf, outcnt);
  1339.     }
  1340.  
  1341.     /* set output file date and time */
  1342.     set_file_time();
  1343.  
  1344.     close(outfd);
  1345.  
  1346.     crc32val = -1 - crc32val;
  1347.         if (crc32val != lrec.crc32)
  1348.                 printf(" Bad CRC %08lx  (should be %08lx)", lrec.crc32, crc32val);
  1349.  
  1350.     printf("\n");
  1351. }
  1352.  
  1353.  
  1354. /* ---------------------------------------------------------- */
  1355.  
  1356. #ifndef    OLDC
  1357. void get_string(int len, char *s)
  1358. #else
  1359. void get_string(len, s)
  1360. int len;
  1361. char *s;
  1362. #endif    /* OLDC */
  1363.  /* read a byte; return 8 if byte available, 0 if not */
  1364. {
  1365.     read(zipfd, s, len);
  1366.     s[len] = 0;
  1367. }
  1368.  
  1369.  
  1370. /* ---------------------------------------------------------- */
  1371.  
  1372. void process_local_file_header(VOIDARG)
  1373. {
  1374.     if ((long) &lrec.crc32 ==
  1375.             (long) &lrec.last_mod_file_date
  1376.             + sizeof(lrec.last_mod_file_date))
  1377.         read(zipfd, (char *) &lrec, sizeof(lrec));
  1378.     else {
  1379.         read(zipfd, (char *) &lrec, (unsigned)
  1380.             ((long) &lrec.last_mod_file_date
  1381.             + sizeof(lrec.last_mod_file_date)
  1382.             - (long) &lrec));
  1383.         read(zipfd, (char *) &lrec.crc32, (unsigned)
  1384.             ((long) &lrec.extra_field_length
  1385.             + sizeof(lrec.extra_field_length)
  1386.             - (long) &lrec.crc32));
  1387.     }
  1388.  
  1389. #ifdef HIGH_LOW
  1390.     swap_bytes(&lrec.version_needed_to_extract);
  1391.     swap_bytes(&lrec.general_purpose_bit_flag);
  1392.     swap_bytes(&lrec.compression_method);
  1393.     swap_bytes(&lrec.last_mod_file_time);
  1394.     swap_bytes(&lrec.last_mod_file_date);
  1395.     swap_lbytes(&lrec.crc32);
  1396.     swap_lbytes(&lrec.compressed_size);
  1397.     swap_lbytes(&lrec.uncompressed_size);
  1398.     swap_bytes(&lrec.filename_length);
  1399.     swap_bytes(&lrec.extra_field_length);
  1400. #endif    /* HIGH_LOW */
  1401.  
  1402.     get_string(lrec.filename_length, filename);
  1403.     get_string(lrec.extra_field_length, extra);
  1404. #ifdef    unix
  1405.     {
  1406.         char *cp;
  1407.         for (cp = filename; *cp; ++cp)
  1408.             if (isupper(*cp)) *cp = tolower(*cp);
  1409.     }
  1410. #endif    /* unix */
  1411.     extract_member();
  1412. }
  1413.  
  1414.  
  1415. /* ---------------------------------------------------------- */
  1416.  
  1417. void process_central_file_header(VOIDARG)
  1418. {
  1419.     central_directory_file_header rec;
  1420.     char filename[STRSIZ];
  1421.     char extra[STRSIZ];
  1422.     char comment[STRSIZ];
  1423.  
  1424.     if ((long) &rec.external_file_attributes ==
  1425.             (long) &rec.internal_file_attributes
  1426.             + sizeof(rec.internal_file_attributes))
  1427.         read(zipfd, (char *) &rec, sizeof(rec));
  1428.     else {
  1429.         read(zipfd, (char *) &rec, (unsigned)
  1430.             ((long) &rec.internal_file_attributes
  1431.             + sizeof(rec.internal_file_attributes)
  1432.             - (long) &rec));
  1433.         read(zipfd, (char *) &rec.external_file_attributes, (unsigned)
  1434.             ((long) &rec.relative_offset_local_header
  1435.             + sizeof(rec.relative_offset_local_header)
  1436.             - (long) &rec.external_file_attributes));
  1437.     }
  1438.  
  1439. #ifdef HIGH_LOW
  1440.     swap_bytes(&rec.version_made_by);
  1441.     swap_bytes(&rec.version_needed_to_extract);
  1442.     swap_bytes(&rec.general_purpose_bit_flag);
  1443.     swap_bytes(&rec.compression_method);
  1444.     swap_bytes(&rec.last_mod_file_time);
  1445.     swap_bytes(&rec.last_mod_file_date);
  1446.     swap_lbytes(&rec.crc32);
  1447.     swap_lbytes(&rec.compressed_size);
  1448.     swap_lbytes(&rec.uncompressed_size);
  1449.     swap_bytes(&rec.filename_length);
  1450.     swap_bytes(&rec.extra_field_length);
  1451.     swap_bytes(&rec.file_comment_length);
  1452.     swap_bytes(&rec.disk_number_start);
  1453.     swap_bytes(&rec.internal_file_attributes);
  1454.     swap_lbytes(&rec.external_file_attributes);
  1455.     swap_lbytes(&rec.relative_offset_local_header);
  1456. #endif    /* HIGH_LOW */
  1457.  
  1458.         get_string(rec.filename_length, filename);
  1459.     get_string(rec.extra_field_length, extra);
  1460.     get_string(rec.file_comment_length, comment);
  1461. #ifdef    unix
  1462.     {
  1463.         char *cp;
  1464.         for (cp = filename; *cp; ++cp)
  1465.             if (isupper(*cp)) *cp = tolower(*cp);
  1466.     }
  1467. #endif    /* unix */
  1468. }
  1469.  
  1470.  
  1471. /* ---------------------------------------------------------- */
  1472.  
  1473. void process_end_central_dir(VOIDARG)
  1474. {
  1475.     end_central_dir_record rec;
  1476.     char comment[STRSIZ];
  1477.  
  1478.     read(zipfd, (char *) &rec, sizeof(rec));
  1479.  
  1480. #ifdef HIGH_LOW
  1481.     swap_bytes(&rec.number_this_disk);
  1482. #ifndef    TURBOC
  1483.     swap_bytes(&rec.num_disk_with_start_cent_dir);
  1484.     swap_bytes(&rec.tot_ents_cent_dir_on_this_disk);
  1485. #else
  1486.     swap_bytes(&rec.number_disk_with_start_central_directory);
  1487.     swap_bytes(&rec.total_entries_central_dir_on_this_disk);
  1488. #endif    /* TURBOC */
  1489.     swap_bytes(&rec.total_entries_central_dir);
  1490.     swap_lbytes(&rec.size_central_directory);
  1491.     swap_lbytes(&rec.offset_start_central_directory);
  1492.     swap_bytes(&rec.zipfile_comment_length);
  1493. #endif    /* HIGH_LOW */
  1494.  
  1495.     get_string(rec.zipfile_comment_length, comment);
  1496. }
  1497.  
  1498.  
  1499. /* ---------------------------------------------------------- */
  1500.  
  1501. void process_headers(VOIDARG)
  1502. {
  1503.     longint sig;
  1504.  
  1505.     while (1) {
  1506.         if (read(zipfd, (char *) &sig, sizeof(sig)) != sizeof(sig))
  1507.             return;
  1508.  
  1509. #ifdef HIGH_LOW
  1510.         swap_lbytes(&sig);
  1511. #endif    /* HIGH_LOW */
  1512.  
  1513.                 if (sig == LOCAL_FILE_HEADER_SIGNATURE)
  1514.             process_local_file_header();
  1515.                 else if (sig == CENTRAL_FILE_HEADER_SIGNATURE)
  1516.             process_central_file_header();
  1517.                 else if (sig == END_CENTRAL_DIR_SIGNATURE) {
  1518.             process_end_central_dir();
  1519.             return;
  1520.         }
  1521.                 else {
  1522.             printf("Invalid Zipfile Header (0x%.8lx)\n", sig);
  1523.             return;
  1524.         }
  1525.     }
  1526.  
  1527. }
  1528.  
  1529.  
  1530. /* ---------------------------------------------------------- */
  1531.  
  1532. void extract_zipfile(VOIDARG)
  1533. {
  1534.     /*
  1535.      * open the zipfile for reading and in BINARY mode to prevent cr/lf
  1536.      * translation, which would corrupt the bitstreams 
  1537.      */
  1538.  
  1539.     if (open_input_file())
  1540.         exit(1);
  1541.  
  1542. #ifdef HIGH_LOW
  1543.     {
  1544.         word w_sig;
  1545.         longint li_sig;
  1546.         char *bp, *bp0 = (char *)&li_sig, *bp3 = ((char *)&li_sig)+3;
  1547.  
  1548.         if (read(zipfd, (char *) &w_sig, 2) == 2)
  1549.             if (w_sig == (LOCAL_FILE_HEADER_SIGNATURE & 0xffff)) {
  1550.                 w0 = 0;
  1551.                 w1 = 1;
  1552.             } else {
  1553.                 w0 = 1;
  1554.                 w1 = 0;
  1555.             }
  1556.         lseek(zipfd, 0L, SEEK_SET);
  1557.         if (read(zipfd, (char *) &li_sig, 4) == 4)
  1558.             if (li_sig == LOCAL_FILE_HEADER_SIGNATURE) {
  1559.                 li0 = 0;
  1560.                 li1 = 1;
  1561.                 li2 = 2;
  1562.                 li3 = 3;
  1563.             } else {
  1564.                 li0 = li1 = li2 = li3 = 0;
  1565.                 for (bp = bp0; bp < bp3; ++bp, ++li0)
  1566.                     if (*bp < 0x4b && !(*bp & 0x01))
  1567.                         break;
  1568.                 for (bp = bp0; bp < bp3; ++bp, ++li1)
  1569.                     if (*bp < 0x4b && (*bp & 0x01))
  1570.                         break;
  1571.                 for (bp = bp0; bp < bp3; ++bp, ++li2)
  1572.                     if (*bp == ((LOCAL_FILE_HEADER_SIGNATURE
  1573.                             >> 8) & 0xffL))
  1574.                         break;
  1575.                 for (bp = bp0; bp < bp3; ++bp, ++li3)
  1576.                     if (*bp == (LOCAL_FILE_HEADER_SIGNATURE
  1577.                             & 0xffL))
  1578.                         break;
  1579.             }
  1580.         lseek(zipfd, 0L, SEEK_SET);
  1581.     }
  1582. #endif    /* HIGH_LOW */
  1583.  
  1584.     process_headers();
  1585.  
  1586.     close(zipfd);
  1587. }
  1588.  
  1589.  
  1590. /* ---------------------------------------------------------- */
  1591. /*
  1592.  * main program
  1593.  *
  1594.  */
  1595.  
  1596. #ifndef    OLDC
  1597. void main(int argc, char **argv)
  1598. #else
  1599. void main(argc, argv)
  1600. int argc;
  1601. char **argv;
  1602. #endif    /* OLDC */
  1603.  /* read a byte; return 8 if byte available, 0 if not */
  1604. {
  1605.     if (argc != 2) {
  1606.                 printf("\n%s\nCourtesy of:  S.H.Smith  and  The Tool Shop BBS,  (602) 279-2673.\n\n",VERSION);
  1607.         printf("You may copy and distribute this program freely, provided that:\n");
  1608.         printf("    1)   No fee is charged for such copying and distribution, and\n");
  1609.         printf("    2)   It is distributed ONLY in its original, unmodified state.\n\n");
  1610.         printf("If you wish to distribute a modified version of this program, you MUST\n");
  1611.         printf("include the source code.\n\n");
  1612.         printf("If you modify this program, I would appreciate a copy of the  new source\n");
  1613.         printf("code.   I am holding the copyright on the source code, so please don't\n");
  1614.         printf("delete my name from the program files or from the documentation.\n\n");
  1615.                 printf("IN NO EVENT WILL I BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING ANY LOST\n");
  1616.                 printf("PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES\n");
  1617.                 printf("ARISING OUT OF YOUR USE OR INABILITY TO USE THE PROGRAM, OR FOR ANY\n");
  1618.                 printf("CLAIM BY ANY OTHER PARTY.\n\n");
  1619.                 printf("Usage:  UnZip FILE[.zip]\n");
  1620.                 exit(1);
  1621.     }
  1622.  
  1623.     /* .ZIP default if none provided by user */
  1624.     strcpy(zipfn, argv[1]);
  1625.     if (strchr(zipfn, '.') == NULL)
  1626.         strcat(zipfn, ".zip");
  1627.  
  1628.         /* allocate i/o buffers */
  1629.     inbuf = (byte *) (malloc(INBUFSIZ));
  1630.     outbuf = (byte *) (malloc(OUTBUFSIZ));
  1631.     if ((inbuf == NULL) || (outbuf == NULL)) {
  1632.         printf("Can't allocate buffers!\n");
  1633.         exit(1);
  1634.     }
  1635.  
  1636.         /* do the job... */
  1637.         extract_zipfile();
  1638.     exit(0);
  1639. }
  1640.  
  1641.