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