home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip51.zip / file_io.c < prev    next >
C/C++ Source or Header  |  1994-01-28  |  32KB  |  1,021 lines

  1. /*---------------------------------------------------------------------------
  2.  
  3.   file_io.c
  4.  
  5.   This file contains routines for doing direct but relatively generic input/
  6.   output, file-related sorts of things, plus some miscellaneous stuff.  Most
  7.   of the stuff has to do with opening, closing, reading and/or writing files.
  8.  
  9.   ---------------------------------------------------------------------------*/
  10.  
  11.  
  12. #define FILE_IO_C
  13. #include "unzip.h"
  14. #include "crypt.h"
  15. #include "tables.h"   /* definition/initialization of crc_32_tab[], ebcdic[] */
  16.  
  17. #ifdef USE_FWRITE  /* see GRR notes below about MS-DOS and 16-bit ints */
  18. #  define WriteError(buf,len,strm) \
  19.           ((ulg)fwrite((char *)(buf),1,(extent)(len),strm) != (ulg)(len))
  20. #else
  21. #  define WriteError(buf,len,strm) \
  22.           ((ulg)write(fileno(strm),(char *)(buf),(extent)(len)) != (ulg)(len))
  23. #endif
  24.  
  25. static int disk_error OF((void));
  26.  
  27.  
  28.  
  29.  
  30.  
  31. /******************************/
  32. /* Function open_input_file() */
  33. /******************************/
  34.  
  35. int open_input_file()    /* return 1 if open failed */
  36. {
  37.     /*
  38.      *  open the zipfile for reading and in BINARY mode to prevent cr/lf
  39.      *  translation, which would corrupt the bitstreams
  40.      */
  41.  
  42. #if defined(UNIX) || defined(TOPS20) || defined(ATARI_ST)
  43.     zipfd = open(zipfn, O_RDONLY);
  44. #else /* !(UNIX || TOPS20) */
  45. #ifdef VMS
  46.     zipfd = open(zipfn, O_RDONLY, 0, "ctx=stm");
  47. #else /* !VMS */
  48. #ifdef MACOS
  49.     zipfd = open(zipfn, 0);
  50. #else /* !MACOS */
  51.     zipfd = open(zipfn, O_RDONLY | O_BINARY);
  52. #endif /* ?MACOS */
  53. #endif /* ?VMS */
  54. #endif /* ?(UNIX || TOPS20) */
  55.     if (zipfd < 0) {
  56.         fprintf(stderr, "error:  can't open zipfile [ %s ]\n", zipfn);
  57.         return 1;
  58.     }
  59.     return 0;
  60.  
  61. } /* end function open_input_file() */
  62.  
  63.  
  64.  
  65.  
  66. #ifndef VMS                      /* for VMS use code in vms.c */
  67.  
  68. /***************************/
  69. /* Function open_outfile() */
  70. /***************************/
  71.  
  72. int open_outfile()         /* return 1 if fail */
  73. {
  74. #ifdef DOS_NT_OS2
  75.     if (stat(filename, &statbuf) == 0 && !(statbuf.st_mode & S_IWRITE))
  76.         chmod(filename, S_IREAD | S_IWRITE);
  77. #endif
  78. #ifdef UNIX
  79.     if (stat(filename, &statbuf) == 0 && unlink(filename) < 0) {
  80.         fprintf(stderr, "\nerror:  cannot delete old %s\n", filename);
  81.         return 1;
  82.     }
  83. #endif
  84. #ifdef TOPS20
  85.     char *tfilnam;
  86.  
  87.     if ((tfilnam = (char *)malloc(2*strlen(filename)+1)) == NULL)
  88.         return 1;
  89.     strcpy(tfilnam, filename);
  90.     upper(tfilnam);
  91.     enquote(tfilnam);
  92.     if ((outfile = fopen(tfilnam, FOPW)) == NULL) {
  93.         fprintf(stderr, "\nerror:  cannot create %s\n", tfilnam);
  94.         free(tfilnam);
  95.         return 1;
  96.     }
  97.     free(tfilnam);
  98. #else
  99. #ifdef MTS
  100.     if (aflag)
  101.         outfile = fopen(filename, FOPWT);
  102.     else
  103.         outfile = fopen(filename, FOPW);
  104.     if (outfile == NULL) {
  105.         fprintf(stderr, "\nerror:  cannot create %s\n", filename);
  106.         return 1;
  107.     }
  108. #else
  109.     if ((outfile = fopen(filename, FOPW)) == NULL) {
  110.         fprintf(stderr, "\nerror:  cannot create %s\n", filename);
  111.         return 1;
  112.     }
  113. #endif
  114. #endif
  115.  
  116. #if 0      /* this SUCKS!  on Ultrix, it must be writing a byte at a time... */
  117.     setbuf(outfile, (char *)NULL);   /* make output unbuffered */
  118. #endif
  119.  
  120. #ifdef USE_FWRITE
  121. #ifdef DOS_NT_OS2
  122.     /* 16-bit MSC: buffer size must be strictly LESS than 32K (WSIZE):  bogus */
  123.     setbuf(outfile, (char *)NULL);   /* make output unbuffered */
  124. #else /* !DOS_NT_OS2 */
  125. #ifdef _IOFBF  /* make output fully buffered (works just about like write()) */
  126.     setvbuf(outfile, (char *)slide, _IOFBF, WSIZE);
  127. #else
  128.     setbuf(outfile, (char *)slide);
  129. #endif
  130. #endif /* ?DOS_NT_OS2 */
  131. #endif /* USE_FWRITE */
  132.     return 0;
  133.  
  134. } /* end function open_outfile() */
  135.  
  136. #endif /* !VMS */
  137.  
  138.  
  139.  
  140.  
  141.  
  142. /**********************/
  143. /* Function readbuf() */
  144. /**********************/
  145.  
  146. int readbuf(buf, size)   /* return number of bytes read into buf */
  147.     char *buf;
  148.     register unsigned size;
  149. {
  150.     register int count;
  151.     int n;
  152.  
  153.     n = size;
  154.     while (size) {
  155.         if (incnt == 0) {
  156. #ifdef OLD_READBUF
  157.             if ((incnt = read(zipfd, (char *)inbuf, INBUFSIZ)) <= 0)
  158.                 return (int)(n-size);
  159. #else
  160.             if ((incnt = read(zipfd, (char *)inbuf, INBUFSIZ)) == 0)
  161.                 return (int)(n-size);
  162.             else if (incnt < 0) {
  163.                 fprintf(stderr, "error:  zipfile read error\n");
  164.                 return -1;  /* discarding some data, but better than lockup */
  165.             }
  166. #endif
  167.             /* buffer ALWAYS starts on a block boundary:  */
  168.             cur_zipfile_bufstart += INBUFSIZ;
  169.             inptr = inbuf;
  170.         }
  171.         count = MIN(size, (unsigned)incnt);
  172.         memcpy(buf, inptr, count);
  173.         buf += count;
  174.         inptr += count;
  175.         incnt -= count;
  176.         size -= count;
  177.     }
  178.     return n;
  179.  
  180. } /* end function readbuf() */
  181.  
  182.  
  183.  
  184.  
  185.  
  186. /***********************/
  187. /* Function readbyte() */
  188. /***********************/
  189.  
  190. int readbyte()   /* refill inbuf and return a byte if available, else EOF */
  191. {
  192.     if (mem_mode || (incnt = read(zipfd,(char *)inbuf,INBUFSIZ)) <= 0)
  193.         return EOF;
  194.     cur_zipfile_bufstart += INBUFSIZ;   /* always starts on a block boundary */
  195.     inptr = inbuf;
  196.  
  197. #ifdef CRYPT
  198.     if (pInfo->encrypted) {
  199.         uch *p;
  200.         int n;
  201.  
  202.         for (n = (long)incnt > csize + 1 ? (int)csize + 1 : incnt,
  203.              p = inptr;  n--;  p++)
  204.             zdecode(*p);
  205.     }
  206. #endif /* CRYPT */
  207.  
  208.     --incnt;
  209.     return *inptr++;
  210.  
  211. } /* end function readbyte() */
  212.  
  213.  
  214.  
  215.  
  216.  
  217. #ifndef VMS                 /* for VMS use code in vms.c */
  218.  
  219. /********************/
  220. /* Function flush() */
  221. /********************/
  222.  
  223. int flush(rawbuf, size, unshrink)   /* cflag => always 0; 50 if write error */
  224.     uch *rawbuf;
  225.     ulg size;
  226.     int unshrink;
  227. {
  228.     register ulg crcval = crc32val;
  229.     register ulg n = size;
  230.     register uch *p=rawbuf, *q;
  231.     uch *transbuf;
  232.     ulg transbufsiz;
  233.     static int didCRlast = FALSE;
  234.  
  235.  
  236. /*---------------------------------------------------------------------------
  237.     Compute the CRC first; if testing or if disk is full, that's it.
  238.   ---------------------------------------------------------------------------*/
  239.  
  240.     while (n--)
  241.         crcval = crc_32_tab[((uch)crcval ^ (*p++)) & 0xff] ^ (crcval >> 8);
  242.     crc32val = crcval;
  243.  
  244.     if (tflag || size == 0L)   /* testing or nothing to write:  all done */
  245.         return 0;
  246.  
  247.     if (disk_full)
  248.         return 50;            /* disk already full:  ignore rest of file */
  249.  
  250. /*---------------------------------------------------------------------------
  251.     Write the bytes rawbuf[0..size-1] to the output device, first converting
  252.     end-of-lines and ASCII/EBCDIC as needed.  If SMALL_MEM or MED_MEM are NOT
  253.     defined, outbuf is assumed to be at least as large as rawbuf and is not
  254.     necessarily checked for overflow.
  255.   ---------------------------------------------------------------------------*/
  256.  
  257.     if (!pInfo->textmode) {
  258.         /* GRR:  note that for standard MS-DOS compilers, size argument to
  259.          * fwrite() can never be more than 65534, so WriteError macro will
  260.          * have to be rewritten if size can ever be that large.  For now,
  261.          * never more than 32K.  Also note that write() returns an int, which
  262.          * doesn't necessarily limit size to 32767 bytes if write() is used
  263.          * on 16-bit systems but does make it more of a pain; hence it is not.
  264.          */
  265.         if (WriteError(rawbuf, size, outfile))  /* write raw binary data */
  266.             return cflag? 0 : disk_error();
  267.     } else {
  268.         if (unshrink) {
  269.             /* rawbuf = outbuf */
  270.             transbuf = outbuf2;
  271.             transbufsiz = TRANSBUFSIZ;
  272.         } else {
  273.             /* rawbuf = slide */
  274.             transbuf = outbuf;
  275.             transbufsiz = OUTBUFSIZ;
  276.             Trace((stderr, "\ntransbufsiz = OUTBUFSIZ = %u\n", OUTBUFSIZ));
  277.         }
  278.         if (newfile) {
  279.             didCRlast = FALSE;   /* no previous buffers written */
  280.             newfile = FALSE;
  281.         }
  282.         p = rawbuf;
  283.         if (*p == LF && didCRlast)
  284.             ++p;
  285.  
  286.     /*-----------------------------------------------------------------------
  287.         Algorithm:  CR/LF => native; lone CR => native; lone LF => native.
  288.         This routine is only for non-raw-VMS, non-raw-VM/CMS files (i.e.,
  289.         stream-oriented files, not record-oriented).
  290.       -----------------------------------------------------------------------*/
  291.  
  292.         for (didCRlast = FALSE, q = transbuf;  p < rawbuf+size;  ++p) {
  293.             if (*p == CR) {              /* lone CR or CR/LF: EOL either way */
  294.                 PutNativeEOL
  295.                 if (p == rawbuf+size-1)  /* last char in buffer */
  296.                     didCRlast = TRUE;
  297.                 else if (p[1] == LF)     /* get rid of accompanying LF */
  298.                     ++p;
  299.             } else if (*p == LF)         /* lone LF */
  300.                 PutNativeEOL
  301.             else
  302. #ifndef DOS_NT_OS2
  303.             if (*p != CTRLZ)             /* lose all ^Z's */
  304. #endif
  305.                 *q++ = native(*p);
  306.  
  307. #if (defined(SMALL_MEM) || defined(MED_MEM))
  308. # if (lenEOL == 1)   /* don't check unshrink:  both buffers small but equal */
  309.             if (!unshrink)
  310. # endif
  311.                 /* check for danger of buffer overflow and flush */
  312.                 if (q > transbuf+transbufsiz-lenEOL) {
  313.                     Trace((stderr,
  314.                       "p - rawbuf = %u   q-transbuf = %u   size = %lu\n",
  315.                       (unsigned)(p-rawbuf), (unsigned)(q-transbuf), size));
  316.                     if (WriteError(transbuf, (unsigned)(q-transbuf), outfile))
  317.                         return cflag? 0 : disk_error();
  318.                     q = transbuf;
  319.                     continue;
  320.                 }
  321. #endif /* SMALL_MEM || MED_MEM */
  322.         }
  323.  
  324.     /*-----------------------------------------------------------------------
  325.         Done translating:  write whatever we've got to file.
  326.       -----------------------------------------------------------------------*/
  327.  
  328.         Trace((stderr, "p - rawbuf = %u   q-transbuf = %u   size = %lu\n",
  329.           (unsigned)(p-rawbuf), (unsigned)(q-transbuf), size));
  330.         if (q > transbuf &&
  331.             WriteError(transbuf, (unsigned)(q-transbuf), outfile))
  332.             return cflag? 0 : disk_error();
  333.     }
  334.  
  335.     return 0;
  336.  
  337. } /* end function flush() */
  338.  
  339.  
  340.  
  341.  
  342.  
  343. /*************************/
  344. /* Function disk_error() */
  345. /*************************/
  346.  
  347. static int disk_error()
  348. {
  349.     fprintf(stderr, "\n%s:  write error (disk full?).  Continue? (y/n/^C) ",
  350.       filename);
  351.     FFLUSH(stderr);
  352.  
  353. #ifndef MSWIN
  354.     fgets(answerbuf, 9, stdin);
  355.     if (*answerbuf == 'y')   /* stop writing to this file */
  356.         disk_full = 1;       /*  (outfile bad?), but new OK */
  357.     else
  358. #endif
  359.         disk_full = 2;       /* no:  exit program */
  360.  
  361.     return 50;               /* 50:  disk full */
  362.  
  363. } /* end function disk_error() */
  364.  
  365. #endif /* !VMS */
  366.  
  367.  
  368.  
  369.  
  370.  
  371. /**********************/
  372. /* Function handler() */
  373. /**********************/
  374.  
  375. void handler(signal)   /* upon interrupt, turn on echo and exit cleanly */
  376.     int signal;
  377. {
  378. #if defined(SIGBUS) || defined(SIGSEGV)
  379.     static char *corrupt = "error:  zipfile probably corrupt (%s)\n";
  380. #endif
  381.  
  382. #if !defined(DOS_NT_OS2) && !defined(MACOS)
  383.     echon();
  384.     putc('\n', stderr);
  385. #endif /* !DOS_NT_OS2 && !MACOS */
  386. #ifdef SIGBUS
  387.     if (signal == SIGBUS) {
  388.         fprintf(stderr, corrupt, "bus error");
  389.         exit(3);
  390.     }
  391. #endif /* SIGBUS */
  392. #ifdef SIGSEGV
  393.     if (signal == SIGSEGV) {
  394.         fprintf(stderr, corrupt, "segmentation violation");
  395.         exit(3);
  396.     }
  397. #endif /* SIGSEGV */
  398.     exit(0);
  399. }
  400.  
  401.  
  402.  
  403.  
  404.  
  405. #ifndef VMS
  406.  
  407. /*******************************/
  408. /* Function dos_to_unix_time() */
  409. /*******************************/
  410.  
  411. time_t dos_to_unix_time(ddate, dtime)
  412.     unsigned ddate, dtime;
  413. {
  414.     int yr, mo, dy, hh, mm, ss;
  415. #ifdef TOPS20
  416. #   define YRBASE  1900
  417.     struct tmx *tmx;
  418.     char temp[20];
  419.     time_t retval;
  420. #else /* !TOPS20 */
  421. #   define YRBASE  1970
  422.     static short yday[]={0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  423.     int leap;
  424.     long m_time, days=0;
  425. #if (!defined(MACOS) && !defined(MSC))
  426. #if (defined(BSD) || defined(MTS) || defined(__GO32__))
  427. #ifndef __386BSD__
  428.     static struct timeb tbp;
  429. #endif /* __386BSD__ */
  430. #else /* !(BSD || MTS || __GO32__) */
  431. #ifdef ATARI_ST
  432.     extern long _timezone;
  433. #   define timezone _timezone;  /* a whoops in our library... */
  434. #else /* !ATARI_ST */
  435.     extern long timezone;       /* declared in <time.h> for MSC (& Borland?) */
  436. #endif /* ?ATARI_ST */
  437. #endif /* ?(BSD || MTS || __GO32__) */
  438. #endif /* !MACOS && !MSC */
  439. #endif /* ?TOPS20 */
  440.  
  441.  
  442.     /* dissect date */
  443.     yr = ((ddate >> 9) & 0x7f) + (1980 - YRBASE);
  444.     mo = ((ddate >> 5) & 0x0f) - 1;
  445.     dy = (ddate & 0x1f) - 1;
  446.  
  447.     /* dissect time */
  448.     hh = (dtime >> 11) & 0x1f;
  449.     mm = (dtime >> 5) & 0x3f;
  450.     ss = (dtime & 0x1f) * 2;
  451.  
  452. #ifdef TOPS20
  453.     tmx = (struct tmx *)malloc(sizeof(struct tmx));
  454.     sprintf (temp, "%02d/%02d/%02d %02d:%02d:%02d", mo+1, dy+1, yr, hh, mm, ss);
  455.     time_parse(temp, tmx, (char *)0);
  456.     retval = time_make(tmx);
  457.     free(tmx);
  458.     return retval;
  459.  
  460. #else /* !TOPS20 */
  461.     /* leap = # of leap years from BASE up to but not including current year */
  462.     leap = ((yr + YRBASE - 1) / 4);   /* leap year base factor */
  463.  
  464.     /* calculate days from BASE to this year and add expired days this year */
  465.     days = (yr * 365) + (leap - 492) + yday[mo];
  466.  
  467.     /* if year is a leap year and month is after February, add another day */
  468.     if ((mo > 1) && ((yr+YRBASE)%4 == 0) && ((yr+YRBASE) != 2100))
  469.         ++days;                 /* OK through 2199 */
  470.  
  471.     /* convert date & time to seconds relative to 00:00:00, 01/01/YRBASE */
  472.     m_time = ((long)(days + dy) * 86400L) + ((long)hh * 3600) + (mm * 60) + ss;
  473.       /* - 1;   MS-DOS times always rounded up to nearest even second */
  474.  
  475. #ifndef MACOS
  476. #if (defined(BSD) || defined(MTS) || defined(__GO32__))
  477. #if (!defined(__386BSD__) && !defined(__bsdi__))
  478.     ftime(&tbp);
  479.     m_time += tbp.timezone * 60L;
  480. #endif
  481. #else /* !(BSD || MTS || __GO32__) */
  482. #ifdef WIN32
  483.     {
  484.         TIME_ZONE_INFORMATION tzinfo;
  485.         DWORD res;
  486.  
  487.         /* account for timezone differences */
  488.         res = GetTimeZoneInformation(&tzinfo);
  489.         if (res == TIME_ZONE_ID_STANDARD)
  490.             m_time += 60*tzinfo.StandardBias;
  491.         else if (res == TIME_ZONE_ID_DAYLIGHT)
  492.             m_time += 60*tzinfo.DaylightBias;
  493.     }
  494. #else /* !WIN32 */
  495.     tzset();                    /* set `timezone' variable */
  496.     m_time += timezone;
  497. #endif /* ?WIN32 */
  498. #endif /* ?(BSD || MTS || __GO32__) */
  499. #endif /* !MACOS */
  500.  
  501. #ifdef __386BSD__               /* see comments in unix.c */
  502.     m_time -= localtime((time_t *) &m_time)->tm_gmtoff;
  503. #else /* !__386BSD__ */
  504. #ifndef WIN32
  505.     if (localtime((time_t *)&m_time)->tm_isdst)
  506.         m_time -= 60L * 60L;    /* adjust for daylight savings time */
  507. #endif /* !WIN32 */
  508. #endif /* ?__386BSD__ */
  509.  
  510.     return m_time;
  511. #endif /* ?TOPS20 */
  512.  
  513. } /* end function dos_to_unix_time() */
  514.  
  515. #endif /* !VMS */
  516.  
  517.  
  518.  
  519.  
  520.  
  521. #if !defined(VMS) && !defined(OS2)
  522.  
  523. /******************************/
  524. /* Function check_for_newer() */
  525. /******************************/
  526.  
  527. int check_for_newer(filename)   /* return 1 if existing file newer or equal; */
  528.     char *filename;             /*  0 if older; -1 if doesn't exist yet */
  529. {
  530.     time_t existing, archive;
  531.  
  532.     if (stat(filename, &statbuf))
  533.         return DOES_NOT_EXIST;
  534.  
  535.     /* round up existing filetime to nearest 2 seconds for comparison */
  536.     existing = (statbuf.st_mtime & 1) ? statbuf.st_mtime+1 : statbuf.st_mtime;
  537.     archive  = dos_to_unix_time(lrec.last_mod_file_date,
  538.                                 lrec.last_mod_file_time);
  539. #ifdef PRINT_TIME
  540.     fprintf(stderr, "existing %ld, archive %ld, e-a %ld\n", existing, archive,
  541.       existing-archive);
  542. #endif
  543.  
  544.     return (existing >= archive);
  545.  
  546. } /* end function check_for_newer() */
  547.  
  548. #endif /* !VMS && !OS2 */
  549.  
  550.  
  551.  
  552.  
  553.  
  554. /***********************************/
  555. /* Function find_end_central_dir() */
  556. /***********************************/
  557.  
  558. int find_end_central_dir(searchlen)   /* return PK-class error */
  559.     long searchlen;
  560. {
  561.     int i, numblks, found=FALSE;
  562.     LONGINT tail_len;
  563.     ec_byte_rec byterec;
  564.  
  565.  
  566. /*---------------------------------------------------------------------------
  567.     Treat case of short zipfile separately.
  568.   ---------------------------------------------------------------------------*/
  569.  
  570.     if (ziplen <= INBUFSIZ) {
  571.         lseek(zipfd, 0L, SEEK_SET);
  572.         if ((incnt = read(zipfd,(char *)inbuf,(unsigned int)ziplen)) ==
  573.              (int)ziplen)
  574.  
  575.             /* 'P' must be at least 22 bytes from end of zipfile */
  576.             for (inptr = inbuf+(int)ziplen-22;  inptr >= inbuf;  --inptr)
  577.                 if ((native(*inptr) == 'P')  &&
  578.                      !strncmp((char *)inptr, end_central_sig, 4)) {
  579.                     incnt -= inptr - inbuf;
  580.                     found = TRUE;
  581.                     break;
  582.                 }
  583.  
  584. /*---------------------------------------------------------------------------
  585.     Zipfile is longer than INBUFSIZ:  may need to loop.  Start with short
  586.     block at end of zipfile (if not TOO short).
  587.   ---------------------------------------------------------------------------*/
  588.  
  589.     } else {
  590.         if ((tail_len = ziplen % INBUFSIZ) > ECREC_SIZE) {
  591.             cur_zipfile_bufstart = lseek(zipfd, ziplen-tail_len, SEEK_SET);
  592.             if ((incnt = read(zipfd,(char *)inbuf,(unsigned int)tail_len)) !=
  593.                  (int)tail_len)
  594.                 goto fail;      /* shut up; it's expedient */
  595.  
  596.             /* 'P' must be at least 22 bytes from end of zipfile */
  597.             for (inptr = inbuf+(int)tail_len-22;  inptr >= inbuf;  --inptr)
  598.                 if ((native(*inptr) == 'P')  &&
  599.                      !strncmp((char *)inptr, end_central_sig, 4)) {
  600.                     incnt -= inptr - inbuf;
  601.                     found = TRUE;
  602.                     break;
  603.                 }
  604.             /* sig may span block boundary: */
  605.             strncpy((char *)hold, (char *)inbuf, 3);
  606.         } else
  607.             cur_zipfile_bufstart = ziplen - tail_len;
  608.  
  609.     /*-----------------------------------------------------------------------
  610.         Loop through blocks of zipfile data, starting at the end and going
  611.         toward the beginning.  In general, need not check whole zipfile for
  612.         signature, but may want to do so if testing.
  613.       -----------------------------------------------------------------------*/
  614.  
  615.         numblks = (int)((searchlen - tail_len + (INBUFSIZ-1)) / INBUFSIZ);
  616.         /*               ==amount=   ==done==   ==rounding==    =blksiz=  */
  617.  
  618.         for (i = 1;  !found && (i <= numblks);  ++i) {
  619.             cur_zipfile_bufstart -= INBUFSIZ;
  620.             lseek(zipfd, cur_zipfile_bufstart, SEEK_SET);
  621.             if ((incnt = read(zipfd,(char *)inbuf,INBUFSIZ)) != INBUFSIZ)
  622.                 break;          /* fall through and fail */
  623.  
  624.             for (inptr = inbuf+INBUFSIZ-1;  inptr >= inbuf;  --inptr)
  625.                 if ((native(*inptr) == 'P')  &&
  626.                      !strncmp((char *)inptr, end_central_sig, 4)) {
  627.                     incnt -= inptr - inbuf;
  628.                     found = TRUE;
  629.                     break;
  630.                 }
  631.             /* sig may span block boundary: */
  632.             strncpy((char *)hold, (char *)inbuf, 3);
  633.         }
  634.     } /* end if (ziplen > INBUFSIZ) */
  635.  
  636. /*---------------------------------------------------------------------------
  637.     Searched through whole region where signature should be without finding
  638.     it.  Print informational message and die a horrible death.
  639.   ---------------------------------------------------------------------------*/
  640.  
  641. fail:
  642.     if (!found) {
  643. #ifdef MSWIN
  644.         MessageBeep(1);
  645. #endif
  646.         if (qflag || (zipinfo_mode && !hflag))
  647.             fprintf(stderr, "[%s]\n", zipfn);
  648.         fprintf(stderr, "\
  649.   End-of-central-directory signature not found.  Either this file is not\n\
  650.   a zipfile, or it constitutes one disk of a multi-part archive.  In the\n\
  651.   latter case the central directory and zipfile comment will be found on\n\
  652.   the last disk(s) of this archive.\n\n");
  653.         return PK_ERR;   /* failed */
  654.     }
  655.  
  656. /*---------------------------------------------------------------------------
  657.     Found the signature, so get the end-central data before returning.  Do
  658.     any necessary machine-type conversions (byte ordering, structure padding
  659.     compensation) by reading data into character array and copying to struct.
  660.   ---------------------------------------------------------------------------*/
  661.  
  662.     real_ecrec_offset = cur_zipfile_bufstart + (inptr-inbuf);
  663. #ifdef TEST
  664.     printf("\n  found end-of-central-dir signature at offset %ld (%.8lXh)\n",
  665.       real_ecrec_offset, real_ecrec_offset);
  666.     printf("    from beginning of file; offset %d (%.4Xh) within block\n",
  667.       inptr-inbuf, inptr-inbuf);
  668. #endif
  669.  
  670.     if (readbuf((char *)byterec, ECREC_SIZE+4) <= 0)
  671.         return PK_EOF;
  672.  
  673.     ecrec.number_this_disk =
  674.         makeword(&byterec[NUMBER_THIS_DISK]);
  675.     ecrec.num_disk_with_start_central_dir =
  676.         makeword(&byterec[NUM_DISK_WITH_START_CENTRAL_DIR]);
  677.     ecrec.num_entries_centrl_dir_ths_disk =
  678.         makeword(&byterec[NUM_ENTRIES_CENTRL_DIR_THS_DISK]);
  679.     ecrec.total_entries_central_dir =
  680.         makeword(&byterec[TOTAL_ENTRIES_CENTRAL_DIR]);
  681.     ecrec.size_central_directory =
  682.         makelong(&byterec[SIZE_CENTRAL_DIRECTORY]);
  683.     ecrec.offset_start_central_directory =
  684.         makelong(&byterec[OFFSET_START_CENTRAL_DIRECTORY]);
  685.     ecrec.zipfile_comment_length =
  686.         makeword(&byterec[ZIPFILE_COMMENT_LENGTH]);
  687.  
  688.     expect_ecrec_offset = ecrec.offset_start_central_directory +
  689.                           ecrec.size_central_directory;
  690.     return PK_COOL;
  691.  
  692. } /* end function find_end_central_dir() */
  693.  
  694.  
  695.  
  696.  
  697.  
  698. /********************************/
  699. /* Function get_cdir_file_hdr() */
  700. /********************************/
  701.  
  702. int get_cdir_file_hdr()   /* return PK-type error code */
  703. {
  704.     cdir_byte_hdr byterec;
  705.  
  706.  
  707. /*---------------------------------------------------------------------------
  708.     Read the next central directory entry and do any necessary machine-type
  709.     conversions (byte ordering, structure padding compensation--do so by
  710.     copying the data from the array into which it was read (byterec) to the
  711.     usable struct (crec)).
  712.   ---------------------------------------------------------------------------*/
  713.  
  714.     if (readbuf((char *)byterec, CREC_SIZE) <= 0)
  715.         return PK_EOF;
  716.  
  717.     crec.version_made_by[0] = byterec[C_VERSION_MADE_BY_0];
  718.     crec.version_made_by[1] = byterec[C_VERSION_MADE_BY_1];
  719.     crec.version_needed_to_extract[0] = byterec[C_VERSION_NEEDED_TO_EXTRACT_0];
  720.     crec.version_needed_to_extract[1] = byterec[C_VERSION_NEEDED_TO_EXTRACT_1];
  721.  
  722.     crec.general_purpose_bit_flag =
  723.         makeword(&byterec[C_GENERAL_PURPOSE_BIT_FLAG]);
  724.     crec.compression_method =
  725.         makeword(&byterec[C_COMPRESSION_METHOD]);
  726.     crec.last_mod_file_time =
  727.         makeword(&byterec[C_LAST_MOD_FILE_TIME]);
  728.     crec.last_mod_file_date =
  729.         makeword(&byterec[C_LAST_MOD_FILE_DATE]);
  730.     crec.crc32 =
  731.         makelong(&byterec[C_CRC32]);
  732.     crec.csize =
  733.         makelong(&byterec[C_COMPRESSED_SIZE]);
  734.     crec.ucsize =
  735.         makelong(&byterec[C_UNCOMPRESSED_SIZE]);
  736.     crec.filename_length =
  737.         makeword(&byterec[C_FILENAME_LENGTH]);
  738.     crec.extra_field_length =
  739.         makeword(&byterec[C_EXTRA_FIELD_LENGTH]);
  740.     crec.file_comment_length =
  741.         makeword(&byterec[C_FILE_COMMENT_LENGTH]);
  742.     crec.disk_number_start =
  743.         makeword(&byterec[C_DISK_NUMBER_START]);
  744.     crec.internal_file_attributes =
  745.         makeword(&byterec[C_INTERNAL_FILE_ATTRIBUTES]);
  746.     crec.external_file_attributes =
  747.         makelong(&byterec[C_EXTERNAL_FILE_ATTRIBUTES]);  /* LONG, not word! */
  748.     crec.relative_offset_local_header =
  749.         makelong(&byterec[C_RELATIVE_OFFSET_LOCAL_HEADER]);
  750.  
  751.     return PK_COOL;
  752.  
  753. } /* end function get_cdir_file_hdr() */
  754.  
  755.  
  756.  
  757.  
  758.  
  759. /************************/
  760. /* Function do_string() */
  761. /************************/
  762.  
  763. int do_string(len, option)      /* return PK-type error code */
  764.     unsigned int len;           /* without prototype, ush converted to this */
  765.     int option;
  766. {
  767.     long comment_bytes_left, block_length;
  768.     int error=PK_OK;
  769.     ush extra_len;
  770.  
  771.  
  772. /*---------------------------------------------------------------------------
  773.     This function processes arbitrary-length (well, usually) strings.  Three
  774.     options are allowed:  SKIP, wherein the string is skipped (pretty logical,
  775.     eh?); DISPLAY, wherein the string is printed to standard output after un-
  776.     dergoing any necessary or unnecessary character conversions; and FILENAME,
  777.     wherein the string is put into the filename[] array after undergoing ap-
  778.     propriate conversions (including case-conversion, if that is indicated:
  779.     see the global variable pInfo->lcflag).  The latter option should be OK,
  780.     since filename is now dimensioned at 1025, but we check anyway.
  781.  
  782.     The string, by the way, is assumed to start at the current file-pointer
  783.     position; its length is given by len.  So start off by checking length
  784.     of string:  if zero, we're already done.
  785.   ---------------------------------------------------------------------------*/
  786.  
  787.     if (!len)
  788.         return PK_COOL;
  789.  
  790.     switch (option) {
  791.  
  792.     /*
  793.      * First case:  print string on standard output.  First set loop vari-
  794.      * ables, then loop through the comment in chunks of OUTBUFSIZ bytes,
  795.      * converting formats and printing as we go.  The second half of the
  796.      * loop conditional was added because the file might be truncated, in
  797.      * which case comment_bytes_left will remain at some non-zero value for
  798.      * all time.  outbuf is used as a scratch buffer because it is avail-
  799.      * able (we should be either before or in between any file processing).
  800.      * [The typecast in front of the MIN() macro was added because of the
  801.      * new promotion rules under ANSI C; readbuf() wants an int, but MIN()
  802.      * returns a signed long, if I understand things correctly.  The proto-
  803.      * type should handle it, but just in case...]
  804.      */
  805.  
  806.     case DISPLAY:
  807.         comment_bytes_left = len;
  808.         block_length = OUTBUFSIZ;    /* for the while statement, first time */
  809.         while (comment_bytes_left > 0 && block_length > 0) {
  810. #ifndef MSWIN
  811.             register uch *p = outbuf-1;
  812. #endif
  813.             if ((block_length = readbuf((char *)outbuf,
  814.                    (int) MIN(OUTBUFSIZ, comment_bytes_left))) <= 0)
  815.                 return PK_EOF;
  816.             comment_bytes_left -= block_length;
  817.             NUKE_CRs(outbuf, block_length);   /* (modifies block_length) */
  818.  
  819.             /*  this is why we allocated an extra byte for outbuf: */
  820.             outbuf[block_length] = '\0';   /* terminate w/zero:  ASCIIZ */
  821.  
  822.             A_TO_N(outbuf);   /* translate string to native */
  823.  
  824. #ifdef MSWIN
  825.             /* ran out of local mem -- had to cheat */
  826.             WriteStringToMsgWin(outbuf, bRealTimeMsgUpdate);
  827. #else /* !MSWIN */
  828. #ifdef NATIVE
  829.             printf("%s", outbuf);   /* GRR:  can ANSI be used with EBCDIC? */
  830. #else /* ASCII */
  831.             while (*++p)
  832.                 if (*p == 0x1B) {   /* ASCII escape char */
  833.                     putchar('^');
  834.                     putchar('[');
  835.                 } else
  836.                     putchar(*p);
  837. #endif /* ?NATIVE */
  838. #endif /* ?MSWIN */
  839.         }
  840.         printf("\n");   /* assume no newline at end */
  841.         break;
  842.  
  843.     /*
  844.      * Second case:  read string into filename[] array.  The filename should
  845.      * never ever be longer than FILNAMSIZ-1 (1024), but for now we'll check,
  846.      * just to be sure.
  847.      */
  848.  
  849.     case FILENAME:
  850.         extra_len = 0;
  851.         if (len >= FILNAMSIZ) {
  852.             fprintf(stderr, "warning:  filename too long--truncating.\n");
  853.             error = PK_WARN;
  854.             extra_len = len - FILNAMSIZ + 1;
  855.             len = FILNAMSIZ - 1;
  856.         }
  857.         if (readbuf(filename, len) <= 0)
  858.             return PK_EOF;
  859.         filename[len] = '\0';   /* terminate w/zero:  ASCIIZ */
  860.  
  861.         A_TO_N(filename);       /* translate string to native */
  862.  
  863.         if (pInfo->lcflag)      /* replace with lowercase filename */
  864.             TOLOWER(filename, filename);
  865.  
  866.         if (pInfo->vollabel && len > 8 && filename[8] == '.') {
  867.             char *p = filename+8;
  868.             while (*p++)
  869.                 p[-1] = *p;  /* disk label, and 8th char is dot:  remove dot */
  870.         }
  871.  
  872.         if (!extra_len)         /* we're done here */
  873.             break;
  874.  
  875.         /*
  876.          * We truncated the filename, so print what's left and then fall
  877.          * through to the SKIP routine.
  878.          */
  879.         fprintf(stderr, "[ %s ]\n", filename);
  880.         len = extra_len;
  881.         /*  FALL THROUGH...  */
  882.  
  883.     /*
  884.      * Third case:  skip string, adjusting readbuf's internal variables
  885.      * as necessary (and possibly skipping to and reading a new block of
  886.      * data).
  887.      */
  888.  
  889.     case SKIP:
  890.         LSEEK(cur_zipfile_bufstart + (inptr-inbuf) + len)
  891.         break;
  892.  
  893.     /*
  894.      * Fourth case:  assume we're at the start of an "extra field"; malloc
  895.      * storage for it and read data into the allocated space.
  896.      */
  897.  
  898.     case EXTRA_FIELD:
  899.         if (extra_field != (uch *)NULL)
  900.             free(extra_field);
  901.         if ((extra_field = (uch *)malloc(len)) == (uch *)NULL) {
  902.             fprintf(stderr,
  903.               "warning:  extra field too long (%d).  Ignoring...\n", len);
  904.             LSEEK(cur_zipfile_bufstart + (inptr-inbuf) + len)
  905.         } else
  906.             if (readbuf((char *)extra_field, len) <= 0)
  907.                 return PK_EOF;
  908.         break;
  909.  
  910.     } /* end switch (option) */
  911.     return error;
  912.  
  913. } /* end function do_string() */
  914.  
  915.  
  916.  
  917.  
  918.  
  919. /***********************/
  920. /* Function makeword() */
  921. /***********************/
  922.  
  923. ush makeword(b)
  924.     uch *b;
  925. {
  926.     /*
  927.      * Convert Intel style 'short' integer to non-Intel non-16-bit
  928.      * host format.  This routine also takes care of byte-ordering.
  929.      */
  930.     return (ush)((b[1] << 8) | b[0]);
  931. }
  932.  
  933.  
  934.  
  935.  
  936.  
  937. /***********************/
  938. /* Function makelong() */
  939. /***********************/
  940.  
  941. ulg makelong(sig)
  942.     uch *sig;
  943. {
  944.     /*
  945.      * Convert intel style 'long' variable to non-Intel non-16-bit
  946.      * host format.  This routine also takes care of byte-ordering.
  947.      */
  948.     return (((ulg)sig[3]) << 24)
  949.         + (((ulg)sig[2]) << 16)
  950.         + (((ulg)sig[1]) << 8)
  951.         + ((ulg)sig[0]);
  952. }
  953.  
  954.  
  955.  
  956.  
  957.  
  958. #ifdef ZMEM   /* memset, memcpy for systems without them */
  959.  
  960. /*********************/
  961. /* Function memset() */
  962. /*********************/
  963.  
  964. char *memset(buf, init, len)
  965.     register char *buf, init;   /* buffer loc and initializer */
  966.     register unsigned int len;  /* length of the buffer */
  967. {
  968.     char *start;
  969.  
  970.     start = buf;
  971.     while (len--)
  972.         *(buf++) = init;
  973.     return start;
  974. }
  975.  
  976.  
  977.  
  978.  
  979.  
  980. /*********************/
  981. /* Function memcpy() */
  982. /*********************/
  983.  
  984. char *memcpy(dst, src, len)
  985.     register char *dst, *src;
  986.     register unsigned int len;
  987. {
  988.     char *start;
  989.  
  990.     start = dst;
  991.     while (len-- > 0)
  992.         *dst++ = *src++;
  993.     return start;
  994. }
  995.  
  996. #endif /* ZMEM */
  997.  
  998.  
  999.  
  1000.  
  1001.  
  1002. /************************/
  1003. /* Function zstrnicmp() */
  1004. /************************/
  1005.  
  1006. int zstrnicmp(s1, s2, n)
  1007.     register char *s1, *s2;
  1008.     register int n;
  1009. {
  1010.     for (; n > 0;  --n, ++s1, ++s2) {
  1011.  
  1012.         if (ToLower(*s1) != ToLower(*s2))
  1013.             /* test includes early termination of one string */
  1014.             return (ToLower(*s1) < ToLower(*s2))? -1 : 1;
  1015.  
  1016.         if (*s1 == '\0')   /* both strings terminate early */
  1017.             return 0;
  1018.     }
  1019.     return 0;
  1020. }
  1021.