home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip532.zip / win32 / win32.c < prev   
C/C++ Source or Header  |  1997-10-21  |  68KB  |  1,961 lines

  1. /*---------------------------------------------------------------------------
  2.  
  3.   win32.c
  4.  
  5.   32-bit Windows-specific (NT/95) routines for use with Info-ZIP's UnZip 5.3
  6.   and later.
  7.  
  8.   Contains:  GetLoadPath()
  9.              Opendir()
  10.              Readdir()
  11.              Closedir()
  12.              process_defer_NT()   process any deferred items
  13.              SetSD()              set security descriptor on file
  14.              EvalExtraFields()    evaluate and process and extra field NOW
  15.              IsWinNT()            indicate type of WIN32 platform
  16.              test_NTSD()          test integrity of NT security data
  17.              utime2FileTime()
  18.              NTQueryTargetFS()
  19.              UTCtime2Localtime()
  20.              NTtzbugWorkaround()
  21.              getNTfiletime()
  22.              close_outfile()
  23.              stamp_file()
  24.              isfloppy()
  25.              IsVolumeOldFAT()
  26.              IsFileNameValid()
  27.              do_wild()
  28.              mapattr()
  29.              mapname()
  30.              map2fat()
  31.              checkdir()
  32.              version()
  33.              stat_bandaid()       [Watcom only]
  34.              getch()              [Watcom only]
  35.  
  36.   ---------------------------------------------------------------------------*/
  37.  
  38.  
  39. #define UNZIP_INTERNAL
  40. #include "unzip.h"
  41. #include <windows.h>   /* must be AFTER unzip.h to avoid struct G problems */
  42. #ifdef __RSXNT__
  43. #  include "win32/rsxntwin.h"
  44. #endif
  45. #include "win32/nt.h"
  46.  
  47.  
  48. #if (defined(__GO32__) || defined(__EMX__))
  49. #  include <dirent.h>        /* use readdir() */
  50. #  define MKDIR(path,mode)   mkdir(path,mode)
  51. #  define Opendir  opendir
  52. #  define Readdir  readdir
  53. #  define Closedir closedir
  54. #  define zdirent  dirent
  55. #  define zDIR     DIR
  56. #else /* !(__GO32__ || __EMX__) */
  57. #  define MKDIR(path,mode)   mkdir(path)
  58.  
  59.    typedef struct zdirent {
  60.        char    reserved [21];
  61.        char    ff_attrib;
  62.        short   ff_ftime;
  63.        short   ff_fdate;
  64.        long    size;
  65.        char    d_name[MAX_PATH];
  66.        int     d_first;
  67.        HANDLE  d_hFindFile;
  68.    } zDIR;
  69.  
  70.    static zDIR           *Opendir  (const char *n);
  71.    static struct zdirent *Readdir  (zDIR *d);
  72.    static void            Closedir (zDIR *d);
  73. #endif /* ?(__GO32__ || __EMX__) */
  74.  
  75.  
  76. /* Function prototypes */
  77. #ifdef NTSD_EAS
  78.    static int  SetSD(__GPRO__ char *path, PVOLUMECAPS VolumeCaps,
  79.                      uch *eb_ptr, unsigned eb_len);
  80.    static int  EvalExtraFields(__GPRO__ char *path, uch *ef_ptr,
  81.                                unsigned ef_len);
  82. #endif
  83.  
  84. #if (defined(USE_EF_UT_TIME) || defined(NT_TZBUG_WORKAROUND) || \
  85.      defined(TIMESTAMP))
  86.    static void utime2FileTime(time_t ut, FILETIME *pft);
  87.    static int NTQueryTargetFS(const char *path);
  88. #endif /* USE_EF_UT_TIME || NT_TZBUG_WORKAROUND || TIMESTAMP */
  89. #ifdef NT_TZBUG_WORKAROUND
  90.    static time_t UTCtime2Localtime(time_t utctime);
  91.    static void NTtzbugWorkaround(time_t ut, FILETIME *pft);
  92. #endif /* NT_TZBUG_WORKAROUND */
  93.  
  94. static int  getNTfiletime   (__GPRO__ FILETIME *pModFT, FILETIME *pAccFT,
  95.                              FILETIME *pCreFT);
  96. static int  isfloppy        (int nDrive);
  97. static int  IsVolumeOldFAT  (const char *name);
  98. static int  IsFileNameValid (const char *name);
  99. static void map2fat         (char *pathcomp, char **pEndFAT);
  100.  
  101.  
  102. /* static int created_dir;      */     /* used by mapname(), checkdir() */
  103. /* static int renamed_fullpath; */     /* ditto */
  104. /* static int fnlen;            */     /* ditto */
  105. /* static unsigned nLabelDrive; */     /* ditto */
  106.  
  107. extern char Far TruncNTSD[];    /* in extract.c */
  108.  
  109.  
  110.  
  111. #ifdef SFX
  112.  
  113. /**************************/
  114. /* Function GetLoadPath() */
  115. /**************************/
  116.  
  117. char *GetLoadPath(__GPRO)
  118. {
  119. #ifdef MSC
  120.     extern char *_pgmptr;
  121.     return _pgmptr;
  122.  
  123. #else    /* use generic API call */
  124.  
  125.     GetModuleFileName(NULL, G.filename, FILNAMSIZ-1);
  126.     _ISO_INTERN(G.filename);    /* translate to codepage of C rtl's stdio */
  127.     return G.filename;
  128. #endif
  129.  
  130. } /* end function GetLoadPath() */
  131.  
  132.  
  133.  
  134.  
  135.  
  136. #else /* !SFX */
  137.  
  138. #if (!defined(__GO32__) && !defined(__EMX__))
  139.  
  140. /**********************/        /* Borrowed from ZIP 2.0 sources            */
  141. /* Function Opendir() */        /* Difference: no special handling for      */
  142. /**********************/        /*             hidden or system files.      */
  143.  
  144. static zDIR *Opendir(n)
  145.     const char *n;          /* directory to open */
  146. {
  147.     zDIR *d;                /* malloc'd return value */
  148.     char *p;                /* malloc'd temporary string */
  149.     WIN32_FIND_DATA fd;
  150.     int len = strlen(n);
  151.  
  152.     /* Start searching for files in the MSDOS directory n */
  153.  
  154.     if ((d = (zDIR *)malloc(sizeof(zDIR))) == NULL ||
  155.         (p = malloc(strlen(n) + 5)) == NULL)
  156.     {
  157.         if (d != (zDIR *)NULL)
  158.             free((void *)d);
  159.         return (zDIR *)NULL;
  160.     }
  161.     INTERN_TO_ISO(n, p);
  162.     if (p[len-1] == ':')
  163.         p[len++] = '.';   /* x: => x:. */
  164.     else if (p[len-1] == '/' || p[len-1] == '\\')
  165.         --len;            /* foo/ => foo */
  166.     strcpy(p+len, "/*");
  167.  
  168.     if (INVALID_HANDLE_VALUE == (d->d_hFindFile = FindFirstFile(p, &fd))) {
  169.         free((zvoid *)d);
  170.         free((zvoid *)p);
  171.         return NULL;
  172.     }
  173.     strcpy(d->d_name, fd.cFileName);
  174.  
  175.     free((zvoid *)p);
  176.     d->d_first = 1;
  177.     return d;
  178.  
  179. } /* end of function Opendir() */
  180.  
  181.  
  182.  
  183.  
  184. /**********************/        /* Borrowed from ZIP 2.0 sources            */
  185. /* Function Readdir() */        /* Difference: no special handling for      */
  186. /**********************/        /*             hidden or system files.      */
  187.  
  188. static struct zdirent *Readdir(d)
  189.     zDIR *d;                    /* directory stream from which to read */
  190. {
  191.     /* Return pointer to first or next directory entry, or NULL if end. */
  192.  
  193.     if ( d->d_first )
  194.         d->d_first = 0;
  195.     else
  196.     {
  197.         WIN32_FIND_DATA fd;
  198.  
  199.         if ( !FindNextFile(d->d_hFindFile, &fd) )
  200.             return NULL;
  201.  
  202.         ISO_TO_INTERN(fd.cFileName, d->d_name);
  203.     }
  204.     return (struct zdirent *)d;
  205.  
  206. } /* end of function Readdir() */
  207.  
  208.  
  209.  
  210.  
  211. /***********************/
  212. /* Function Closedir() */       /* Borrowed from ZIP 2.0 sources */
  213. /***********************/
  214.  
  215. static void Closedir(d)
  216.     zDIR *d;                    /* directory stream to close */
  217. {
  218.     FindClose(d->d_hFindFile);
  219.     free(d);
  220. }
  221.  
  222. #endif /* !__GO32__ && !__EMX__ */
  223. #endif /* ?SFX */
  224.  
  225.  
  226.  
  227.  
  228. #ifdef NTSD_EAS
  229.  
  230. /*********************************/
  231. /*  Function process_defer_NT()  */
  232. /*********************************/
  233.  
  234. void process_defer_NT(__G)
  235.     __GDEF
  236. {
  237.     /* process deferred items */
  238.  
  239.     unsigned long dir, bytes;
  240.     unsigned long dirfail, bytesfail;
  241.  
  242. #ifndef NO_NTSD_WITH_RSXNT
  243.     ProcessDefer(&dir, &bytes, &dirfail, &bytesfail);
  244. #else
  245.     dir = bytes = dirfail = bytesfail = 0L;
  246. #endif
  247.  
  248.     if (!G.tflag && (G.qflag < 2)) {
  249.         if (dir)
  250.             Info(slide, 0, ((char *)slide,
  251.               "    updated: %lu directory entries with %lu bytes security",
  252.               dir, bytes));
  253.         if (dirfail)
  254.             Info(slide, 0, ((char *)slide,
  255.               "     failed: %lu directory entries with %lu bytes security",
  256.               dirfail, bytesfail));
  257.     }
  258. }
  259.  
  260.  
  261.  
  262. /**********************/
  263. /*  Function SetSD()  */   /* return almost-PK errors */
  264. /**********************/
  265.  
  266. static int SetSD(__G__ path, VolumeCaps, eb_ptr, eb_len)
  267.     __GDEF
  268.     char *path;
  269.     PVOLUMECAPS VolumeCaps;
  270.     uch *eb_ptr;
  271.     unsigned eb_len;
  272. {
  273.     ulg ntsd_ucSize;
  274.     uch *security_data;
  275.     int error;
  276.  
  277.     if (eb_ptr == NULL || eb_len < EB_NTSD_L_LEN)
  278.         return PK_OK;  /* not a valid NTSD extra field:  assume OK */
  279.  
  280.     /* check if we know how to handle this version */
  281.     if (*(eb_ptr + (EB_HEADSIZE+EB_NTSD_VERSION)) > (uch)EB_NTSD_MAX_VER)
  282.         return PK_OK;
  283.  
  284.     ntsd_ucSize = makelong(eb_ptr + (EB_HEADSIZE+EB_UCSIZE_P));
  285.     if (ntsd_ucSize > 0L && eb_len <= (EB_NTSD_L_LEN + EB_CMPRHEADLEN))
  286.         return IZ_EF_TRUNC;               /* no compressed data! */
  287.  
  288.     /* allocate storage for uncompressed data */
  289.     security_data = (uch *)malloc((extent)ntsd_ucSize);
  290.     if (security_data == (uch *)NULL)
  291.         return PK_MEM4;
  292.  
  293.     error = memextract(__G__ security_data, ntsd_ucSize,
  294.       (eb_ptr + (EB_HEADSIZE+EB_NTSD_L_LEN)), (ulg)(eb_len - EB_NTSD_L_LEN));
  295.  
  296.     if (error == PK_OK) {
  297. #ifdef NO_NTSD_WITH_RSXNT
  298.         Info(slide, 0, ((char *)slide,
  299.           "%s port does not yet support setting security", "RSXNT"));
  300.         /* error = PK_OK; */  /* GRR:  change to PK_WARN? */
  301. #else /* !NO_NTSD_WITH_RSXNT */
  302.         if (SecuritySet(path, VolumeCaps, security_data)) {
  303.             error = PK_COOL;
  304.             if (!G.tflag && (G.qflag < 2) &&
  305.                 (!(VolumeCaps->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
  306.                 Info(slide, 0, ((char *)slide, " (%ld bytes security)",
  307.                   ntsd_ucSize));
  308.         }
  309. #endif /* ?NO_NTSD_WITH_RSXNT */
  310.     }
  311.  
  312.     free(security_data);
  313.     return error;
  314. }
  315.  
  316.  
  317.  
  318.  
  319. /********************************/   /* scan extra fields for something */
  320. /*  Function EvalExtraFields()  */   /*  we happen to know */
  321. /********************************/
  322.  
  323. static int EvalExtraFields(__G__ path, ef_ptr, ef_len)
  324.     __GDEF
  325.     char *path;
  326.     uch *ef_ptr;
  327.     unsigned ef_len;
  328. {
  329.     int rc = PK_OK;
  330.  
  331.     if (!G.X_flag)
  332.         return PK_OK;  /* user said don't process ACLs; for now, no other
  333.                           extra block types are handled here */
  334.  
  335.     while (ef_len >= EB_HEADSIZE)
  336.     {
  337.         unsigned eb_id = makeword(EB_ID + ef_ptr);
  338.         unsigned eb_len = makeword(EB_LEN + ef_ptr);
  339.  
  340.         if (eb_len > (ef_len - EB_HEADSIZE)) {
  341.             /* discovered some extra field inconsistency! */
  342.             Trace((stderr,
  343.               "EvalExtraFields: block length %u > rest ef_size %u\n", eb_len,
  344.               ef_len - EB_HEADSIZE));
  345.             break;
  346.         }
  347.  
  348.         switch (eb_id)
  349.         {
  350.             /* process security descriptor extra data if:
  351.                  Caller is WinNT AND
  352.                  Target local/remote drive supports acls AND
  353.                  Target file is not a directory (else we defer processing
  354.                    until later)
  355.              */
  356.             case EF_NTSD:
  357.                 if (IsWinNT()) {
  358.                     VOLUMECAPS VolumeCaps;
  359.  
  360.                     /* provide useful input */
  361.                     VolumeCaps.dwFileAttributes = G.pInfo->file_attr;
  362.                     VolumeCaps.bUsePrivileges = (G.X_flag > 1);
  363.  
  364. #ifndef NO_NTSD_WITH_RSXNT
  365.                     /* check target volume capabilities - just fall through
  366.                      * and try if fail */
  367.                     if (GetVolumeCaps(G.rootpath, path, &VolumeCaps) &&
  368.                         !(VolumeCaps.dwFileSystemFlags & FS_PERSISTENT_ACLS))
  369.                     {
  370.                         rc = PK_OK;
  371.                         break;
  372.                     }
  373. #endif
  374.                     rc = SetSD(__G__ path, &VolumeCaps, ef_ptr, eb_len);
  375.                 } else
  376.                     rc = PK_OK;
  377.                 break;
  378.  
  379. #if 0
  380.             /* perhaps later we can add support for unzipping OS/2 EAs to NT */
  381.             case EF_OS2:
  382.                 rc = SetEAs(__G__ path, ef_ptr);
  383.                 break;
  384.  
  385.             case EF_IZUNIX:
  386.             case EF_IZUNIX2:
  387.             case EF_TIME:
  388.                 break;          /* handled elsewhere */
  389. #else /* ! 0 */
  390. #ifdef DEBUG
  391.             case EF_AV:
  392.             case EF_OS2:
  393.             case EF_PKVMS:
  394.             case EF_PKUNIX:
  395.             case EF_IZVMS:
  396.             case EF_IZUNIX:
  397.             case EF_IZUNIX2:
  398.             case EF_TIME:
  399.             case EF_JLMAC:
  400.             case EF_ZIPIT:
  401.             case EF_VMCMS:
  402.             case EF_MVS:
  403.             case EF_ACL:
  404.             case EF_BEOS:
  405.             case EF_QDOS:
  406.             case EF_AOSVS:
  407.             case EF_SPARK:
  408.             case EF_MD5:
  409.             case EF_ASIUNIX:
  410.                 break;          /* shut up for other known e.f. blocks  */
  411. #endif /* DEBUG */
  412. #endif /* ? 0 */
  413.  
  414.             default:
  415.                 Trace((stderr,
  416.                   "EvalExtraFields: unknown extra field block, ID=%u\n",
  417.                   eb_id));
  418.                 break;
  419.         }
  420.  
  421.         ef_ptr += (eb_len + EB_HEADSIZE);
  422.         ef_len -= (eb_len + EB_HEADSIZE);
  423.  
  424.         if (rc != PK_OK)
  425.             break;
  426.     }
  427.  
  428.     return rc;
  429. }
  430.  
  431.  
  432.  
  433.  
  434. #ifndef SFX
  435.  
  436. /**************************/
  437. /*  Function test_NTSD()  */   /*  returns PK_WARN when NTSD data is invalid */
  438. /**************************/
  439.  
  440. int test_NTSD(__G__ eb, eb_size, eb_ucptr, eb_ucsize)
  441.     __GDEF
  442.     uch *eb;
  443.     unsigned eb_size;
  444.     uch *eb_ucptr;
  445.     ulg eb_ucsize;
  446. {
  447.     int r = PK_OK;
  448.  
  449. #ifndef NO_NTSD_WITH_RSXNT
  450.     if (!ValidateSecurity(eb_ucptr))
  451.         r = PK_WARN;
  452. #endif
  453.     return r;
  454.  
  455. } /* end function test_NTSD() */
  456.  
  457. #endif /* !SFX */
  458. #endif /* NTSD_EAS */
  459.  
  460.  
  461.  
  462.  
  463. /**********************/
  464. /* Function IsWinNT() */
  465. /**********************/
  466.  
  467. int IsWinNT(void)       /* returns TRUE if real NT, FALSE if Win95 or Win32s */
  468. {
  469.     static DWORD g_PlatformId = 0xFFFFFFFF; /* saved platform indicator */
  470.  
  471.     if (g_PlatformId == 0xFFFFFFFF) {
  472.         /* note: GetVersionEx() doesn't exist on WinNT 3.1 */
  473.         if (GetVersion() < 0x80000000)
  474.             g_PlatformId = TRUE;
  475.         else
  476.             g_PlatformId = FALSE;
  477.     }
  478.     return (int)g_PlatformId;
  479. }
  480.  
  481.  
  482.  
  483.  
  484. #if (defined(USE_EF_UT_TIME) || defined(NT_TZBUG_WORKAROUND) || \
  485.      defined(TIMESTAMP))
  486.  
  487. /*****************************/
  488. /* Function utime2FileTime() */     /* convert Unix time_t format into the */
  489. /*****************************/     /* form used by SetFileTime() in NT/95 */
  490.  
  491. #define UNIX_TIME_ZERO_HI  0x019DB1DE
  492. #define UNIX_TIME_ZERO_LO  0xD53E8000
  493. #define NT_QUANTA_PER_UNIX 10000000
  494.  
  495. static void utime2FileTime(time_t ut, FILETIME *pft)
  496. {
  497. #if defined(__GNUC__) || defined(ULONG_LONG_MAX)
  498.     unsigned long long NTtime;
  499.  
  500.     NTtime = ((unsigned long long)ut * NT_QUANTA_PER_UNIX) +
  501.              ((unsigned long long)UNIX_TIME_ZERO_LO +
  502.               ((unsigned long long)UNIX_TIME_ZERO_HI << 32));
  503.     pft->dwLowDateTime = (DWORD)NTtime;
  504.     pft->dwHighDateTime = (DWORD)(NTtime >> 32);
  505.  
  506. #else /* "unsigned long long" may not be supported */
  507.     unsigned int b1, b2, carry = 0;
  508.     unsigned long r0, r1, r2, r3, r4;
  509.  
  510.     b1 = ut & 0xFFFF;
  511.     b2 = (ut >> 16) & 0xFFFF;       /* if ut is over 32 bits, too bad */
  512.     r1 = b1 * (NT_QUANTA_PER_UNIX & 0xFFFF);
  513.     r2 = b1 * (NT_QUANTA_PER_UNIX >> 16);
  514.     r3 = b2 * (NT_QUANTA_PER_UNIX & 0xFFFF);
  515.     r4 = b2 * (NT_QUANTA_PER_UNIX >> 16);
  516.     r0 = (r1 + (r2 << 16)) & 0xFFFFFFFF;
  517.     if (r0 < r1)
  518.         carry++;
  519.     r1 = r0;
  520.     r0 = (r0 + (r3 << 16)) & 0xFFFFFFFF;
  521.     if (r0 < r1)
  522.         carry++;
  523.     pft->dwLowDateTime = r0 + UNIX_TIME_ZERO_LO;
  524.     if (pft->dwLowDateTime < r0)
  525.         carry++;
  526.     pft->dwHighDateTime = r4 + (r2 >> 16) + (r3 >> 16)
  527.                             + UNIX_TIME_ZERO_HI + carry;
  528. #endif /* ?(64-bit "unsigned long long" support) */
  529.  
  530. } /* end function utime2FileTime() */
  531.  
  532.  
  533.  
  534. /******************************/
  535. /* Function NTQueryTargetFS() */
  536. /******************************/
  537.  
  538. static int NTQueryTargetFS(const char *path)
  539. {
  540.     char     *tmp0;
  541.     char      rootPathName[4];
  542.     char      tmp1[MAX_PATH], tmp2[MAX_PATH];
  543.     unsigned  volSerNo, maxCompLen, fileSysFlags;
  544. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  545.     char *ansi_path = (char *)alloca(strlen(path) + 1);
  546.  
  547.     INTERN_TO_ISO(path, ansi_path);
  548.     path = ansi_path;
  549. #endif
  550.  
  551.     if (isalpha(path[0]) && (path[1] == ':'))
  552.         tmp0 = (char *)path;
  553.     else
  554.     {
  555.         GetFullPathName(path, MAX_PATH, tmp1, &tmp0);
  556.         tmp0 = &tmp1[0];
  557.     }
  558.     strncpy(rootPathName, tmp0, 3);   /* Build the root path name, */
  559.     rootPathName[3] = '\0';           /* e.g. "A:/"                */
  560.  
  561.     GetVolumeInformation((LPCTSTR)rootPathName, (LPTSTR)tmp1, (DWORD)MAX_PATH,
  562.                          (LPDWORD)&volSerNo, (LPDWORD)&maxCompLen,
  563.                          (LPDWORD)&fileSysFlags, (LPTSTR)tmp2, (DWORD)MAX_PATH);
  564.  
  565.     /* Volumes in (V)FAT and (OS/2) HPFS format store file timestamps in
  566.      * local time!
  567.      */
  568.     return !strncmp(strupr(tmp2), "FAT", 3) ||
  569.            !strncmp(tmp2, "VFAT", 4) ||
  570.            !strncmp(tmp2, "HPFS", 4);
  571.  
  572. } /* end function NTQueryTargetFS() */
  573.  
  574. #endif /* USE_EF_UT_TIME || NT_TZBUG_WORKAROUND || TIMESTAMP */
  575.  
  576.  
  577.  
  578. #ifndef NT_TZBUG_WORKAROUND
  579. #  define UTIME_BOUNDCHECK_1(utimval) \
  580.      if (fs_uses_loctime) { \
  581.          utime_dosmin = dos_to_unix_time((unsigned)DOSDATE_MINIMUM, 0); \
  582.          if ((ulg)utimval < (ulg)utime_dosmin) \
  583.              utimval = utime_dosmin; \
  584.      }
  585. #  define UTIME_BOUNDCHECK_N(utimval) \
  586.      if (fs_uses_loctime && ((ulg)utimval < (ulg)utime_dosmin)) \
  587.          utimval = utime_dosmin;
  588. #  define NT_TZBUG_PRECOMPENSATE(ut, pft)
  589.  
  590. #else /* !NT_TZBUG_WORKAROUND */
  591. #  define UTIME_1980_JAN_01_00_00   315532800L
  592. #  define UTIME_BOUNDCHECK_1(utimval)
  593. #  define UTIME_BOUNDCHECK_N(utimval)
  594. #  define NT_TZBUG_PRECOMPENSATE(ut, pft) \
  595.      if (fs_uses_loctime) NTtzbugWorkaround(ut, pft);
  596.  
  597.    /* nonzero if `y' is a leap year, else zero */
  598. #  define leap(y) (((y)%4 == 0 && (y)%100 != 0) || (y)%400 == 0)
  599.    /* number of leap years from 1970 to `y' (not including `y' itself) */
  600. #  define nleap(y) (((y)-1969)/4 - ((y)-1901)/100 + ((y)-1601)/400)
  601.  
  602. extern ZCONST ush ydays[];
  603.  
  604. /********************************/
  605. /* Function UTCtime2Localtime() */   /* borrowed from Zip's mkgmtime() */
  606. /********************************/
  607.  
  608. static time_t UTCtime2Localtime(time_t utctime)
  609. {
  610.     time_t utc = utctime;
  611.     struct tm *tm;
  612.     unsigned years, months, days, hours, minutes, seconds;
  613.  
  614.  
  615. #ifdef __BORLANDC__   /* Borland C++ 5.x crashes when trying to reference tm */
  616.     if (utc < UTIME_1980_JAN_01_00_00)
  617.         utc = UTIME_1980_JAN_01_00_00;
  618. #endif
  619.     tm = localtime(&utc);
  620.  
  621.     years = tm->tm_year + 1900; /* year - 1900 -> year */
  622.     months = tm->tm_mon;        /* 0..11 */
  623.     days = tm->tm_mday - 1;     /* 1..31 -> 0..30 */
  624.     hours = tm->tm_hour;        /* 0..23 */
  625.     minutes = tm->tm_min;       /* 0..59 */
  626.     seconds = tm->tm_sec;       /* 0..61 in ANSI C */
  627.  
  628.     /* set `days' to the number of days into the year */
  629.     days += ydays[months] + (months > 1 && leap(years));
  630.  
  631.     /* now set `days' to the number of days since 1 Jan 1970 */
  632.     days += 365 * (years - 1970) + nleap(years);
  633.  
  634.     return (time_t)(86400L * (ulg)days + 3600L * (ulg)hours +
  635.                     (ulg)(60 * minutes + seconds));
  636.  
  637. } /* end function UTCtime2Localtime() */
  638.  
  639.  
  640.  
  641. /********************************/
  642. /* Function NTtzbugWorkaround() */
  643. /********************************/
  644.  
  645. static void NTtzbugWorkaround(time_t ut, FILETIME *pft)
  646. {
  647.     FILETIME C_RTL_locft, NTAPI_locft;
  648.     time_t ux_loctime = UTCtime2Localtime(ut);
  649.  
  650.     /* This routine is only used when the target file system stores time-
  651.      * stamps as local time in MSDOS format.  Thus we make sure that the
  652.      * resulting timestamp is within the range of MSDOS date-time values. */
  653.     if (ux_loctime < UTIME_1980_JAN_01_00_00)
  654.         ux_loctime = UTIME_1980_JAN_01_00_00;
  655.  
  656.     utime2FileTime(ux_loctime, &C_RTL_locft);
  657.     if (!FileTimeToLocalFileTime(pft, &NTAPI_locft))
  658.         return;
  659.     else {
  660.         long time_shift_l, time_shift_h;
  661.         int carry = 0;
  662.  
  663.         time_shift_l = C_RTL_locft.dwLowDateTime - NTAPI_locft.dwLowDateTime;
  664.         if (C_RTL_locft.dwLowDateTime < NTAPI_locft.dwLowDateTime)
  665.             carry--;
  666.         time_shift_h = C_RTL_locft.dwHighDateTime - NTAPI_locft.dwHighDateTime;
  667.         pft->dwLowDateTime += time_shift_l;
  668.         if (pft->dwLowDateTime < (ulg)time_shift_l)
  669.             carry++;
  670.         pft->dwHighDateTime += time_shift_h + carry;
  671.     }
  672. } /* end function NTtzbugWorkaround() */
  673.  
  674. #endif /* ?NT_TZBUG_WORKAROUND */
  675.  
  676.  
  677.  
  678. /****************************/      /* Get the file time in a format that */
  679. /* Function getNTfiletime() */      /*  can be used by SetFileTime() in NT */
  680. /****************************/
  681.  
  682. static int getNTfiletime(__G__ pModFT, pAccFT, pCreFT)
  683.     __GDEF
  684.     FILETIME *pModFT;
  685.     FILETIME *pAccFT;
  686.     FILETIME *pCreFT;
  687. {
  688. #ifdef NT_TZBUG_WORKAROUND
  689.     time_t ux_modtime;
  690. #else /* !NT_TZBUG_WORKAROUND */
  691.     FILETIME locft;    /* 64-bit value made up of two 32-bit [low & high] */
  692.     WORD wDOSDate;     /* for converting from DOS date to Windows NT */
  693.     WORD wDOSTime;
  694. #endif /* ?NT_TZBUG_WORKAROUND */
  695. #ifdef USE_EF_UT_TIME
  696.     unsigned eb_izux_flg;
  697.     iztimes z_utime;   /* struct for Unix-style actime & modtime, + creatime */
  698. #endif
  699. #if (defined(USE_EF_UT_TIME) && !defined(NT_TZBUG_WORKAROUND))
  700.     time_t utime_dosmin;
  701. # endif
  702. #if (defined(USE_EF_UT_TIME) || defined(NT_TZBUG_WORKAROUND))
  703.     int fs_uses_loctime = NTQueryTargetFS(G.filename);
  704. #endif
  705.  
  706.     /* Copy and/or convert time and date variables, if necessary;
  707.      * return a flag indicating which time stamps are available. */
  708. #ifdef USE_EF_UT_TIME
  709.     if (G.extra_field &&
  710.         ((eb_izux_flg = ef_scan_for_izux(G.extra_field,
  711.           G.lrec.extra_field_length, 0, G.lrec.last_mod_file_date,
  712.           &z_utime, NULL)) & EB_UT_FL_MTIME))
  713.     {
  714.         TTrace((stderr, "getNTfiletime:  Unix e.f. modif. time = %lu\n",
  715.           z_utime.mtime));
  716.         UTIME_BOUNDCHECK_1(z_utime.mtime)
  717.         utime2FileTime(z_utime.mtime, pModFT);
  718.         NT_TZBUG_PRECOMPENSATE(z_utime.mtime, pModFT)
  719.         if (eb_izux_flg & EB_UT_FL_ATIME) {
  720.             UTIME_BOUNDCHECK_N(z_utime.atime)
  721.             utime2FileTime(z_utime.atime, pAccFT);
  722.             NT_TZBUG_PRECOMPENSATE(z_utime.atime, pAccFT)
  723.         }
  724.         if (eb_izux_flg & EB_UT_FL_CTIME) {
  725.             UTIME_BOUNDCHECK_N(z_utime.ctime)
  726.             utime2FileTime(z_utime.ctime, pCreFT);
  727.             NT_TZBUG_PRECOMPENSATE(z_utime.ctime, pCreFT)
  728.         }
  729.         return (int)eb_izux_flg;
  730.     }
  731. #endif /* USE_EF_UT_TIME */
  732. #ifdef NT_TZBUG_WORKAROUND
  733.     ux_modtime = dos_to_unix_time(G.lrec.last_mod_file_date,
  734.                                   G.lrec.last_mod_file_time);
  735.     utime2FileTime(ux_modtime, pModFT);
  736.     NT_TZBUG_PRECOMPENSATE(ux_modtime, pModFT)
  737. #else /* !NT_TZBUG_WORKAROUND */
  738.  
  739.     wDOSTime = (WORD)G.lrec.last_mod_file_time;
  740.     wDOSDate = (WORD)G.lrec.last_mod_file_date;
  741.  
  742.     /* The DosDateTimeToFileTime() function converts a DOS date/time
  743.      * into a 64-bit Windows NT file time */
  744.     if (!DosDateTimeToFileTime(wDOSDate, wDOSTime, &locft))
  745.     {
  746.         Info(slide, 0, ((char *)slide, "DosDateTime failed: %d\n",
  747.           (int)GetLastError()));
  748.         return 0;
  749.     }
  750.     if (!LocalFileTimeToFileTime(&locft, pModFT))
  751.     {
  752.         Info(slide, 0, ((char *)slide, "LocalFileTime failed: %d\n",
  753.           (int)GetLastError()));
  754.         *pModFT = locft;
  755.     }
  756. #endif /* ?NT_TZBUG_WORKAROUND */
  757.     *pAccFT = *pModFT;
  758.     return (EB_UT_FL_MTIME | EB_UT_FL_ATIME);
  759.  
  760. } /* end function getNTfiletime() */
  761.  
  762.  
  763.  
  764.  
  765. /****************************/
  766. /* Function close_outfile() */
  767. /****************************/
  768.  
  769. void close_outfile(__G)
  770.     __GDEF
  771. {
  772.     FILETIME Modft;    /* File time type defined in NT, `last modified' time */
  773.     FILETIME Accft;    /* NT file time type, `last access' time */
  774.     FILETIME Creft;    /* NT file time type, `file creation' time */
  775.     HANDLE hFile;      /* File handle defined in NT    */
  776.     int gotTime;
  777. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  778.     char *ansi_name = (char *)alloca(strlen(G.filename) + 1);
  779.  
  780.     INTERN_TO_ISO(G.filename, ansi_name);
  781. #   define Ansi_Fname  ansi_name
  782. #else
  783. #   define Ansi_Fname  G.filename
  784. #endif
  785.  
  786.     /* don't set the time stamp on standard output */
  787.     if (G.cflag) {
  788.         fclose(G.outfile);
  789.         return;
  790.     }
  791.  
  792.     gotTime = getNTfiletime(__G__ &Modft, &Accft, &Creft);
  793.  
  794.     /* Close the file and then re-open it using the Win32
  795.      * CreateFile call, so that the file can be created
  796.      * with GENERIC_WRITE access, otherwise the SetFileTime
  797.      * call will fail. */
  798.     fclose(G.outfile);
  799.  
  800.     /* open a handle to the file before processing extra fields;
  801.        we do this in case new security on file prevents us from updating
  802.        time stamps */
  803.     hFile = CreateFile(Ansi_Fname, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
  804.          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  805.  
  806.     /* sfield@microsoft.com: set attributes before time in case we decide to
  807.        support other filetime members later.  This also allows us to apply
  808.        attributes before the security is changed, which may prevent this
  809.        from succeeding otherwise.  Also, since most files don't have
  810.        any interesting attributes, only change them if something other than
  811.        FILE_ATTRIBUTE_ARCHIVE appears in the attributes.  This works well
  812.        as an optimization because FILE_ATTRIBUTE_ARCHIVE gets applied to the
  813.        file anyway, when it's created new. */
  814.     if((G.pInfo->file_attr & 0x7F) & ~FILE_ATTRIBUTE_ARCHIVE) {
  815.         if (!SetFileAttributes(Ansi_Fname, G.pInfo->file_attr & 0x7F))
  816.             Info(slide, 1, ((char *)slide,
  817.               "\nwarning (%d): could not set file attributes\n",
  818.               (int)GetLastError()));
  819.     }
  820.  
  821. #ifdef NTSD_EAS
  822.     /* set extra fields, both stored-in-zipfile and .LONGNAME flavors */
  823.     if (G.extra_field) {    /* zipfile extra field may have extended attribs */
  824.         int err = EvalExtraFields(__G__ G.filename, G.extra_field,
  825.                                   G.lrec.extra_field_length);
  826.  
  827.         if (err == IZ_EF_TRUNC) {
  828.             if (G.qflag)
  829.                 Info(slide, 1, ((char *)slide, "%-22s ",
  830.                   FnFilter1(G.filename)));
  831.             Info(slide, 1, ((char *)slide, LoadFarString(TruncNTSD),
  832.               makeword(G.extra_field+2)-10, G.qflag? "\n":""));
  833.         }
  834.     }
  835. #endif /* NTSD_EAS */
  836.  
  837.     if ( hFile == INVALID_HANDLE_VALUE )
  838.         Info(slide, 1, ((char *)slide,
  839.           "\nCreateFile error %d when trying set file time\n",
  840.           (int)GetLastError()));
  841.     else {
  842.         if (gotTime) {
  843.             FILETIME *pModft = (gotTime & EB_UT_FL_MTIME) ? &Modft : NULL;
  844.             FILETIME *pAccft = (gotTime & EB_UT_FL_ATIME) ? &Accft : NULL;
  845.             FILETIME *pCreft = (gotTime & EB_UT_FL_CTIME) ? &Creft : NULL;
  846.  
  847.             if (!SetFileTime(hFile, pCreft, pAccft, pModft))
  848.                 Info(slide, 0, ((char *)slide, "\nSetFileTime failed: %d\n",
  849.                   (int)GetLastError()));
  850.         }
  851.         CloseHandle(hFile);
  852.     }
  853.  
  854.     return;
  855.  
  856. #undef Ansi_Fname
  857.  
  858. } /* end function close_outfile() */
  859.  
  860.  
  861.  
  862.  
  863. #ifdef TIMESTAMP
  864.  
  865. /*************************/
  866. /* Function stamp_file() */
  867. /*************************/
  868.  
  869. int stamp_file(ZCONST char *fname, time_t modtime)
  870. {
  871.     FILETIME Modft;    /* File time type defined in NT, `last modified' time */
  872.     HANDLE hFile;      /* File handle defined in NT    */
  873.     int errstat = 0;   /* return status: 0 == "OK", -1 == "Failure" */
  874. #ifndef NT_TZBUG_WORKAROUND
  875.     time_t utime_dosmin;        /* internal variable for UTIME_BOUNDCHECK_1 */
  876. #endif
  877.     int fs_uses_loctime = NTQueryTargetFS(fname);
  878. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  879.     char *ansi_name = (char *)alloca(strlen(fname) + 1);
  880.  
  881.     INTERN_TO_ISO(fname, ansi_name);
  882. #   define Ansi_Fname  ansi_name
  883. #else
  884. #   define Ansi_Fname  fname
  885. #endif
  886.  
  887.     /* open a handle to the file to prepare setting the mod-time stamp */
  888.     hFile = CreateFile(Ansi_Fname, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
  889.          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  890.     if ( hFile == INVALID_HANDLE_VALUE ) {
  891.         errstat = -1;
  892.     } else {
  893.         /* convert time_t modtime into WIN32 native 64bit format */
  894.         UTIME_BOUNDCHECK_1(modtime)
  895.         utime2FileTime(modtime, &Modft);
  896.         NT_TZBUG_PRECOMPENSATE(modtime, &Modft)
  897.         /* set Access and Modification times of the file to modtime */
  898.         if (!SetFileTime(hFile, NULL, &Modft, &Modft)) {
  899.             errstat = -1;
  900.         }
  901.         CloseHandle(hFile);
  902.     }
  903.  
  904.     return errstat;
  905.  
  906. #undef Ansi_Fname
  907. } /* end function stamp_file() */
  908.  
  909. #endif /* TIMESTAMP */
  910.  
  911.  
  912.  
  913.  
  914. /***********************/
  915. /* Function isfloppy() */   /* more precisely, is it removable? */
  916. /***********************/
  917.  
  918. static int isfloppy(int nDrive)   /* 1 == A:, 2 == B:, etc. */
  919. {
  920.     char rootPathName[4];
  921.  
  922.     rootPathName[0] = (char)('A' + nDrive - 1);   /* build the root path */
  923.     rootPathName[1] = ':';                        /*  name, e.g. "A:/" */
  924.     rootPathName[2] = '/';
  925.     rootPathName[3] = '\0';
  926.  
  927.     return (GetDriveType(rootPathName) == DRIVE_REMOVABLE);
  928.  
  929. } /* end function isfloppy() */
  930.  
  931.  
  932.  
  933.  
  934. /*****************************/
  935. /* Function IsVolumeOldFAT() */
  936. /*****************************/
  937.  
  938. /*
  939.  * Note:  8.3 limits on filenames apply only to old-style FAT filesystems.
  940.  *        More recent versions of Windows (Windows NT 3.5 / Windows 4.0)
  941.  *        can support long filenames (LFN) on FAT filesystems.  Check the
  942.  *        filesystem maximum component length field to detect LFN support.
  943.  *        [GRR:  this routine is only used to determine whether spaces in
  944.  *        filenames are supported...]
  945.  */
  946.  
  947. static int IsVolumeOldFAT(const char *name)
  948. {
  949.     char     *tmp0;
  950.     char      rootPathName[4];
  951.     char      tmp1[MAX_PATH], tmp2[MAX_PATH];
  952.     unsigned  volSerNo, maxCompLen, fileSysFlags;
  953. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  954.     char *ansi_name = (char *)alloca(strlen(name) + 1);
  955.  
  956.     INTERN_TO_ISO(name, ansi_name);
  957.     name = ansi_name;
  958. #endif
  959.  
  960.     if (isalpha(name[0]) && (name[1] == ':'))
  961.         tmp0 = (char *)name;
  962.     else
  963.     {
  964.         GetFullPathName(name, MAX_PATH, tmp1, &tmp0);
  965.         tmp0 = &tmp1[0];
  966.     }
  967.     strncpy(rootPathName, tmp0, 3);   /* Build the root path name, */
  968.     rootPathName[3] = '\0';           /* e.g. "A:/"                */
  969.  
  970.     GetVolumeInformation((LPCTSTR)rootPathName, (LPTSTR)tmp1, (DWORD)MAX_PATH,
  971.                          (LPDWORD)&volSerNo, (LPDWORD)&maxCompLen,
  972.                          (LPDWORD)&fileSysFlags, (LPTSTR)tmp2, (DWORD)MAX_PATH);
  973.  
  974.     /* Long Filenames (LFNs) are available if the component length is > 12 */
  975.     return maxCompLen <= 12;
  976. /*  return !strncmp(strupr(tmp2), "FAT", 3);   old version */
  977.  
  978. }
  979.  
  980.  
  981.  
  982.  
  983. /******************************/
  984. /* Function IsFileNameValid() */
  985. /******************************/
  986.  
  987. static int IsFileNameValid(const char *name)
  988. {
  989.     HFILE    hf;
  990.     OFSTRUCT of;
  991. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  992.     char *ansi_name = (char *)alloca(strlen(name) + 1);
  993.  
  994.     INTERN_TO_ISO(name, ansi_name);
  995.     name = ansi_name;
  996. #endif
  997.  
  998.     hf = OpenFile(name, &of, OF_READ | OF_SHARE_DENY_NONE);
  999.     if (hf == HFILE_ERROR)
  1000.         switch (GetLastError())
  1001.         {
  1002.             case ERROR_INVALID_NAME:
  1003.             case ERROR_FILENAME_EXCED_RANGE:
  1004.                 return FALSE;
  1005.             default:
  1006.                 return TRUE;
  1007.         }
  1008.     else
  1009.         _lclose(hf);
  1010.     return TRUE;
  1011. }
  1012.  
  1013.  
  1014.  
  1015.  
  1016. #ifndef SFX
  1017.  
  1018. /************************/
  1019. /*  Function do_wild()  */   /* identical to OS/2 version */
  1020. /************************/
  1021.  
  1022. char *do_wild(__G__ wildspec)
  1023.     __GDEF
  1024.     char *wildspec;         /* only used first time on a given dir */
  1025. {
  1026.  /* static zDIR *dir = NULL;                               */
  1027.  /* static char *dirname, *wildname, matchname[FILNAMSIZ]; */
  1028.  /* static int firstcall=TRUE, have_dirname, dirnamelen;   */
  1029.     struct zdirent *file;
  1030.  
  1031.     /* Even when we're just returning wildspec, we *always* do so in
  1032.      * matchname[]--calling routine is allowed to append four characters
  1033.      * to the returned string, and wildspec may be a pointer to argv[].
  1034.      */
  1035.     if (!G.notfirstcall) {  /* first call:  must initialize everything */
  1036.         G.notfirstcall = TRUE;
  1037.  
  1038.         if (!iswild(wildspec)) {
  1039.             strcpy(G.matchname, wildspec);
  1040.             G.have_dirname = FALSE;
  1041.             G.wild_dir = NULL;
  1042.             return G.matchname;
  1043.         }
  1044.  
  1045.         /* break the wildspec into a directory part and a wildcard filename */
  1046.         if ((G.wildname = strrchr(wildspec, '/')) == NULL &&
  1047.             (G.wildname = strrchr(wildspec, ':')) == NULL) {
  1048.             G.dirname = ".";
  1049.             G.dirnamelen = 1;
  1050.             G.have_dirname = FALSE;
  1051.             G.wildname = wildspec;
  1052.         } else {
  1053.             ++G.wildname;     /* point at character after '/' or ':' */
  1054.             G.dirnamelen = G.wildname - wildspec;
  1055.             if ((G.dirname = (char *)malloc(G.dirnamelen+1)) == NULL) {
  1056.                 Info(slide, 1, ((char *)slide,
  1057.                   "warning:  cannot allocate wildcard buffers\n"));
  1058.                 strcpy(G.matchname, wildspec);
  1059.                 return G.matchname; /* but maybe filespec was not a wildcard */
  1060.             }
  1061.             strncpy(G.dirname, wildspec, G.dirnamelen);
  1062.             G.dirname[G.dirnamelen] = '\0';    /* terminate for strcpy below */
  1063.             G.have_dirname = TRUE;
  1064.         }
  1065.         Trace((stderr, "do_wild:  dirname = [%s]\n", G.dirname));
  1066.  
  1067.         if ((G.wild_dir = (zvoid *)Opendir(G.dirname)) != NULL) {
  1068.             while ((file = Readdir((zDIR *)G.wild_dir)) != NULL) {
  1069.                 Trace((stderr, "do_wild:  Readdir returns %s\n", file->d_name));
  1070.                 if (match(file->d_name, G.wildname, 1)) { /* 1 == ignore case */
  1071.                     Trace((stderr, "do_wild:  match() succeeds\n"));
  1072.                     if (G.have_dirname) {
  1073.                         strcpy(G.matchname, G.dirname);
  1074.                         strcpy(G.matchname+G.dirnamelen, file->d_name);
  1075.                     } else
  1076.                         strcpy(G.matchname, file->d_name);
  1077.                     return G.matchname;
  1078.                 }
  1079.             }
  1080.             /* if we get to here directory is exhausted, so close it */
  1081.             Closedir((zDIR *)G.wild_dir);
  1082.             G.wild_dir = NULL;
  1083.         }
  1084.         Trace((stderr, "do_wild:  Opendir(%s) returns NULL\n", G.dirname));
  1085.  
  1086.         /* return the raw wildspec in case that works (e.g., directory not
  1087.          * searchable, but filespec was not wild and file is readable) */
  1088.         strcpy(G.matchname, wildspec);
  1089.         return G.matchname;
  1090.     }
  1091.  
  1092.     /* last time through, might have failed opendir but returned raw wildspec */
  1093.     if (G.wild_dir == NULL) {
  1094.         G.notfirstcall = FALSE;    /* reset for new wildspec */
  1095.         if (G.have_dirname)
  1096.             free(G.dirname);
  1097.         return (char *)NULL;
  1098.     }
  1099.  
  1100.     /* If we've gotten this far, we've read and matched at least one entry
  1101.      * successfully (in a previous call), so dirname has been copied into
  1102.      * matchname already.
  1103.      */
  1104.     while ((file = Readdir((zDIR *)G.wild_dir)) != NULL)
  1105.         if (match(file->d_name, G.wildname, 1)) {   /* 1 == ignore case */
  1106.             if (G.have_dirname) {
  1107.                 /* strcpy(G.matchname, G.dirname); */
  1108.                 strcpy(G.matchname+G.dirnamelen, file->d_name);
  1109.             } else
  1110.                 strcpy(G.matchname, file->d_name);
  1111.             return G.matchname;
  1112.         }
  1113.  
  1114.     Closedir((zDIR *)G.wild_dir);  /* at least one entry read; nothing left */
  1115.     G.wild_dir = NULL;
  1116.     G.notfirstcall = FALSE;        /* reset for new wildspec */
  1117.     if (G.have_dirname)
  1118.         free(G.dirname);
  1119.     return (char *)NULL;
  1120.  
  1121. } /* end function do_wild() */
  1122.  
  1123. #endif /* !SFX */
  1124.  
  1125.  
  1126.  
  1127. /**********************/
  1128. /* Function mapattr() */
  1129. /**********************/
  1130.  
  1131. /* Identical to MS-DOS, OS/2 versions.  However, NT has a lot of extra
  1132.  * permission stuff, so this function should probably be extended in the
  1133.  * future. */
  1134.  
  1135. int mapattr(__G)
  1136.     __GDEF
  1137. {
  1138.     /* set archive bit (file is not backed up): */
  1139.     G.pInfo->file_attr = (unsigned)(G.crec.external_file_attributes | FILE_ATTRIBUTE_ARCHIVE) &
  1140.       0xff;
  1141.     return 0;
  1142.  
  1143. } /* end function mapattr() */
  1144.  
  1145.  
  1146.  
  1147.  
  1148. /************************/
  1149. /*  Function mapname()  */
  1150. /************************/
  1151.                              /* return 0 if no error, 1 if caution (filename */
  1152. int mapname(__G__ renamed)   /*  truncated), 2 if warning (skip file because */
  1153.     __GDEF                   /*  dir doesn't exist), 3 if error (skip file), */
  1154.     int renamed;             /*  or 10 if out of memory (skip file) */
  1155. {                            /*  [also IZ_VOL_LABEL, IZ_CREATED_DIR] */
  1156.     char pathcomp[FILNAMSIZ];   /* path-component buffer */
  1157.     char *pp, *cp=NULL;         /* character pointers */
  1158.     char *lastsemi = NULL;      /* pointer to last semi-colon in pathcomp */
  1159.     int error;
  1160.     register unsigned workch;   /* hold the character being tested */
  1161.  
  1162.  
  1163. /*---------------------------------------------------------------------------
  1164.     Initialize various pointers and counters and stuff.
  1165.   ---------------------------------------------------------------------------*/
  1166.  
  1167.     /* can create path as long as not just freshening, or if user told us */
  1168.     G.create_dirs = (!G.fflag || renamed);
  1169.  
  1170.     G.created_dir = FALSE;      /* not yet */
  1171.     G.renamed_fullpath = FALSE;
  1172.     G.fnlen = strlen(G.filename);
  1173.  
  1174.     if (renamed) {
  1175.         cp = G.filename - 1;    /* point to beginning of renamed name... */
  1176.         while (*++cp)
  1177.             if (*cp == '\\')    /* convert backslashes to forward */
  1178.                 *cp = '/';
  1179.         cp = G.filename;
  1180.         /* use temporary rootpath if user gave full pathname */
  1181.         if (G.filename[0] == '/') {
  1182.             G.renamed_fullpath = TRUE;
  1183.             pathcomp[0] = '/';  /* copy the '/' and terminate */
  1184.             pathcomp[1] = '\0';
  1185.             ++cp;
  1186.         } else if (isalpha(G.filename[0]) && G.filename[1] == ':') {
  1187.             G.renamed_fullpath = TRUE;
  1188.             pp = pathcomp;
  1189.             *pp++ = *cp++;      /* copy the "d:" (+ '/', possibly) */
  1190.             *pp++ = *cp++;
  1191.             if (*cp == '/')
  1192.                 *pp++ = *cp++;  /* otherwise add "./"? */
  1193.             *pp = '\0';
  1194.         }
  1195.     }
  1196.  
  1197.     /* pathcomp is ignored unless renamed_fullpath is TRUE: */
  1198.     if ((error = checkdir(__G__ pathcomp, INIT)) != 0)    /* init path buffer */
  1199.         return error;           /* ...unless no mem or vol label on hard disk */
  1200.  
  1201.     *pathcomp = '\0';           /* initialize translation buffer */
  1202.     pp = pathcomp;              /* point to translation buffer */
  1203.     if (!renamed) {             /* cp already set if renamed */
  1204.         if (G.jflag)            /* junking directories */
  1205.             cp = (char *)strrchr(G.filename, '/');
  1206.         if (cp == NULL)         /* no '/' or not junking dirs */
  1207.             cp = G.filename;    /* point to internal zipfile-member pathname */
  1208.         else
  1209.             ++cp;               /* point to start of last component of path */
  1210.     }
  1211.  
  1212. /*---------------------------------------------------------------------------
  1213.     Begin main loop through characters in filename.
  1214.   ---------------------------------------------------------------------------*/
  1215.  
  1216.     while ((workch = (uch)*cp++) != 0) {
  1217.  
  1218.         switch (workch) {
  1219.         case '/':             /* can assume -j flag not given */
  1220.             *pp = '\0';
  1221.             if ((error = checkdir(__G__ pathcomp, APPEND_DIR)) > 1)
  1222.                 return error;
  1223.             pp = pathcomp;    /* reset conversion buffer for next piece */
  1224.             lastsemi = NULL;  /* leave directory semi-colons alone */
  1225.             break;
  1226.  
  1227.         case ':':             /* drive names not stored in zipfile, */
  1228.         case '<':             /*  so no colons allowed */
  1229.         case '>':             /* no redirection symbols allowed either */
  1230.         case '|':             /* no pipe signs allowed */
  1231.         case '"':             /* no double quotes allowed */
  1232.         case '?':             /* no wildcards allowed */
  1233.         case '*':
  1234.             *pp++ = '_';      /* these rules apply equally to FAT and NTFS */
  1235.             break;
  1236.         case ';':             /* start of VMS version? */
  1237.             lastsemi = pp;    /* remove VMS version later... */
  1238.             *pp++ = ';';      /*  but keep semicolon for now */
  1239.             break;
  1240.  
  1241.         case ' ':             /* keep spaces unless specifically */
  1242.             /* NT cannot create filenames with spaces on FAT volumes */
  1243.             if (G.sflag || IsVolumeOldFAT(G.filename))
  1244.                 *pp++ = '_';
  1245.             else
  1246.                 *pp++ = ' ';
  1247.             break;
  1248.  
  1249.         default:
  1250.             /* allow European characters in filenames: */
  1251.             if (isprint(workch) || workch >= 127)
  1252.                 *pp++ = (char)workch;
  1253.         } /* end switch */
  1254.     } /* end while loop */
  1255.  
  1256.     *pp = '\0';                   /* done with pathcomp:  terminate it */
  1257.  
  1258.     /* if not saving them, remove VMS version numbers (appended "###") */
  1259.     if (!G.V_flag && lastsemi) {
  1260.         pp = lastsemi + 1;        /* semi-colon was kept:  expect #'s after */
  1261.         while (isdigit((uch)(*pp)))
  1262.             ++pp;
  1263.         if (*pp == '\0')          /* only digits between ';' and end:  nuke */
  1264.             *lastsemi = '\0';
  1265.     }
  1266.  
  1267. /*---------------------------------------------------------------------------
  1268.     Report if directory was created (and no file to create:  filename ended
  1269.     in '/'), check name to be sure it exists, and combine path and name be-
  1270.     fore exiting.
  1271.   ---------------------------------------------------------------------------*/
  1272.  
  1273.     if (G.filename[G.fnlen-1] == '/') {
  1274.         checkdir(__G__ G.filename, GETPATH);
  1275.         if (G.created_dir) {
  1276.             if (QCOND2) {
  1277.                 Info(slide, 0, ((char *)slide, "   creating: %-22s\n",
  1278.                   FnFilter1(G.filename)));
  1279.             }
  1280.             /* HG: are we setting the date & time on a newly created   */
  1281.             /*     dir?  Not quite sure how to do this.  It does not   */
  1282.             /*     seem to be done in the MS-DOS version of mapname(). */
  1283.  
  1284. #ifdef NTSD_EAS
  1285.             /* set extra fields, both stored-in-zipfile and .LONGNAME flavors */
  1286.             if (G.extra_field) { /* zipfile e.f. may have extended attribs */
  1287.                 int err = EvalExtraFields(__G__ G.filename, G.extra_field,
  1288.                                           G.lrec.extra_field_length);
  1289.  
  1290.                 if (err == IZ_EF_TRUNC) {
  1291.                     if (G.qflag)
  1292.                         Info(slide, 1, ((char *)slide, "%-22s ",
  1293.                           FnFilter1(G.filename)));
  1294.                     Info(slide, 1, ((char *)slide, LoadFarString(TruncNTSD),
  1295.                       makeword(G.extra_field+2)-10, G.qflag? "\n":""));
  1296.                 }
  1297.             }
  1298. #endif /* NTSD_EAS */
  1299.             return IZ_CREATED_DIR;      /* set dir time (note trailing '/') */
  1300.         }
  1301.         return 2;   /* dir existed already; don't look for data to extract */
  1302.     }
  1303.  
  1304.     if (*pathcomp == '\0') {
  1305.         Info(slide, 1, ((char *)slide, "mapname:  conversion of %s failed\n",
  1306.           FnFilter1(G.filename)));
  1307.         return 3;
  1308.     }
  1309.  
  1310.     checkdir(__G__ pathcomp, APPEND_NAME);  /* returns 1 if truncated: care? */
  1311.     checkdir(__G__ G.filename, GETPATH);
  1312.     Trace((stderr, "mapname returns with filename = [%s] (error = %d)\n\n",
  1313.       FnFilter1(G.filename), error));
  1314.  
  1315.     if (G.pInfo->vollabel) {    /* set the volume label now */
  1316.         char drive[4];
  1317. #ifdef __RSXNT__        /* RSXNT/EMX C rtl uses OEM charset */
  1318.         char *ansi_name = (char *)alloca(strlen(G.filename) + 1);
  1319.         INTERN_TO_ISO(G.filename, ansi_name);
  1320. #       define Ansi_Fname  ansi_name
  1321. #else
  1322. #       define Ansi_Fname  G.filename
  1323. #endif
  1324.  
  1325.         /* Build a drive string, e.g. "b:" */
  1326.         drive[0] = (char)('a' + G.nLabelDrive - 1);
  1327.         strcpy(drive + 1, ":\\");
  1328.         if (QCOND2)
  1329.             Info(slide, 0, ((char *)slide, "labelling %s %-22s\n", drive,
  1330.               FnFilter1(G.filename)));
  1331.         if (!SetVolumeLabel(drive, Ansi_Fname)) {
  1332.             Info(slide, 1, ((char *)slide,
  1333.               "mapname:  error setting volume label\n"));
  1334.             return 3;
  1335.         }
  1336.         return 2;   /* success:  skip the "extraction" quietly */
  1337. #undef Ansi_Fname
  1338.     }
  1339.  
  1340.     return error;
  1341.  
  1342. } /* end function mapname() */
  1343.  
  1344.  
  1345.  
  1346.  
  1347. /**********************/
  1348. /* Function map2fat() */        /* Not quite identical to OS/2 version */
  1349. /**********************/
  1350.  
  1351. static void map2fat(pathcomp, pEndFAT)
  1352.     char *pathcomp, **pEndFAT;
  1353. {
  1354.     char *ppc = pathcomp;       /* variable pointer to pathcomp */
  1355.     char *pEnd = *pEndFAT;      /* variable pointer to buildpathFAT */
  1356.     char *pBegin = *pEndFAT;    /* constant pointer to start of this comp. */
  1357.     char *last_dot = NULL;      /* last dot not converted to underscore */
  1358.     int dotname = FALSE;        /* flag:  path component begins with dot */
  1359.                                 /*  ("." and ".." don't count) */
  1360.     register unsigned workch;   /* hold the character being tested */
  1361.  
  1362.  
  1363.     /* Only need check those characters which are legal in NTFS but not
  1364.      * in FAT:  to get here, must already have passed through mapname.
  1365.      * Also must truncate path component to ensure 8.3 compliance.
  1366.      */
  1367.     while ((workch = (uch)*ppc++) != 0) {
  1368.         switch (workch) {
  1369.             case '[':
  1370.             case ']':
  1371.             case '+':
  1372.             case ',':
  1373.             case ';':
  1374.             case '=':
  1375.                 *pEnd++ = '_';      /* convert brackets to underscores */
  1376.                 break;
  1377.  
  1378.             case '.':
  1379.                 if (pEnd == *pEndFAT) {   /* nothing appended yet... */
  1380.                     if (*ppc == '\0')     /* don't bother appending a */
  1381.                         break;            /*  "./" component to the path */
  1382.                     else if (*ppc == '.' && ppc[1] == '\0') {   /* "../" */
  1383.                         *pEnd++ = '.';    /* add first dot, unchanged... */
  1384.                         ++ppc;            /* skip second dot, since it will */
  1385.                     } else {              /*  be "added" at end of if-block */
  1386.                         *pEnd++ = '_';    /* FAT doesn't allow null filename */
  1387.                         dotname = TRUE;   /*  bodies, so map .exrc -> _.exrc */
  1388.                     }                     /*  (extra '_' now, "dot" below) */
  1389.                 } else if (dotname) {     /* found a second dot, but still */
  1390.                     dotname = FALSE;      /*  have extra leading underscore: */
  1391.                     *pEnd = '\0';         /*  remove it by shifting chars */
  1392.                     pEnd = *pEndFAT + 1;  /*  left one space (e.g., .p1.p2: */
  1393.                     while (pEnd[1]) {     /*  __p1 -> _p1_p2 -> _p1.p2 when */
  1394.                         *pEnd = pEnd[1];  /*  finished) [opt.:  since first */
  1395.                         ++pEnd;           /*  two chars are same, can start */
  1396.                     }                     /*  shifting at second position] */
  1397.                 }
  1398.                 last_dot = pEnd;    /* point at last dot so far... */
  1399.                 *pEnd++ = '_';      /* convert dot to underscore for now */
  1400.                 break;
  1401.  
  1402.             default:
  1403.                 *pEnd++ = (char)workch;
  1404.  
  1405.         } /* end switch */
  1406.     } /* end while loop */
  1407.  
  1408.     *pEnd = '\0';                 /* terminate buildpathFAT */
  1409.  
  1410.     /* NOTE:  keep in mind that pEnd points to the end of the path
  1411.      * component, and *pEndFAT still points to the *beginning* of it...
  1412.      * Also note that the algorithm does not try to get too fancy:
  1413.      * if there are no dots already, the name either gets truncated
  1414.      * at 8 characters or the last underscore is converted to a dot
  1415.      * (only if more characters are saved that way).  In no case is
  1416.      * a dot inserted between existing characters.
  1417.      */
  1418.     if (last_dot == NULL) {       /* no dots:  check for underscores... */
  1419.         char *plu = strrchr(pBegin, '_');   /* pointer to last underscore */
  1420.  
  1421.         if (plu == NULL) {   /* no dots, no underscores:  truncate at 8 chars */
  1422.             *pEndFAT += 8;        /* (or could insert '.' and keep 11...?) */
  1423.             if (*pEndFAT > pEnd)
  1424.                 *pEndFAT = pEnd;  /* oops...didn't have 8 chars to truncate */
  1425.             else
  1426.                 **pEndFAT = '\0';
  1427.         } else if (MIN(plu - pBegin, 8) + MIN(pEnd - plu - 1, 3) > 8) {
  1428.             last_dot = plu;       /* be lazy:  drop through to next if-blk */
  1429.         } else if ((pEnd - *pEndFAT) > 8) {
  1430.             *pEndFAT += 8;        /* more fits into just basename than if */
  1431.             **pEndFAT = '\0';     /*  convert last underscore to dot */
  1432.         } else
  1433.             *pEndFAT = pEnd;      /* whole thing fits into 8 chars or less */
  1434.     }
  1435.  
  1436.     if (last_dot != NULL) {       /* one dot (or two, in the case of */
  1437.         *last_dot = '.';          /*  "..") is OK:  put it back in */
  1438.  
  1439.         if ((last_dot - pBegin) > 8) {
  1440.             char *p, *q;
  1441.             int i;
  1442.  
  1443.             p = last_dot;
  1444.             q = last_dot = pBegin + 8;
  1445.             for (i = 0;  (i < 4) && *p;  ++i)  /* too many chars in basename: */
  1446.                 *q++ = *p++;                   /*  shift .ext left and trun- */
  1447.             *q = '\0';                         /*  cate/terminate it */
  1448.             *pEndFAT = q;
  1449.         } else if ((pEnd - last_dot) > 4) {    /* too many chars in extension */
  1450.             *pEndFAT = last_dot + 4;
  1451.             **pEndFAT = '\0';
  1452.         } else
  1453.             *pEndFAT = pEnd;   /* filename is fine; point at terminating zero */
  1454.  
  1455.         if ((last_dot - pBegin) > 0 && last_dot[-1] == ' ')
  1456.             last_dot[-1] = '_';                /* NO blank in front of '.'! */
  1457.     }
  1458. } /* end function map2fat() */
  1459.  
  1460.  
  1461.  
  1462.  
  1463. /***********************/       /* Borrowed from os2.c for UnZip 5.1.        */
  1464. /* Function checkdir() */       /* Difference: no EA stuff                   */
  1465. /***********************/       /*             HPFS stuff works on NTFS too  */
  1466.  
  1467. int checkdir(__G__ pathcomp, flag)
  1468.     __GDEF
  1469.     char *pathcomp;
  1470.     int flag;
  1471. /*
  1472.  * returns:  1 - (on APPEND_NAME) truncated filename
  1473.  *           2 - path doesn't exist, not allowed to create
  1474.  *           3 - path doesn't exist, tried to create and failed; or
  1475.  *               path exists and is not a directory, but is supposed to be
  1476.  *           4 - path is too long
  1477.  *          10 - can't allocate memory for filename buffers
  1478.  */
  1479. {
  1480.  /* static int rootlen = 0;     */   /* length of rootpath */
  1481.  /* static char *rootpath;      */   /* user's "extract-to" directory */
  1482.  /* static char *buildpathHPFS; */   /* full path (so far) to extracted file, */
  1483.  /* static char *buildpathFAT;  */   /*  both HPFS/EA (main) and FAT versions */
  1484.  /* static char *endHPFS;       */   /* corresponding pointers to end of */
  1485.  /* static char *endFAT;        */   /*  buildpath ('\0') */
  1486.  
  1487. #   define FN_MASK   7
  1488. #   define FUNCTION  (flag & FN_MASK)
  1489.  
  1490.  
  1491.  
  1492. /*---------------------------------------------------------------------------
  1493.     APPEND_DIR:  append the path component to the path being built and check
  1494.     for its existence.  If doesn't exist and we are creating directories, do
  1495.     so for this one; else signal success or error as appropriate.
  1496.   ---------------------------------------------------------------------------*/
  1497.  
  1498.     if (FUNCTION == APPEND_DIR) {
  1499.         char *p = pathcomp;
  1500.         int too_long=FALSE;
  1501.  
  1502.         Trace((stderr, "appending dir segment [%s]\n", pathcomp));
  1503.         while ((*G.endHPFS = *p++) != '\0')     /* copy to HPFS filename */
  1504.             ++G.endHPFS;
  1505.         if (IsFileNameValid(G.buildpathHPFS)) {
  1506.             p = pathcomp;
  1507.             while ((*G.endFAT = *p++) != '\0')  /* copy to FAT filename, too */
  1508.                 ++G.endFAT;
  1509.         } else
  1510.             map2fat(pathcomp, &G.endFAT);   /* map into FAT fn, update endFAT */
  1511.  
  1512.         /* GRR:  could do better check, see if overrunning buffer as we go:
  1513.          * check endHPFS-buildpathHPFS after each append, set warning variable
  1514.          * if within 20 of FILNAMSIZ; then if var set, do careful check when
  1515.          * appending.  Clear variable when begin new path. */
  1516.  
  1517.         /* next check:  need to append '/', at least one-char name, '\0' */
  1518.         if ((G.endHPFS-G.buildpathHPFS) > FILNAMSIZ-3)
  1519.             too_long = TRUE;                    /* check if extracting dir? */
  1520. #ifdef FIX_STAT_BUG
  1521.         /* Borland C++ 5.0 does not handle a call to stat() well if the
  1522.          * directory does not exist (it tends to crash in strange places.)
  1523.          * This is apparently a problem only when compiling for GUI rather
  1524.          * than console. The code below attempts to work around this problem.
  1525.          */
  1526.         if (access(G.buildpathFAT, 0) != 0) {
  1527.             if (!G.create_dirs) { /* told not to create (freshening) */
  1528.                 free(G.buildpathHPFS);
  1529.                 free(G.buildpathFAT);
  1530.                 return 2;         /* path doesn't exist:  nothing to do */
  1531.             }
  1532.             if (too_long) {   /* GRR:  should allow FAT extraction w/o EAs */
  1533.                 Info(slide, 1, ((char *)slide,
  1534.                   "checkdir error:  path too long: %s\n",
  1535.                   FnFilter1(G.buildpathHPFS)));
  1536.                 free(G.buildpathHPFS);
  1537.                 free(G.buildpathFAT);
  1538.                 return 4;         /* no room for filenames:  fatal */
  1539.             }
  1540.             if (MKDIR(G.buildpathFAT, 0777) == -1) { /* create the directory */
  1541.                 Info(slide, 1, ((char *)slide,
  1542.                   "checkdir error:  cannot create %s\n\
  1543.                  unable to process %s.\n",
  1544.                   FnFilter2(G.buildpathFAT), FnFilter1(G.filename)));
  1545.                 free(G.buildpathHPFS);
  1546.                 free(G.buildpathFAT);
  1547.                 return 3;      /* path didn't exist, tried to create, failed */
  1548.             }
  1549.             G.created_dir = TRUE;
  1550.         }
  1551. #endif /* FIX_STAT_BUG */
  1552.         if (SSTAT(G.buildpathFAT, &G.statbuf))   /* path doesn't exist */
  1553.         {
  1554.             if (!G.create_dirs) { /* told not to create (freshening) */
  1555.                 free(G.buildpathHPFS);
  1556.                 free(G.buildpathFAT);
  1557.                 return 2;         /* path doesn't exist:  nothing to do */
  1558.             }
  1559.             if (too_long) {   /* GRR:  should allow FAT extraction w/o EAs */
  1560.                 Info(slide, 1, ((char *)slide,
  1561.                   "checkdir error:  path too long: %s\n",
  1562.                   FnFilter1(G.buildpathHPFS)));
  1563.                 free(G.buildpathHPFS);
  1564.                 free(G.buildpathFAT);
  1565.                 return 4;         /* no room for filenames:  fatal */
  1566.             }
  1567.             if (MKDIR(G.buildpathFAT, 0777) == -1) { /* create the directory */
  1568.                 Info(slide, 1, ((char *)slide,
  1569.                   "checkdir error:  cannot create %s\n\
  1570.                  unable to process %s.\n",
  1571.                   FnFilter2(G.buildpathFAT), FnFilter1(G.filename)));
  1572.                 free(G.buildpathHPFS);
  1573.                 free(G.buildpathFAT);
  1574.                 return 3;      /* path didn't exist, tried to create, failed */
  1575.             }
  1576.             G.created_dir = TRUE;
  1577.         } else if (!S_ISDIR(G.statbuf.st_mode)) {
  1578.             Info(slide, 1, ((char *)slide,
  1579.               "checkdir error:  %s exists but is not directory\n   \
  1580.               unable to process %s.\n",
  1581.               FnFilter2(G.buildpathFAT), FnFilter1(G.filename)));
  1582.             free(G.buildpathHPFS);
  1583.             free(G.buildpathFAT);
  1584.             return 3;          /* path existed but wasn't dir */
  1585.         }
  1586.         if (too_long) {
  1587.             Info(slide, 1, ((char *)slide,
  1588.               "checkdir error:  path too long: %s\n",
  1589.                FnFilter1(G.buildpathHPFS)));
  1590.             free(G.buildpathHPFS);
  1591.             free(G.buildpathFAT);
  1592.             return 4;         /* no room for filenames:  fatal */
  1593.         }
  1594.         *G.endHPFS++ = '/';
  1595.         *G.endFAT++ = '/';
  1596.         *G.endHPFS = *G.endFAT = '\0';
  1597.         Trace((stderr, "buildpathHPFS now = [%s]\nbuildpathFAT now =  [%s]\n",
  1598.           FnFilter1(G.buildpathHPFS), FnFilter2(G.buildpathFAT)));
  1599.         return 0;
  1600.  
  1601.     } /* end if (FUNCTION == APPEND_DIR) */
  1602.  
  1603. /*---------------------------------------------------------------------------
  1604.     GETPATH:  copy full FAT path to the string pointed at by pathcomp (want
  1605.     filename to reflect name used on disk, not EAs; if full path is HPFS,
  1606.     buildpathFAT and buildpathHPFS will be identical).  Also free both paths.
  1607.   ---------------------------------------------------------------------------*/
  1608.  
  1609.     if (FUNCTION == GETPATH) {
  1610.         Trace((stderr, "getting and freeing FAT path [%s]\n",
  1611.           FnFilter1(G.buildpathFAT)));
  1612.         Trace((stderr, "freeing HPFS path [%s]\n",
  1613.           FnFilter1(G.buildpathHPFS)));
  1614.         strcpy(pathcomp, G.buildpathFAT);
  1615.         free(G.buildpathFAT);
  1616.         free(G.buildpathHPFS);
  1617.         G.buildpathHPFS = G.buildpathFAT = G.endHPFS = G.endFAT = NULL;
  1618.         return 0;
  1619.     }
  1620.  
  1621. /*---------------------------------------------------------------------------
  1622.     APPEND_NAME:  assume the path component is the filename; append it and
  1623.     return without checking for existence.
  1624.   ---------------------------------------------------------------------------*/
  1625.  
  1626.     if (FUNCTION == APPEND_NAME) {
  1627.         char *p = pathcomp;
  1628.         int error = 0;
  1629.  
  1630.         Trace((stderr, "appending filename [%s]\n", FnFilter1(pathcomp)));
  1631.         while ((*G.endHPFS = *p++) != '\0') {   /* copy to HPFS filename */
  1632.             ++G.endHPFS;
  1633.             if ((G.endHPFS-G.buildpathHPFS) >= FILNAMSIZ) {
  1634.                 *--G.endHPFS = '\0';
  1635.                 Info(slide, 1, ((char *)slide,
  1636.                   "checkdir warning:  path too long; truncating\n \
  1637.                   %s\n                -> %s\n",
  1638.                   FnFilter1(G.filename), FnFilter2(G.buildpathHPFS)));
  1639.                 error = 1;   /* filename truncated */
  1640.             }
  1641.         }
  1642.  
  1643.         if ( G.pInfo->vollabel || IsFileNameValid(G.buildpathHPFS)) {
  1644.             p = pathcomp;
  1645.             while ((*G.endFAT = *p++) != '\0')  /* copy to FAT filename, too */
  1646.                 ++G.endFAT;
  1647.         } else
  1648.             map2fat(pathcomp, &G.endFAT);   /* map into FAT fn, update endFAT */
  1649.         Trace((stderr, "buildpathHPFS: %s\nbuildpathFAT:  %s\n",
  1650.           FnFilter1(G.buildpathHPFS), FnFilter2(G.buildpathFAT)));
  1651.  
  1652.         return error;  /* could check for existence, prompt for new name... */
  1653.  
  1654.     } /* end if (FUNCTION == APPEND_NAME) */
  1655.  
  1656. /*---------------------------------------------------------------------------
  1657.     INIT:  allocate and initialize buffer space for the file currently being
  1658.     extracted.  If file was renamed with an absolute path, don't prepend the
  1659.     extract-to path.
  1660.   ---------------------------------------------------------------------------*/
  1661.  
  1662.     if (FUNCTION == INIT) {
  1663.         Trace((stderr, "initializing buildpathHPFS and buildpathFAT to "));
  1664.         if ((G.buildpathHPFS = (char *)malloc(G.fnlen+G.rootlen+1)) == NULL)
  1665.             return 10;
  1666.         if ((G.buildpathFAT = (char *)malloc(G.fnlen+G.rootlen+1)) == NULL) {
  1667.             free(G.buildpathHPFS);
  1668.             return 10;
  1669.         }
  1670.         if (G.pInfo->vollabel) { /* use root or renamed path, but don't store */
  1671. /* GRR:  for network drives, do strchr() and return IZ_VOL_LABEL if not [1] */
  1672.             if (G.renamed_fullpath && pathcomp[1] == ':')
  1673.                 *G.buildpathHPFS = (char)ToLower(*pathcomp);
  1674.             else if (!G.renamed_fullpath && G.rootlen > 1 &&
  1675.                      G.rootpath[1] == ':')
  1676.                 *G.buildpathHPFS = (char)ToLower(*G.rootpath);
  1677.             else {
  1678.                 char tmpN[MAX_PATH], *tmpP;
  1679.                 if (GetFullPathName(".", MAX_PATH, tmpN, &tmpP) > MAX_PATH)
  1680.                 { /* by definition of MAX_PATH we should never get here */
  1681.                     Info(slide, 1, ((char *)slide,
  1682.                       "checkdir warning: current dir path too long\n"));
  1683.                     return 1;   /* can't get drive letter */
  1684.                 }
  1685.                 G.nLabelDrive = *tmpN - 'a' + 1;
  1686.                 *G.buildpathHPFS = (char)(G.nLabelDrive - 1 + 'a');
  1687.             }
  1688.             G.nLabelDrive = *G.buildpathHPFS - 'a' + 1; /* save for mapname() */
  1689.             if (G.volflag == 0 || *G.buildpathHPFS < 'a'  /* no labels/bogus? */
  1690.                  || (G.volflag == 1 && !isfloppy(G.nLabelDrive))) { /* !fixed */
  1691.                 free(G.buildpathHPFS);
  1692.                 free(G.buildpathFAT);
  1693.                 return IZ_VOL_LABEL;   /* skipping with message */
  1694.             }
  1695.             *G.buildpathHPFS = '\0';
  1696.         } else if (G.renamed_fullpath) /* pathcomp = valid data */
  1697.             strcpy(G.buildpathHPFS, pathcomp);
  1698.         else if (G.rootlen > 0)
  1699.             strcpy(G.buildpathHPFS, G.rootpath);
  1700.         else
  1701.             *G.buildpathHPFS = '\0';
  1702.         G.endHPFS = G.buildpathHPFS;
  1703.         G.endFAT = G.buildpathFAT;
  1704.         while ((*G.endFAT = *G.endHPFS) != '\0') {
  1705.             ++G.endFAT;
  1706.             ++G.endHPFS;
  1707.         }
  1708.         Trace((stderr, "[%s]\n", FnFilter1(G.buildpathHPFS)));
  1709.         return 0;
  1710.     }
  1711.  
  1712. /*---------------------------------------------------------------------------
  1713.     ROOT:  if appropriate, store the path in rootpath and create it if neces-
  1714.     sary; else assume it's a zipfile member and return.  This path segment
  1715.     gets used in extracting all members from every zipfile specified on the
  1716.     command line.  Note that under OS/2 and MS-DOS, if a candidate extract-to
  1717.     directory specification includes a drive letter (leading "x:"), it is
  1718.     treated just as if it had a trailing '/'--that is, one directory level
  1719.     will be created if the path doesn't exist, unless this is otherwise pro-
  1720.     hibited (e.g., freshening).
  1721.   ---------------------------------------------------------------------------*/
  1722.  
  1723. #if (!defined(SFX) || defined(SFX_EXDIR))
  1724.     if (FUNCTION == ROOT) {
  1725.         Trace((stderr, "initializing root path to [%s]\n",
  1726.           FnFilter1(pathcomp)));
  1727.         if (pathcomp == NULL) {
  1728.             G.rootlen = 0;
  1729.             return 0;
  1730.         }
  1731.         if ((G.rootlen = strlen(pathcomp)) > 0) {
  1732.             int had_trailing_pathsep=FALSE, has_drive=FALSE, xtra=2;
  1733.  
  1734.             if (isalpha(pathcomp[0]) && pathcomp[1] == ':')
  1735.                 has_drive = TRUE;   /* drive designator */
  1736.             if (pathcomp[G.rootlen-1] == '/' || pathcomp[G.rootlen-1] == '\\') {
  1737.                 pathcomp[--G.rootlen] = '\0';
  1738.                 had_trailing_pathsep = TRUE;
  1739.             }
  1740.             if (has_drive && (G.rootlen == 2)) {
  1741.                 if (!had_trailing_pathsep)   /* i.e., original wasn't "x:/" */
  1742.                     xtra = 3;      /* room for '.' + '/' + 0 at end of "x:" */
  1743.             } else if (G.rootlen > 0) {   /* need not check "x:." and "x:/" */
  1744.                 if (SSTAT(pathcomp, &G.statbuf) || !S_ISDIR(G.statbuf.st_mode))
  1745.                 {
  1746.                     /* path does not exist */
  1747.                     if (!G.create_dirs /* || iswild(pathcomp) */ ) {
  1748.                         G.rootlen = 0;
  1749.                         return 2;   /* treat as stored file */
  1750.                     }
  1751.                     /* create directory (could add loop here to scan pathcomp
  1752.                      * and create more than one level, but really necessary?) */
  1753.                     if (MKDIR(pathcomp, 0777) == -1) {
  1754.                         Info(slide, 1, ((char *)slide,
  1755.                           "checkdir:  cannot create extraction directory: %s\n",
  1756.                           FnFilter1(pathcomp)));
  1757.                         G.rootlen = 0; /* path didn't exist, tried to create, */
  1758.                         return 3;  /* failed:  file exists, or need 2+ levels */
  1759.                     }
  1760.                 }
  1761.             }
  1762.             if ((G.rootpath = (char *)malloc(G.rootlen+xtra)) == NULL) {
  1763.                 G.rootlen = 0;
  1764.                 return 10;
  1765.             }
  1766.             strcpy(G.rootpath, pathcomp);
  1767.             if (xtra == 3)                  /* had just "x:", make "x:." */
  1768.                 G.rootpath[G.rootlen++] = '.';
  1769.             G.rootpath[G.rootlen++] = '/';
  1770.             G.rootpath[G.rootlen] = '\0';
  1771.             Trace((stderr, "rootpath now = [%s]\n", FnFilter1(G.rootpath)));
  1772.         }
  1773.         return 0;
  1774.     }
  1775. #endif /* !SFX || SFX_EXDIR */
  1776.  
  1777. /*---------------------------------------------------------------------------
  1778.     END:  free rootpath, immediately prior to program exit.
  1779.   ---------------------------------------------------------------------------*/
  1780.  
  1781.     if (FUNCTION == END) {
  1782.         Trace((stderr, "freeing rootpath\n"));
  1783.         if (G.rootlen > 0) {
  1784.             free(G.rootpath);
  1785.             G.rootlen = 0;
  1786.         }
  1787.         return 0;
  1788.     }
  1789.  
  1790.     return 99;  /* should never reach */
  1791.  
  1792. } /* end function checkdir() */
  1793.  
  1794.  
  1795.  
  1796.  
  1797.  
  1798. #ifndef SFX
  1799. #ifndef WINDLL
  1800.  
  1801. /************************/
  1802. /*  Function version()  */
  1803. /************************/
  1804.  
  1805. void version(__G)
  1806.     __GDEF
  1807. {
  1808.     int len;
  1809. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DJGPP__))
  1810.     char buf[80];
  1811. #if (defined(_MSC_VER) && (_MSC_VER > 900))
  1812.     char buf2[80];
  1813. #endif
  1814. #endif
  1815.  
  1816.     len = sprintf((char *)slide, CompiledWith,
  1817.  
  1818. #if defined(_MSC_VER)  /* MSC == VC++, but what about SDK compiler? */
  1819.       (sprintf(buf, "Microsoft C %d.%02d ", _MSC_VER/100, _MSC_VER%100), buf),
  1820. #  if (_MSC_VER == 800)
  1821.       "(Visual C++ v1.1)",
  1822. #  elif (_MSC_VER == 850)
  1823.       "(Windows NT v3.5 SDK)",
  1824. #  elif (_MSC_VER == 900)
  1825.       "(Visual C++ v2.x)",
  1826. #  elif (_MSC_VER > 900)
  1827.       (sprintf(buf2, "(Visual C++ %d.%d)", _MSC_VER/100 - 6, _MSC_VER%100/10),
  1828.         buf2),
  1829. #  else
  1830.       "(bad version)",
  1831. #  endif
  1832. #elif defined(__WATCOMC__)
  1833. #  if (__WATCOMC__ % 10 > 0)
  1834.       (sprintf(buf, "Watcom C/C++ %d.%02d", __WATCOMC__ / 100,
  1835.        __WATCOMC__ % 100), buf), "",
  1836. #  else
  1837.       (sprintf(buf, "Watcom C/C++ %d.%d", __WATCOMC__ / 100,
  1838.        (__WATCOMC__ % 100) / 10), buf), "",
  1839. #  endif
  1840. #elif defined(__BORLANDC__)
  1841.       "Borland C++",
  1842. #  if (__BORLANDC__ < 0x0200)
  1843.       " 1.0",
  1844. #  elif (__BORLANDC__ == 0x0200)
  1845.       " 2.0",
  1846. #  elif (__BORLANDC__ == 0x0400)
  1847.       " 3.0",
  1848. #  elif (__BORLANDC__ == 0x0410)   /* __BCPLUSPLUS__ = 0x0310 */
  1849.       " 3.1",
  1850. #  elif (__BORLANDC__ == 0x0452)   /* __BCPLUSPLUS__ = 0x0320 */
  1851.       " 4.0 or 4.02",
  1852. #  elif (__BORLANDC__ == 0x0460)   /* __BCPLUSPLUS__ = 0x0340 */
  1853.       " 4.5",
  1854. #  elif (__BORLANDC__ == 0x0500)   /* GRR:  assume this will stay sync'd? */
  1855.       " 5.0",
  1856. #  else
  1857.       " later than 5.0",
  1858. #  endif
  1859. #elif defined(__GNUC__)
  1860. #  ifdef __RSXNT__
  1861. #    if defined(__EMX__)
  1862.       "rsxnt(emx)+gcc ",
  1863. #    elif defined(__DJGPP__)
  1864.       (sprintf(buf, "rsxnt(djgpp) v%d.%02d / gcc ", __DJGPP__, __DJGPP_MINOR__),
  1865.        buf),
  1866. #    elif defined(__GO32__)
  1867.       "rsxnt(djgpp) v1.x / gcc ",
  1868. #    else
  1869.       "rsxnt(unknown) / gcc ",
  1870. #    endif
  1871. #  else
  1872.       "gcc ",
  1873. #  endif
  1874.       __VERSION__,
  1875. #else /* !_MSC_VER, !__WATCOMC__, !__BORLANDC__, !__GNUC__ */
  1876.       "unknown compiler (SDK?)", "",
  1877. #endif /* ?compilers */
  1878.  
  1879.       "Windows 95 / Windows NT", "\n(32-bit)",
  1880.  
  1881. #ifdef __DATE__
  1882.       " on ", __DATE__
  1883. #else
  1884.       "", ""
  1885. #endif
  1886.     );
  1887.  
  1888.     (*G.message)((zvoid *)&G, slide, (ulg)len, 0);
  1889.  
  1890.     return;
  1891.  
  1892. } /* end function version() */
  1893.  
  1894. #endif /* !WINDLL */
  1895. #endif /* !SFX */
  1896.  
  1897.  
  1898.  
  1899.  
  1900. #ifdef __WATCOMC__
  1901.  
  1902. /* This papers over a bug in Watcom 10.6's standard library... sigh */
  1903. /* Apparently it applies to both the DOS and Win32 stat()s.         */
  1904. /* I believe they said this was fixed for 11.0?                     */
  1905.  
  1906. int stat_bandaid(const char *path, struct stat *buf)
  1907. {
  1908.   char newname[4];
  1909.   if (!stat(path, buf))
  1910.     return 0;
  1911.   else if (!strcmp(path, ".") || (path[0] && !strcmp(path + 1, ":."))) {
  1912.     strcpy(newname, path);
  1913.     newname[strlen(path) - 1] = '\\';   /* stat(".") fails for root! */
  1914.     return stat(newname, buf);
  1915.   } else
  1916.     return -1;
  1917. }
  1918.  
  1919. /* Watcom 10.6's getch() does not handle Alt+<digit><digit><digit>. */
  1920. /* Note that if PASSWD_FROM_STDIN is defined, the file containing   */
  1921. /* the password must have a carriage return after the word, not a   */
  1922. /* Unix-style newline (linefeed only).  This discards linefeeds.    */
  1923.  
  1924. int getch(void)
  1925. {
  1926.   HANDLE stin;
  1927.   DWORD rc;
  1928.   unsigned char buf[2];
  1929.   int ret = -1;
  1930.  
  1931. #  ifdef PASSWD_FROM_STDIN
  1932.   DWORD odemode = ~0;
  1933.   stin = GetStdHandle(STD_INPUT_HANDLE);
  1934.   if (GetConsoleMode(stin, &odemode))
  1935.     SetConsoleMode(stin, ENABLE_PROCESSED_INPUT);  /* raw except ^C noticed */
  1936. #  else
  1937.   if (!(stin = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE,
  1938.                           FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)))
  1939.     return -1;
  1940.   SetConsoleMode(stin, ENABLE_PROCESSED_INPUT);    /* raw except ^C noticed */
  1941. #  endif
  1942.   if (ReadFile(stin, &buf, 1, &rc, NULL) && rc == 1)
  1943.     ret = buf[0];
  1944.   /* when the user hits return we get CR LF.  We discard the LF, not the CR,
  1945.    * because when we call this for the first time after a previous input
  1946.    * such as the one for "replace foo? [y]es, ..." the LF may still be in
  1947.    * the input stream before whatever the user types at our prompt. */
  1948.   if (ret == '\n')
  1949.     if (ReadFile(stin, &buf, 1, &rc, NULL) && rc == 1)
  1950.       ret = buf[0];
  1951. #  ifdef PASSWD_FROM_STDIN
  1952.   if (odemode != ~0)
  1953.     SetConsoleMode(stin, odemode);
  1954. #  else
  1955.   CloseHandle(stin);
  1956. #  endif
  1957.   return ret;
  1958. }
  1959.  
  1960. #endif /* __WATCOMC__ */
  1961.