home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / unzip540.zip / wince / intrface.cpp < prev    next >
C/C++ Source or Header  |  1998-08-07  |  55KB  |  1,542 lines

  1. //******************************************************************************
  2. //
  3. // File:        INTRFACE.CPP
  4. //
  5. // Description: This module acts as the interface between the Info-ZIP code and
  6. //              our Windows code in WINMAIN.CPP.  We expose the needed
  7. //              functions to query a file list, test file(s), extract file(s),
  8. //              and display a zip file comment.  The windows code is never
  9. //              bothered with understanding the Globals structure "Uz_Globs".
  10. //
  11. //              This module also catches all the callbacks from the Info-ZIP
  12. //              code, cleans up the data provided in the callback, and then
  13. //              forwards the information to the appropriate function in the
  14. //              windows code.  These callbacks include status messages, file
  15. //              lists, comments, password prompt, and file overwrite prompts.
  16. //
  17. //              Finally, this module implements the few functions that the
  18. //              Info-ZIP code expects the port to implement. These functions are
  19. //              OS dependent and are mostly related to validating file names and
  20. //              directoies, and setting file attributes and dates of saved files.
  21. //
  22. // Copyright:   All the source files for Pocket UnZip, except for components
  23. //              written by the Info-ZIP group, are copyrighted 1997 by Steve P.
  24. //              Miller.  The product "Pocket UnZip" itself is property of the
  25. //              author and cannot be altered in any way without written consent
  26. //              from Steve P. Miller.
  27. //
  28. // Disclaimer:  All project files are provided "as is" with no guarantee of
  29. //              their correctness.  The authors are not liable for any outcome
  30. //              that is the result of using this source.  The source for Pocket
  31. //              UnZip has been placed in the public domain to help provide an
  32. //              understanding of its implementation.  You are hereby granted
  33. //              full permission to use this source in any way you wish, except
  34. //              to alter Pocket UnZip itself.  For comments, suggestions, and
  35. //              bug reports, please write to stevemil@pobox.com.
  36. //
  37. // Functions:   DoListFiles
  38. //              DoExtractOrTestFiles
  39. //              DoGetComment
  40. //              SetExtractToDirectory
  41. //              InitGlobals
  42. //              FreeGlobals
  43. //              IsFileOrDirectory
  44. //              SmartCreateDirectory
  45. //              ExtractOrTestFilesThread
  46. //              CheckForAbort
  47. //              SetCurrentFile
  48. //              UzpMessagePrnt2
  49. //              UzpInput2
  50. //              UzpMorePause
  51. //              UzpPassword
  52. //              UzpReplace
  53. //              UzpSound
  54. //              SendAppMsg
  55. //              win_fprintf
  56. //              mapattr
  57. //              utimeToFileTime
  58. //              GetFileTimes
  59. //              close_outfile
  60. //              do_wild
  61. //              mapname
  62. //              test_NT
  63. //              checkdir
  64. //              match
  65. //              iswild
  66. //              IsOldFileSystem
  67. //
  68. //
  69. // Date      Name          History
  70. // --------  ------------  -----------------------------------------------------
  71. // 02/01/97  Steve Miller  Created (Version 1.0 using Info-ZIP UnZip 5.30)
  72. //
  73. //******************************************************************************
  74.  
  75.  
  76. //******************************************************************************
  77. #if 0 // The following information and structure are here just for reference
  78. //******************************************************************************
  79. //
  80. // The Windows CE version of Unzip builds with the following defines set:
  81. //
  82. //
  83. //    WIN32
  84. //    _WINDOWS
  85. //    UNICODE
  86. //    _UNICODE
  87. //    WIN32_LEAN_AND_MEAN
  88. //    STRICT
  89. //
  90. //    POCKET_UNZIP         (Main define - Always set)
  91. //
  92. //    UNZIP_INTERNAL
  93. //    WINDLL
  94. //    DLL
  95. //    REENTRANT
  96. //    USE_EF_UT_TIME
  97. //    NO_ZIPINFO
  98. //    NO_STDDEF_H
  99. //    NO_NTSD_EAS
  100. //
  101. //    USE_SMITH_CODE       (optional - See COPYING document)
  102. //    USE_UNSHRINK         (optional - See COPYING document)
  103. //
  104. //    DEBUG                (When building for Debug)
  105. //    _DEBUG               (When building for Debug)
  106. //    NDEBUG               (When building for Retail)
  107. //    _NDEBUG              (When building for Retail)
  108. //
  109. //    _WIN32_WCE=100       (When building for Windows CE native)
  110. //
  111. // This causes our Globals structure to look like the following.  The only
  112. // things we care about is this Globals structure, the process_zipfiles()
  113. // function, and a few callback functions.  The Info-ZIP code has not been
  114. // been modified in any way.
  115. //
  116.  
  117. typedef struct Globals {
  118.    zvoid         *callerglobs;          // points to pass-through global vars
  119.    UzpOpts        UzO;                  // command options structure
  120.    int            prompt_always;        // prompt to overwrite if TRUE
  121.    int            noargs;               // did true command line have *any* arguments?
  122.    unsigned       filespecs;            // number of real file specifications to be matched
  123.    unsigned       xfilespecs;           // number of excluded filespecs to be matched
  124.    int            process_all_files;
  125.    int            create_dirs;          // used by main(), mapname(), checkdir()
  126.    int            extract_flag;
  127.    int            newzip;               // reset in extract.c; used in crypt.c
  128.    LONGINT        real_ecrec_offset;
  129.    LONGINT        expect_ecrec_offset;
  130.    long           csize;                // used by decompr. (NEXTBYTE): must be signed
  131.    long           ucsize;               // used by unReduce(), explode()
  132.    long           used_csize;           // used by extract_or_test_member(), explode()
  133.    int            fValidate;            // true if only validating an archive
  134.    int            filenotfound;
  135.    int            redirect_data;        // redirect data to memory buffer
  136.    int            redirect_text;        // redirect text output to buffer
  137.    int            redirect_slide;       // redirect decompression area to mem buffer
  138.    unsigned       _wsize;
  139.    unsigned       redirect_size;
  140.    uch           *redirect_buffer;
  141.    uch           *redirect_pointer;
  142.    uch           *redirect_sldptr;      // head of decompression slide buffer
  143.    char         **pfnames;
  144.    char         **pxnames;
  145.    char           sig[4];
  146.    char           answerbuf[10];
  147.    min_info       info[DIR_BLKSIZ];
  148.    min_info      *pInfo;
  149.    union work     area;                 // see unzpriv.h for definition of work
  150.    ZCONST ulg near *crc_32_tab;
  151.    ulg            crc32val;             // CRC shift reg. (was static in funzip)
  152.    uch           *inbuf;                // input buffer (any size is OK)
  153.    uch           *inptr;                // pointer into input buffer
  154.    int            incnt;
  155.    ulg            bitbuf;
  156.    int            bits_left;            // unreduce and unshrink only
  157.    int            zipeof;
  158.    char          *argv0;                // used for NT and EXE_EXTENSION
  159.    char          *wildzipfn;
  160.    char          *zipfn;                // GRR:  MSWIN:  must nuke any malloc'd zipfn...
  161.    int            zipfd;                // zipfile file handle
  162.    LONGINT        ziplen;
  163.    LONGINT        cur_zipfile_bufstart; // extract_or_test, readbuf, ReadByte
  164.    LONGINT        extra_bytes;          // used in unzip.c, misc.c
  165.    uch           *extra_field;          // Unix, VMS, Mac, OS/2, Acorn, ...
  166.    uch           *hold;
  167.  
  168.    local_file_hdr lrec;                 // used in unzip.c, extract.c
  169.    cdir_file_hdr  crec;                 // used in unzip.c, extract.c, misc.c
  170.    ecdir_rec      ecrec;                // used in unzip.c, extract.c
  171.    struct stat    statbuf;              // used by main, mapname, check_for_newer
  172.  
  173.    int            mem_mode;
  174.    uch           *outbufptr;            // extract.c static
  175.    ulg            outsize;              // extract.c static
  176.    int            reported_backslash;   // extract.c static
  177.    int            disk_full;
  178.    int            newfile;
  179.  
  180.    int            didCRlast;            // fileio static
  181.    ulg            numlines;             // fileio static: number of lines printed
  182.    int            sol;                  // fileio static: at start of line
  183.    int            no_ecrec;             // process static
  184.    FILE          *outfile;
  185.    uch           *outbuf;
  186.    uch           *realbuf;
  187.  
  188.    uch           *outbuf2;              //  main() (never changes); else malloc'd
  189.    uch           *outptr;
  190.    ulg            outcnt;               // number of chars stored in outbuf
  191.    char           filename[FILNAMSIZ];
  192.  
  193.    char          *key;                  // crypt static: decryption password or NULL
  194.    int            nopwd;                // crypt static
  195.    ulg            keys[3];              // crypt static: keys defining pseudo-random sequence
  196.  
  197.    unsigned       hufts;                // track memory usage
  198.  
  199.    struct huft   *fixed_tl;             // inflate static
  200.    struct huft   *fixed_td;             // inflate static
  201.    int            fixed_bl
  202.    int            fixed_bd;             // inflate static
  203.    unsigned       wp;                   // inflate static: current position in slide
  204.    ulg            bb;                   // inflate static: bit buffer
  205.    unsigned       bk;                   // inflate static: bits in bit buffer
  206.    MsgFn         *message;
  207.    InputFn       *input;
  208.    PauseFn       *mpause;
  209.    PasswdFn      *decr_passwd;
  210.    StatCBFn      *statreportcb;
  211.    LPUSERFUNCTIONS lpUserFunctions;
  212.  
  213.    int            incnt_leftover;       // so improved NEXTBYTE does not waste input
  214.    uch           *inptr_leftover;
  215.  
  216.    // These are defined in PUNZIP.H.
  217.    char           matchname[FILNAMSIZ]; // used by do_wild()
  218.    int            notfirstcall;         // used by do_wild()
  219.    char          *zipfnPtr;
  220.    char          *wildzipfnPtr;
  221. } Uz_Globs;
  222.  
  223. #endif // #if 0 - This struct is here just for reference
  224.  
  225. //******************************************************************************
  226.  
  227. extern "C" {
  228. #define __INTRFACE_CPP__
  229. #define UNZIP_INTERNAL
  230. #include "unzip.h"
  231. #include "crypt.h"     // Needed to pick up CRYPT define
  232. #include <commctrl.h>
  233. #include "intrface.h"
  234. #include "winmain.h"
  235.  
  236. #ifndef _WIN32_WCE
  237. #include <process.h>   // _beginthreadex() and _endthreadex()
  238. #endif
  239.  
  240. }
  241. #include <tchar.h> // Must be outside of extern "C" block
  242.  
  243.  
  244. //******************************************************************************
  245. //***** "Local" Global Variables
  246. //******************************************************************************
  247.  
  248. static USERFUNCTIONS  g_uf;
  249. static EXTRACT_INFO  *g_pExtractInfo = NULL;
  250. static FILE_NODE     *g_pFileLast    = NULL;
  251. static CHAR           g_szExtractToDirectory[_MAX_PATH];
  252. static BOOL           g_fOutOfMemory;
  253.  
  254. //******************************************************************************
  255. //***** Local Function Prototypes
  256. //******************************************************************************
  257.  
  258. extern "C" {
  259.  
  260. // Our exposed interface functions to the Info-ZIP core.
  261. BOOL DoListFiles(LPCSTR szZipFile);
  262. BOOL DoExtractOrTestFiles(LPCSTR szZipFile, EXTRACT_INFO *pei);
  263. BOOL DoGetComment(LPCSTR szFile);
  264. BOOL SetExtractToDirectory(LPTSTR szDirectory);
  265.  
  266. // Internal functions.
  267. Uz_Globs* InitGlobals(LPCSTR szZipFile);
  268. void FreeGlobals(Uz_Globs *pG);
  269. int IsFileOrDirectory(LPCTSTR szPath);
  270. BOOL SmartCreateDirectory(Uz_Globs *pG, LPCSTR szDirectory);
  271.  
  272. #ifdef _WIN32_WCE
  273. DWORD WINAPI ExtractOrTestFilesThread(LPVOID lpv);
  274. #else
  275. unsigned __stdcall ExtractOrTestFilesThread(void *lpv);
  276. #endif
  277.  
  278. void CheckForAbort(Uz_Globs *pG);
  279. void SetCurrentFile(Uz_Globs *pG);
  280.  
  281. // Callbacks from Info-ZIP code.
  282. int UzpMessagePrnt2(zvoid *pG, uch *buffer, ulg size, int flag);
  283. int UzpInput2(zvoid *pG, uch *buffer, int *size, int flag);
  284. void UzpMorePause(zvoid *pG, const char *szPrompt, int flag);
  285. int UzpPassword(zvoid *pG, int *pcRetry, char *szPassword, int nSize,
  286.                 const char *szZipFile, const char *szFile);
  287. int WINAPI UzpReplace(char *szFile);
  288. void WINAPI UzpSound(void);
  289. void WINAPI SendAppMsg(ulg dwSize, ulg dwCompressedSize, int ratio, int month,
  290.                        int day, int year, int hour, int minute, int uppercase,
  291.                        char *szPath, char *szMethod, ulg dwCRC);
  292. int win_fprintf(FILE *file, unsigned int dwCount, char far *buffer);
  293.  
  294. // Functions that Info-ZIP expects the port to write and export.
  295. void utimeToFileTime(time_t ut, FILETIME *pft, BOOL fOldFileSystem);
  296. int GetFileTimes(Uz_Globs *pG, FILETIME *pftCreated, FILETIME *pftAccessed,
  297.                  FILETIME *pftModified);
  298. int mapattr(Uz_Globs *pG);
  299. void close_outfile(Uz_Globs *pG);
  300. char* do_wild(Uz_Globs *pG, char *wildspec);
  301. int mapname(Uz_Globs *pG, int renamed);
  302. int test_NT(Uz_Globs *pG, uch *eb, unsigned eb_size);
  303. int checkdir(Uz_Globs *pG, char *pathcomp, int flag);
  304.  
  305. // Check for FAT, VFAT, HPFS, etc.
  306. BOOL IsOldFileSystem(char *szPath);
  307.  
  308. } // extern "C"
  309.  
  310.  
  311. //******************************************************************************
  312. //***** Our exposed interface functions to the Info-ZIP core
  313. //******************************************************************************
  314.  
  315. int DoListFiles(LPCSTR szZipFile) {
  316.  
  317.    int result;
  318.  
  319.    // Create our Globals struct and fill it in whith some default values.
  320.    Uz_Globs *pG = InitGlobals(szZipFile);
  321.    if (!pG) {
  322.       return PK_MEM;
  323.    }
  324.  
  325.    pG->UzO.vflag = 1; // verbosely: list directory (for WIN32 it is 0 or 1)
  326.    pG->process_all_files = TRUE; // improves speed
  327.  
  328.    g_pFileLast = NULL;
  329.    g_fOutOfMemory = FALSE;
  330.  
  331.    // We wrap some exception handling around the entire Info-ZIP engine to be
  332.    // safe.  Since we are running on a device with tight memory configurations,
  333.    // all sorts of problems can arise when we run out of memory.
  334.    __try {
  335.  
  336.       // Call the unzip routine.  We will catch the file information in a
  337.       // callback to SendAppMsg().
  338.       result = process_zipfiles(pG);
  339.  
  340.       // Make sure we didn't run out of memory in the process.
  341.       if (g_fOutOfMemory) {
  342.          result = PK_MEM;
  343.       }
  344.  
  345.    } __except(EXCEPTION_EXECUTE_HANDLER) {
  346.  
  347.       // Catch any exception here.
  348.       DebugOut(TEXT("Exception 0x%08X occurred in DoListFiles()"),
  349.                GetExceptionCode());
  350.       result = PK_EXCEPTION;
  351.    }
  352.  
  353.    g_pFileLast = NULL;
  354.  
  355.    // It is possible that the ZIP engine change the file name a bit (like adding
  356.    // a ".zip" if needed).  If so, we will pick up the new name.
  357.    if ((result != PK_EXCEPTION) && pG->zipfn && *pG->zipfn) {
  358.       strcpy(g_szZipFile, pG->zipfn);
  359.    }
  360.  
  361.    // Free our globals.
  362.    FreeGlobals(pG);
  363.  
  364.    return result;
  365. }
  366.  
  367. //******************************************************************************
  368. BOOL DoExtractOrTestFiles(LPCSTR szZipFile, EXTRACT_INFO *pei) {
  369.  
  370.    // WARNING!!!  This functions hands the EXTRACT_INFO structure of to a thread
  371.    // to perform the actual extraction/test.  When the thread is done, it will
  372.    // send a message to the progress dialog.  The calling function must not
  373.    // delete the EXTRAT_INFO structure until it receives the message.  Currently,
  374.    // this is not a problem for us since the structure lives on the stack of the
  375.    // calling thread.  The calling thread then displays a dialog that blocks the
  376.    // calling thread from clearing the stack until the dialog is dismissed, which
  377.    // occurs when the dialog receives the message.
  378.  
  379.    // Create our globals so we can store the file name.
  380.    Uz_Globs *pG = InitGlobals(szZipFile);
  381.    if (!pG) {
  382.       pei->result = PK_MEM;
  383.       SendMessage(g_hDlgProgress, WM_PRIVATE, MSG_OPERATION_COMPLETE, (LPARAM)pei);
  384.       return FALSE;
  385.    }
  386.  
  387.    // Store a global pointer to the Extract structure so it can be reached from
  388.    // our thread and callback functions.
  389.    g_pExtractInfo = pei;
  390.  
  391.    // Spawn our thread
  392.    DWORD dwThreadId;
  393.    HANDLE hThread;
  394.  
  395. #ifdef _WIN32_WCE
  396.  
  397.    // On CE, we use good old CreateThread() since the WinCE CRT does not
  398.    // allocate per-thread storage.
  399.    hThread = CreateThread(NULL, 0, ExtractOrTestFilesThread, pG, 0, &dwThreadId);
  400.  
  401. #else
  402.  
  403.    // On NT, we need use the CRT's thread function so that we don't leak any
  404.    // CRT allocated memory when the thread exits.
  405.    hThread = (HANDLE)_beginthreadex(NULL, 0, ExtractOrTestFilesThread, pG, 0,
  406.                                     (unsigned*)&dwThreadId);
  407.  
  408. #endif
  409.  
  410.    // Bail out if our thread failed to create.
  411.    if (!hThread) {
  412.  
  413.       DebugOut(TEXT("CreateThread() failed [%u]"), GetLastError());
  414.  
  415.       // Set our error as a memory error.
  416.       g_pExtractInfo->result = PK_MEM;
  417.  
  418.       // Free our globals.
  419.       FreeGlobals(pG);
  420.  
  421.       // Tell the progress dialog that we are done.
  422.       SendMessage(g_hDlgProgress, WM_PRIVATE, MSG_OPERATION_COMPLETE, (LPARAM)pei);
  423.  
  424.       g_pExtractInfo = NULL;
  425.       return FALSE;
  426.    }
  427.  
  428.    // Close our thread handle since we have no use for it.
  429.    CloseHandle(hThread);
  430.    return TRUE;
  431. }
  432.  
  433. //******************************************************************************
  434. int DoGetComment(LPCSTR szFile) {
  435.  
  436.    int result;
  437.  
  438.    // Create our Globals struct and fill it in whith some default values.
  439.    Uz_Globs *pG = InitGlobals(szFile);
  440.    if (!pG) {
  441.       return PK_MEM;
  442.    }
  443.  
  444.    pG->UzO.zflag = TRUE; // display the zipfile comment
  445.  
  446.    // We wrap some exception handling around the entire Info-ZIP engine to be
  447.    // safe.  Since we are running on a device with tight memory configurations,
  448.    // all sorts of problems can arise when we run out of memory.
  449.    __try {
  450.  
  451.       // Call the unzip routine.  We will catch the comment string in a callback
  452.       // to win_fprintf().
  453.       result = process_zipfiles(pG);
  454.  
  455.    } __except(EXCEPTION_EXECUTE_HANDLER) {
  456.  
  457.       // Catch any exception here.
  458.       DebugOut(TEXT("Exception 0x%08X occurred in DoGetComment()"),
  459.                GetExceptionCode());
  460.       result = PK_EXCEPTION;
  461.    }
  462.  
  463.    // Free our globals.
  464.    FreeGlobals(pG);
  465.  
  466.    return result;
  467. }
  468.  
  469. //******************************************************************************
  470. BOOL SetExtractToDirectory(LPTSTR szDirectory) {
  471.  
  472.    BOOL fNeedToAddWack = FALSE;
  473.  
  474.    // Remove any trailing wack from the path.
  475.    int length = _tcslen(szDirectory);
  476.    if ((length > 0) && (szDirectory[length - 1] == TEXT('\\'))) {
  477.       szDirectory[--length] = TEXT('\0');
  478.       fNeedToAddWack = TRUE;
  479.    }
  480.  
  481. #ifndef _WIN32_WCE
  482.  
  483.    // Check to see if a root directory was specified.
  484.    if ((length == 2) && isalpha(szDirectory[0]) && (szDirectory[1] == ':')) {
  485.  
  486.       // If just a root is specified, we need to only verify the drive letter.
  487.       if (!(GetLogicalDrives() & (1 << (tolower(szDirectory[0]) - (int)'a')))) {
  488.  
  489.          // This drive does not exist.  Bail out with a failure.
  490.          return FALSE;
  491.       }
  492.  
  493.    } else
  494.  
  495. #endif
  496.  
  497.    // We only verify path if length is >0 since we know "\" is valid.
  498.    if (length > 0) {
  499.  
  500.       // Verify the the path exists and that it is a directory.
  501.       if (IsFileOrDirectory(szDirectory) != 2) {
  502.          return FALSE;
  503.       }
  504.    }
  505.  
  506.    // Store the directory for when we do an extract.
  507.    wcstombs(g_szExtractToDirectory, szDirectory, countof(g_szExtractToDirectory));
  508.  
  509.    // We always want a wack at the end of our path.
  510.    strcat(g_szExtractToDirectory, "\\");
  511.  
  512.    // Add the wack back to the end of the path.
  513.    if (fNeedToAddWack) {
  514.       _tcscat(szDirectory, TEXT("\\"));
  515.    }
  516.  
  517.    return TRUE;
  518. }
  519.  
  520. //******************************************************************************
  521. //***** Internal functions
  522. //******************************************************************************
  523.  
  524. Uz_Globs* InitGlobals(LPCSTR szZipFile) {
  525.  
  526.    // Create our global structure - pG
  527.    CONSTRUCTGLOBALS();
  528.  
  529.    // Bail out if we failed to allocate our Globals structure.
  530.    if (!pG) {
  531.       return NULL;
  532.    }
  533.  
  534.    // Store a global pointer to our USERFUNCTIONS structure so that LIST.C,
  535.    // PROCESS.C, and WINMAIN can access it.
  536.    pG->lpUserFunctions = &g_uf;
  537.  
  538.    // Clear our USERFUNCTIONS structure and assign our SendAppMsg() function.
  539.    ZeroMemory(&g_uf, sizeof(g_uf));
  540.    g_uf.SendApplicationMessage = SendAppMsg;
  541.  
  542.    // Fill in all our callback functions.
  543.    pG->message     = UzpMessagePrnt2;
  544.    pG->input       = UzpInput2;
  545.    pG->mpause      = UzpMorePause;
  546.    pG->lpUserFunctions->replace     = UzpReplace;
  547.    pG->lpUserFunctions->sound       = UzpSound;
  548.  
  549. #if CRYPT
  550.    pG->decr_passwd = UzpPassword;
  551. #endif
  552.  
  553.    // Match filenames case-sensitively.  We can do this since we can guarentee
  554.    // exact case because the user can only select files via our UI.
  555.    pG->UzO.C_flag = FALSE;
  556.  
  557.    // Allocate and store the ZIP file name in pG->zipfn
  558.    if (!(pG->zipfnPtr = new char[FILNAMSIZ])) {
  559.       FreeGlobals(pG);
  560.       return NULL;
  561.    }
  562.    pG->zipfn = pG->zipfnPtr;
  563.    strcpy(pG->zipfn, szZipFile);
  564.  
  565.    // Allocate and store the ZIP file name in pG->zipfn.  This needs to done
  566.    // so that do_wild() does not wind up clearing out the zip file name when
  567.    // it returns in process.c
  568.    if (!(pG->wildzipfnPtr = new char[FILNAMSIZ])) {
  569.       FreeGlobals(pG);
  570.       return NULL;
  571.    }
  572.    pG->wildzipfn = pG->wildzipfnPtr;
  573.    strcpy(pG->wildzipfn, szZipFile);
  574.  
  575.    return pG;
  576. }
  577.  
  578. //******************************************************************************
  579. void FreeGlobals(Uz_Globs *pG) {
  580.  
  581.    // Free our ZIP file name
  582.    if (pG->zipfnPtr) {
  583.       delete[] pG->zipfnPtr;
  584.       pG->zipfnPtr = pG->zipfn = NULL;
  585.    }
  586.  
  587.    // Free our wild name buffer
  588.    if (pG->wildzipfnPtr) {
  589.       delete[] pG->wildzipfnPtr;
  590.       pG->wildzipfnPtr = pG->wildzipfn = NULL;
  591.    }
  592.  
  593.    // Free everything else.
  594.    DESTROYGLOBALS()
  595. }
  596.  
  597. //******************************************************************************
  598. int IsFileOrDirectory(LPCTSTR szPath) {
  599.  
  600.    // Geth the attributes of the item.
  601.    DWORD dwAttribs = GetFileAttributes(szPath);
  602.  
  603.    // Bail out now if we could not find the path at all.
  604.    if (dwAttribs == 0xFFFFFFFF) {
  605.       return 0;
  606.    }
  607.  
  608.    // Return 1 for file and 2 for directory.
  609.    return ((dwAttribs & FILE_ATTRIBUTE_DIRECTORY) ? 2 : 1);
  610. }
  611.  
  612. //******************************************************************************
  613. BOOL SmartCreateDirectory(Uz_Globs *pG, LPCSTR szDirectory) {
  614.  
  615.    // Copy path to a UNICODE buffer.
  616.    TCHAR szBuffer[_MAX_PATH];
  617.    mbstowcs(szBuffer, szDirectory, countof(szBuffer));
  618.  
  619.    int x = IsFileOrDirectory(szBuffer);
  620.  
  621.    // Create the directory if it does not exist.
  622.    if (x == 0) {
  623.       if (!CreateDirectory(szBuffer, NULL)) {
  624.          Info(slide, 1, ((char *)slide, "error creating directory: %s\n", szDirectory));
  625.          return FALSE;
  626.       }
  627.  
  628.    // If there is a file with the same name, then display an error.
  629.    } else if (x == 1) {
  630.       Info(slide, 1, ((char *)slide,
  631.            "cannot create %s as a file with same name already exists.\n",
  632.            szDirectory));
  633.       return FALSE;
  634.    }
  635.  
  636.    // If the directory already exists or was created, then return success.
  637.    return TRUE;
  638. }
  639.  
  640. //******************************************************************************
  641. #ifdef _WIN32_WCE
  642.  
  643. // On WinCE, we declare our thread function the way CreateThread() likes it.
  644. DWORD WINAPI ExtractOrTestFilesThread(LPVOID lpv) {
  645.  
  646. #else
  647.  
  648. // On WinNT, we declare our thread function the way _beginthreadex likes it.
  649. unsigned __stdcall ExtractOrTestFilesThread(void *lpv) {
  650.  
  651. #endif
  652.  
  653.    Uz_Globs *pG = (Uz_Globs*)lpv;
  654.  
  655.    if (g_pExtractInfo->fExtract) {
  656.  
  657.       pG->extract_flag = TRUE;
  658.  
  659.       switch (g_pExtractInfo->overwriteMode) {
  660.  
  661.          case OM_NEWER:         // Update (extract only newer/brand-new files)
  662.             pG->UzO.uflag = TRUE;
  663.             break;
  664.  
  665.          case OM_ALWAYS:        // OK to overwrite files without prompting
  666.             pG->UzO.overwrite_all = TRUE;
  667.             break;
  668.  
  669.          case OM_NEVER:         // Never overwrite files (no prompting)
  670.             pG->UzO.overwrite_none = TRUE;
  671.             break;
  672.  
  673.          default:               // Force a prompt
  674.             pG->prompt_always = TRUE;
  675.             break;
  676.       }
  677.  
  678.       // Throw away paths if requested.
  679.       pG->UzO.jflag = !g_pExtractInfo->fRestorePaths;
  680.  
  681.    } else {
  682.       pG->UzO.tflag = TRUE;
  683.    }
  684.  
  685.    if (g_pExtractInfo->szFileList) {
  686.       pG->filespecs = g_pExtractInfo->dwFileCount;
  687.       pG->pfnames = g_pExtractInfo->szFileList;
  688.    } else {
  689.       // Improves performance if all files are being extracted.
  690.       pG->process_all_files = TRUE;
  691.    }
  692.  
  693.    // Invalidate our file offset to show that we are starting a new operation.
  694.    g_pExtractInfo->dwFileOffset = 0xFFFFFFFF;
  695.  
  696.    // We wrap some exception handling around the entire Info-ZIP engine to be
  697.    // safe.  Since we are running on a device with tight memory configurations,
  698.    // all sorts of problems can arise when we run out of memory.
  699.    __try {
  700.  
  701.       // Put a jump marker on our stack so the user can abort.
  702.       int error = setjmp(dll_error_return);
  703.  
  704.       // If setjmp() returns 0, then we just set our jump marker and we can
  705.       // continue with the operation.  If setjmp() returned something else,
  706.       // then we reached this point because the operation was aborted and
  707.       // set our instruction pointer back here.
  708.  
  709.       if (error > 0) {
  710.          // We already called process_zipfiles() and were thrown back here.
  711.          g_pExtractInfo->result = (error == 1) ? PK_BADERR : error;
  712.  
  713.       } else {
  714.          // Entering Info-ZIP... close your eyes.
  715.          g_pExtractInfo->result = process_zipfiles(pG);
  716.       }
  717.  
  718.    } __except(EXCEPTION_EXECUTE_HANDLER) {
  719.  
  720.       // Catch any exception here.
  721.       DebugOut(TEXT("Exception 0x%08X occurred in ExtractOrTestFilesThread()"),
  722.                GetExceptionCode());
  723.       g_pExtractInfo->result = PK_EXCEPTION;
  724.    }
  725.  
  726.    // Free our globals.
  727.    FreeGlobals(pG);
  728.  
  729.    // Tell the progress dialog that we are done.
  730.    SendMessage(g_hDlgProgress, WM_PRIVATE, MSG_OPERATION_COMPLETE,
  731.                (LPARAM)g_pExtractInfo);
  732.  
  733.    // Clear our global pointer as we are done with it.
  734.    g_pExtractInfo = NULL;
  735.  
  736. #ifndef _WIN32_WCE
  737.    // On NT, we need to free any CRT allocated memory.
  738.    _endthreadex(0);
  739. #endif
  740.  
  741.    return 0;
  742. }
  743.  
  744. //******************************************************************************
  745. void CheckForAbort(Uz_Globs *pG) {
  746.    if (g_pExtractInfo->fAbort) {
  747.  
  748.       // Add a newline to our log if we are in the middle of a line of text.
  749.       if (!g_pExtractInfo->fNewLineOfText) {
  750.          SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT, (LPARAM)"\n");
  751.       }
  752.  
  753.       // Make sure whatever file we are currently processing gets closed.
  754.       if (((int)pG->outfile != 0) && ((int)pG->outfile != -1)) {
  755.          if (g_pExtractInfo->fExtract && *pG->filename) {
  756.  
  757.             // Make sure the user is aware that this file is screwed.
  758.             SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT,
  759.                         (LPARAM)"warning: ");
  760.             SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT,
  761.                         (LPARAM)pG->filename);
  762.             SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT,
  763.                         (LPARAM)" is probably truncated.\n");
  764.          }
  765.  
  766.          // Close the file.
  767.          close_outfile(pG);
  768.       }
  769.  
  770.       // Display an aborted message in the log
  771.       SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT,
  772.                   (LPARAM)"Operation aborted by user.\n");
  773.  
  774.       // I hate to do this... Take a giant step out of here.
  775.       longjmp(dll_error_return, PK_ABORTED);
  776.    }
  777. }
  778.  
  779. //******************************************************************************
  780. void SetCurrentFile(Uz_Globs *pG) {
  781.  
  782.    // Reset all our counters as we about to process a new file.
  783.    g_pExtractInfo->dwFileOffset = (DWORD)pG->pInfo->offset;
  784.    g_pExtractInfo->dwFile++;
  785.    g_pExtractInfo->dwBytesWrittenThisFile = 0;
  786.    g_pExtractInfo->dwBytesWrittenPreviousFiles += g_pExtractInfo->dwBytesTotalThisFile;
  787.    g_pExtractInfo->dwBytesTotalThisFile = pG->ucsize;
  788.    g_pExtractInfo->szFile = pG->filename;
  789.    g_pExtractInfo->fNewLineOfText = TRUE;
  790.  
  791.    // Pass control to our GUI thread to do a full update our progress dialog.
  792.    SendMessage(g_hWndMain, WM_PRIVATE, MSG_UPDATE_PROGRESS_COMPLETE,
  793.                (LPARAM)g_pExtractInfo);
  794.  
  795.    // Check our abort flag.
  796.    CheckForAbort(pG);
  797. }
  798.  
  799.  
  800. //******************************************************************************
  801. //***** Callbacks from Info-ZIP code.
  802. //******************************************************************************
  803.  
  804. int UzpMessagePrnt2(zvoid *pG, uch *buffer, ulg size, int flag) {
  805.  
  806.    // Some ZIP files cause us to get called during DoListFiles(). We only handle
  807.    // messages while processing DoExtractFiles().
  808.    if (!g_pExtractInfo) {
  809.       if (g_hWndEdit) {
  810.          SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT,
  811.                      (LPARAM)buffer);
  812.       } else {
  813.          DebugOut(TEXT("Unhandled call to UzpMessagePrnt2(\"%S\")"), buffer);
  814.       }
  815.       return 0;
  816.    }
  817.  
  818.    // When extracting, mapname() will get called for every file which in turn
  819.    // will call SetCurrentFile().  For testing though, mapname() never gets
  820.    // called so we need to be on the lookout for a new file.
  821.    if (g_pExtractInfo->dwFileOffset != (DWORD)((Uz_Globs*)pG)->pInfo->offset) {
  822.       SetCurrentFile((Uz_Globs*)pG);
  823.    }
  824.  
  825.    // Make sure this message was inteded for us to display.
  826.    if (!MSG_NO_WGUI(flag) && !MSG_NO_WDLL(flag)) {
  827.  
  828.       // Insert a leading newline if requested to do so.
  829.       if (MSG_LNEWLN(flag) && !g_pExtractInfo->fNewLineOfText) {
  830.          SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT, (LPARAM)"\n");
  831.          g_pExtractInfo->fNewLineOfText = TRUE;
  832.       }
  833.  
  834.       // Since we use a proportional font, we need to do a little cleanup of the
  835.       // text we are passed since it assumes a fixed font and adds padding to try
  836.       // to line things up.  We remove leading whitespace on any new line of text.
  837.       if (g_pExtractInfo->fNewLineOfText) {
  838.          while (*buffer == ' ') {
  839.             buffer++;
  840.          }
  841.       }
  842.  
  843.       // We always remove trailing whitespace.
  844.       LPSTR psz = (LPSTR)buffer + strlen((LPSTR)buffer) - 1;
  845.       while ((psz >= (LPSTR)buffer) && (*psz == ' ')) {
  846.          *(psz--) = '\0';
  847.       }
  848.  
  849.       // Determine if the next line of text will be a new line of text.
  850.       g_pExtractInfo->fNewLineOfText = ((*psz == '\r') || (*psz == '\n'));
  851.  
  852.       // Change all forward slashes to back slashes in the buffer
  853.       ForwardSlashesToBackSlashesA((LPSTR)buffer);
  854.  
  855.       // Add the cleaned-up text to our extraction log edit control.
  856.       SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT, (LPARAM)buffer);
  857.  
  858.       // Append a trailing newline if requested to do so.
  859.       if (MSG_TNEWLN(flag) || MSG_MNEWLN(flag) && !g_pExtractInfo->fNewLineOfText) {
  860.          SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT, (LPARAM)"\n");
  861.          g_pExtractInfo->fNewLineOfText = TRUE;
  862.       }
  863.    }
  864.  
  865.    return 0;
  866. }
  867.  
  868. //******************************************************************************
  869. int UzpInput2(zvoid *pG, uch *buffer, int *size, int flag) {
  870.    DebugOut(TEXT("WARNING: UzpInput2(...) called"));
  871.    return 0;
  872. }
  873.  
  874. //******************************************************************************
  875. void UzpMorePause(zvoid *pG, const char *szPrompt, int flag) {
  876.    DebugOut(TEXT("WARNING: UzpMorePause(...) called"));
  877. }
  878.  
  879. //******************************************************************************
  880. int UzpPassword(zvoid *pG, int *pcRetry, char *szPassword, int nSize,
  881.                 const char *szZipFile, const char *szFile)
  882. {
  883.    // Return Values:
  884.    //    IZ_PW_ENTERED    got some PWD string, use/try it
  885.    //    IZ_PW_CANCEL     no password available (for this entry)
  886.    //    IZ_PW_CANCELALL  no password, skip any further PWD request
  887.    //    IZ_PW_ERROR      failure (no mem, no tty, ...)
  888.  
  889. #if CRYPT
  890.  
  891.    // Build the data structure for our dialog.
  892.    DECRYPT_INFO di;
  893.    di.retry      = *pcRetry;
  894.    di.szPassword = szPassword;
  895.    di.nSize      = nSize;
  896.    di.szFile     = szFile;
  897.  
  898.    // Clear the password to be safe.
  899.    *di.szPassword = '\0';
  900.  
  901.    // On our first call for a file, *pcRetry == 0.  If we would like to allow
  902.    // for retries, then we set the value of *pcRetry to the number of retries we
  903.    // are willing to allow.  We will be recalled as neccessary, each time with
  904.    // *pcRetry being decremented once.  1 is the last retry we will get.
  905.    *pcRetry = (*pcRetry == 0) ? MAX_PASSWORD_RETRIES : (*pcRetry - 1);
  906.  
  907.    // Pass control to our GUI thread which will prompt the user for a password.
  908.    return SendMessage(g_hWndMain, WM_PRIVATE, MSG_PROMPT_FOR_PASSWORD, (LPARAM)&di);
  909.  
  910. #else
  911.    return -2;
  912. #endif
  913. }
  914.  
  915. //******************************************************************************
  916. int WINAPI UzpReplace(char *szFile) {
  917.    // Pass control to our GUI thread which will prompt the user to overwrite.
  918.    return SendMessage(g_hWndMain, WM_PRIVATE, MSG_PROMPT_TO_REPLACE, (LPARAM)szFile);
  919. }
  920.  
  921. //******************************************************************************
  922. void WINAPI UzpSound(void) {
  923.    // Do nothing.
  924. }
  925.  
  926. //******************************************************************************
  927. // Called from LIST.C
  928. void WINAPI SendAppMsg(ulg dwSize, ulg dwCompressedSize, int ratio, int month,
  929.                        int day, int year, int hour, int minute, int uppercase,
  930.                        char *szPath, char *szMethod, ulg dwCRC)
  931. {
  932.    // If we are out of memory, then just bail since we will only make things worse.
  933.    if (g_fOutOfMemory) {
  934.       return;
  935.    }
  936.  
  937.    // We get our Globals structure and then retrieve the real file name.
  938.    GETGLOBALS()
  939.    szPath = pG->filename;
  940.  
  941.    // Allocate a FILE_NODE large enough to hold this file.
  942.    int length = strlen(szPath) + strlen(szMethod);
  943.    g_pFileLast = (FILE_NODE*)new BYTE[sizeof(FILE_NODE) + (sizeof(TCHAR) * length)];
  944.  
  945.    // Bail out if we failed to allocate the node.
  946.    if (!g_pFileLast) {
  947.       DebugOut(TEXT("Failed to create a FILE_NODE for \"%S\"."), szPath);
  948.       g_fOutOfMemory = TRUE;
  949.       return;
  950.    }
  951.  
  952.    // Fill in our node.
  953.    g_pFileLast->dwSize           = dwSize;
  954.    g_pFileLast->dwCompressedSize = dwCompressedSize;
  955.    g_pFileLast->dwCRC            = dwCRC;
  956.    g_pFileLast->szComment        = NULL;
  957.    g_pFileLast->szType           = NULL;
  958.  
  959.    // Fix the year value to contain the real year.
  960.    year += 1900;
  961.  
  962.    // Year:   0 - 4095 (12) 1111 1111 1111 0000 0000 0000 0000 0000 (0xFFF00000)
  963.    // Month:  1 -   12 ( 4) 0000 0000 0000 1111 0000 0000 0000 0000 (0x000F0000)
  964.    // Day:    1 -   31 ( 5) 0000 0000 0000 0000 1111 1000 0000 0000 (0x0000F800)
  965.    // Hour:   0 -   23 ( 5) 0000 0000 0000 0000 0000 0111 1100 0000 (0x000007C0)
  966.    // Minute: 0 -   59 ( 6) 0000 0000 0000 0000 0000 0000 0011 1111 (0x0000003F)
  967.  
  968.    // Do some bit shifting to make the date and time fit in a DWORD.
  969.    g_pFileLast->dwModified = (((DWORD)(year   & 0x0FFF) << 20) |
  970.                               ((DWORD)(month  & 0x000F) << 16) |
  971.                               ((DWORD)(day    & 0x001F) << 11) |
  972.                               ((DWORD)(hour   & 0x001F) <<  6) |
  973.                               ((DWORD)(minute & 0x003F)));
  974.  
  975.    // We need to get our globals structure to determine our attributes and
  976.    // encryption information.
  977.    g_pFileLast->dwAttributes = (pG->crec.external_file_attributes & 0xFF);
  978.    if (pG->crec.general_purpose_bit_flag & 1) {
  979.       g_pFileLast->dwAttributes |= FILE_ATTRIBUTE_ENCRYPTED;
  980.    }
  981.  
  982.    // Store the path and method in our string buffer.
  983.    strcpy(g_pFileLast->szPathAndMethod, szPath);
  984.    strcpy(g_pFileLast->szPathAndMethod + strlen(szPath) + 1, szMethod);
  985.  
  986.    // Pass the file object to our windows code to have it added to our list.
  987.    AddFileToListView(g_pFileLast);
  988. }
  989.  
  990. //******************************************************************************
  991. int win_fprintf(FILE *file, unsigned int dwCount, char far *buffer) {
  992.  
  993.    // win_fprintf() is used within Info-ZIP to write to a file as well as log
  994.    // information.  If the "file" is a real file handle (not stdout or stderr),
  995.    // then we write the data to the file and return.
  996.  
  997.    if ((file != stdout) && (file != stderr)) {
  998.  
  999.       DWORD dwBytesWriten = 0;
  1000. #ifdef _WIN32_WCE
  1001.       // On WinCE all FILEs are really HANDLEs.  See WINCE.CPP for more info.
  1002.       WriteFile((HANDLE)file, buffer, dwCount, &dwBytesWriten, NULL);
  1003. #else
  1004.       dwBytesWriten = fwrite(buffer, 1, dwCount, file);
  1005. #endif
  1006.  
  1007.       // Update our bytes written count.
  1008.       g_pExtractInfo->dwBytesWrittenThisFile += dwBytesWriten;
  1009.  
  1010.       // Pass control to our GUI thread to do a partial update our progress dialog.
  1011.       SendMessage(g_hWndMain, WM_PRIVATE, MSG_UPDATE_PROGRESS_PARTIAL,
  1012.                   (LPARAM)g_pExtractInfo);
  1013.  
  1014.       // Check our abort flag.
  1015.       GETGLOBALS();
  1016.       CheckForAbort(pG);
  1017.  
  1018.       return dwBytesWriten;
  1019.    }
  1020.  
  1021.    // Check to see if we are expecting a extraction progress string
  1022.    if (g_pExtractInfo) {
  1023.  
  1024.       // Most of our progress strings come to our UzpMessagePrnt2() callback,
  1025.       // but we occasionally get one here.  We will just forward it to
  1026.       // UzpMessagePrnt2() as if it never came here.  To do this, we need to
  1027.       // get a pointer to our Globals struct.  Calling GETGLOBALS() sort of
  1028.       // breaks us from be REENTRANT, but we don't support that anyway.
  1029.       GETGLOBALS();
  1030.       UzpMessagePrnt2(pG, (uch*)buffer, dwCount, 0);
  1031.       return dwCount;
  1032.    }
  1033.  
  1034.    // Check to see if we are expecting a zip file comment string.
  1035.    if (g_hWndEdit) {
  1036.  
  1037.       // Change all forward slashes to back slashes in the buffer
  1038.       ForwardSlashesToBackSlashesA((LPSTR)buffer);
  1039.  
  1040.       SendMessage(g_hWndMain, WM_PRIVATE, MSG_ADD_TEXT_TO_EDIT, (LPARAM)buffer);
  1041.       return dwCount;
  1042.    }
  1043.  
  1044.    // Check to see if we are expecting a compressed file comment string.
  1045.    if (g_pFileLast) {
  1046.  
  1047.       // Calcalute the size of the buffer we will need to store this comment.
  1048.       // We are going to convert all ASC values 0 - 31 (excpet tab, new line,
  1049.       // and CR) to ^char.
  1050.       int size = 1;
  1051.       for (char *p2, *p1 = buffer; *p1; p1++) {
  1052.          size += ((*p1 >= 32) || (*p1 == '\t') || (*p1 == '\r') || (*p1 == '\n')) ? 1 : 2;
  1053.       }
  1054.  
  1055.       // Allocate a comment buffer and assign it to the last file node we saw.
  1056.       if (g_pFileLast->szComment = new CHAR[size]) {
  1057.  
  1058.          // Copy while formatting.
  1059.          for (p1 = buffer, p2 = (char*)g_pFileLast->szComment; *p1; p1++) {
  1060.             if ((*p1 >= 32) || (*p1 == '\t') || (*p1 == '\r') || (*p1 == '\n')) {
  1061.                *(p2++) = *p1;
  1062.             } else {
  1063.                *(p2++) = '^';
  1064.                *(p2++) = 64 + *p1;
  1065.             }
  1066.          }
  1067.          *p2 = '\0';
  1068.       }
  1069.  
  1070.       // Update the attributes of the file node to incldue the comment attribute.
  1071.       g_pFileLast->dwAttributes |= FILE_ATTRIBUTE_COMMENT;
  1072.  
  1073.       // Clear the file node so we don't try to add another bogus comment to it.
  1074.       g_pFileLast = NULL;
  1075.  
  1076.       return dwCount;
  1077.    }
  1078.  
  1079.    if (dwCount >= _MAX_PATH) {
  1080.       buffer[_MAX_PATH] = '\0';
  1081.    }
  1082.    DebugOut(TEXT("Unhandled call to win_fprintf(\"%S\")"), buffer);
  1083.    return dwCount;
  1084. }
  1085.  
  1086.  
  1087. //******************************************************************************
  1088. //***** Functions that Info-ZIP expects the port to write and export.
  1089. //***** Some of this code was stolen from the WIN32 port and highly modified.
  1090. //******************************************************************************
  1091.  
  1092. int mapattr(Uz_Globs *pG) {
  1093.  
  1094.    // Check to see if we are extracting this file for viewing.  Currently, we do
  1095.    // this by checking the szMappedPath member of our extract info stucture
  1096.    // since we know OnActionView() is the only one who sets this member.
  1097.  
  1098.    if (g_pExtractInfo && g_pExtractInfo->szMappedPath) {
  1099.  
  1100.       // If we are extracting for view only, then we ignore the file's real
  1101.       // attributes and force the file to create as read-only.  We make the file
  1102.       // read-only to help prevent the user from making changes to the temporary
  1103.       // file and then trying to save the changes back to a file that we will
  1104.       // eventually delete.
  1105.       pG->pInfo->file_attr = FILE_ATTRIBUTE_READONLY;
  1106.  
  1107.    } else {
  1108.  
  1109.       // Store the attribute exactly as it appears for normal extraction/test.
  1110.       pG->pInfo->file_attr = (unsigned)pG->crec.external_file_attributes & 0xff;
  1111.    }
  1112.    return PK_OK;
  1113. }
  1114.  
  1115. //******************************************************************************
  1116. void utimeToFileTime(time_t ut, FILETIME *pft, BOOL fOldFileSystem) {
  1117.  
  1118.    // time_t    is a 32-bit value for the seconds since January 1, 1970
  1119.    // FILETIME  is a 64-bit value for the number of 100-nanosecond intervals since
  1120.    //           January 1, 1601
  1121.    // DWORDLONG is a 64-bit int that we can use to perform large math operations.
  1122.  
  1123.  
  1124.    // time_t has minimum of 1/1/1970.  Many file systems, such as FAT, have a
  1125.    // minimum date of 1/1/1980.  If extracting to one of those file systems and
  1126.    // out time_t is less than 1980, then we make it 1/1/1980.
  1127.    // (365 days/yr * 10 yrs + 3 leap yr days) * (60 secs * 60 mins * 24 hrs).
  1128.    if (fOldFileSystem && (ut < 0x12CFF780)) {
  1129.       ut = 0x12CFF780;
  1130.    }
  1131.  
  1132.    // Compute the FILETIME for the given time_t.
  1133.    DWORDLONG dwl = ((DWORDLONG)116444736000000000 +
  1134.                    ((DWORDLONG)ut * (DWORDLONG)10000000));
  1135.  
  1136.    // Store the return value.
  1137.    *pft = *(FILETIME*)&dwl;
  1138.  
  1139.    // Now for the next fix for old file systems.  If we are in Daylight Savings
  1140.    // Time (DST) and the file is not in DST, then we need subtract off the DST
  1141.    // bias from the filetime.  This is due to a bug in Windows (NT, CE, and 95)
  1142.    // that causes the DST bias to be added to all file times when the system
  1143.    // is in DST, even if the file is not in DST.  This only effects old file
  1144.    // systems since they store local times instead of UTC times.  Newer file
  1145.    // systems like NTFS and CEFS store UTC times.
  1146.  
  1147.    if (fOldFileSystem) {
  1148.  
  1149.       // We use the CRT's localtime() and Win32's FileTimeToLocalTime()
  1150.       // functions to compute the DST bias.  This works because localtime()
  1151.       // correctly adds the DST bias only if the file time is in DST.
  1152.       // FileTimeToLocalTime() always adds the DST bias to the time.
  1153.       // Therefore, if the functions return different results, we know we
  1154.       // are dealing with a non-DST file during a system DST.
  1155.  
  1156.       FILETIME ftCRT, ftWin32;
  1157.  
  1158.       // Get the CRT result - result is a "tm" struct.
  1159.       struct tm *ptmCRT = localtime(&ut);
  1160.  
  1161.       // Convert the "tm" struct to a FILETIME.
  1162.       SYSTEMTIME stCRT;
  1163.       ZeroMemory(&stCRT, sizeof(stCRT));
  1164.       stCRT.wYear   = ptmCRT->tm_year + 1900;
  1165.       stCRT.wMonth  = ptmCRT->tm_mon + 1;
  1166.       stCRT.wDay    = ptmCRT->tm_mday;
  1167.       stCRT.wHour   = ptmCRT->tm_hour;
  1168.       stCRT.wMinute = ptmCRT->tm_min;
  1169.       stCRT.wSecond = ptmCRT->tm_sec;
  1170.       SystemTimeToFileTime(&stCRT, &ftCRT);
  1171.  
  1172.       // Get the Win32 result - result is a FILETIME.
  1173.       if (FileTimeToLocalFileTime(pft, &ftWin32)) {
  1174.  
  1175.          // Subtract the difference from our current filetime.
  1176.          *(DWORDLONG*)pft -= *(DWORDLONG*)&ftWin32 - *(DWORDLONG*)&ftCRT;
  1177.       }
  1178.    }
  1179. }
  1180.  
  1181. //******************************************************************************
  1182. int GetFileTimes(Uz_Globs *pG, FILETIME *pftCreated, FILETIME *pftAccessed,
  1183.                  FILETIME *pftModified)
  1184. {
  1185.    // We need to check to see if this file system is limited.  This includes
  1186.    // FAT, VFAT, and HPFS.  It does not include NTFS and CEFS.  The limited
  1187.    // file systems can not support dates < 1980 and they store file local times
  1188.    // for files as opposed to UTC times.
  1189.    BOOL fOldFileSystem = IsOldFileSystem(pG->filename);
  1190.  
  1191. #ifdef USE_EF_UT_TIME  // Always true for WinCE build
  1192.  
  1193. #ifdef IZ_CHECK_TZ
  1194.    if (pG->extra_field && pG->tz_is_valid) {
  1195. #else
  1196.    if (pG->extra_field) {
  1197. #endif
  1198.  
  1199.       // Structure for Unix style actime, modtime, creatime
  1200.       iztimes z_utime;
  1201.  
  1202.       // Get any date/time we can.  This can return 0 to 3 unix time fields.
  1203.       unsigned eb_izux_flg = ef_scan_for_izux(pG->extra_field,
  1204.                                               pG->lrec.extra_field_length, 0,
  1205.                                               pG->lrec.last_mod_file_date,
  1206.                                               &z_utime, NULL);
  1207.  
  1208.       // We require at least a modified time.
  1209.       if (eb_izux_flg & EB_UT_FL_MTIME) {
  1210.  
  1211.          // We know we have a modified time, so get it first.
  1212.          utimeToFileTime(z_utime.mtime, pftModified, fOldFileSystem);
  1213.  
  1214.          // Get the accessed time if we have one.
  1215.          if (eb_izux_flg & EB_UT_FL_ATIME) {
  1216.             utimeToFileTime(z_utime.atime, pftAccessed, fOldFileSystem);
  1217.          }
  1218.  
  1219.          // Get the created time if we have one.
  1220.          if (eb_izux_flg & EB_UT_FL_CTIME) {
  1221.             utimeToFileTime(z_utime.ctime, pftCreated, fOldFileSystem);
  1222.          }
  1223.  
  1224.          // Return our flags.
  1225.          return (int)eb_izux_flg;
  1226.       }
  1227.    }
  1228.  
  1229. #endif // USE_EF_UT_TIME
  1230.  
  1231.    // If all else fails, we can resort to using the DOS date and time data.
  1232.    time_t ux_modtime = dos_to_unix_time(G.lrec.last_mod_file_date,
  1233.                                         G.lrec.last_mod_file_time);
  1234.    utimeToFileTime(ux_modtime, pftModified, fOldFileSystem);
  1235.  
  1236.    *pftAccessed = *pftModified;
  1237.  
  1238.    return (EB_UT_FL_MTIME | EB_UT_FL_ATIME);
  1239. }
  1240.  
  1241. //******************************************************************************
  1242. void close_outfile(Uz_Globs *pG) {
  1243.  
  1244.    // Get the 3 time stamps for the file.
  1245.    FILETIME ftCreated, ftAccessed, ftModified;
  1246.    int timeFlags = GetFileTimes(pG, &ftCreated, &ftAccessed, &ftModified);
  1247.  
  1248.    TCHAR szFile[_MAX_PATH];
  1249.    mbstowcs(szFile, pG->filename, countof(szFile));
  1250.  
  1251. #ifdef _WIN32_WCE
  1252.  
  1253.    // Cast the outfile to a HANDLE (since that is really what it is), and
  1254.    // flush the file.  We need to flush, because any unsaved data that is
  1255.    // written to the file during CloseHandle() will step on the work done
  1256.    // by SetFileTime().
  1257.    HANDLE hFile = (HANDLE)pG->outfile;
  1258.    FlushFileBuffers(hFile);
  1259.  
  1260. #else
  1261.  
  1262.    // Close the file and then re-open it using the Win32 CreateFile() call.
  1263.    // SetFileTime() requires a Win32 file HANDLE created with GENERIC_WRITE
  1264.    // access.
  1265.    fclose(pG->outfile);
  1266.    HANDLE hFile = CreateFile(szFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
  1267.                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1268.  
  1269. #endif
  1270.  
  1271.    // Set the file's date and time.
  1272.    if (hFile != INVALID_HANDLE_VALUE) {
  1273.  
  1274.       // Make sure we retrieved some valid time stamp(s)
  1275.       if (timeFlags) {
  1276.  
  1277.          // Set the various date and time fields.
  1278.          if (!SetFileTime(hFile,
  1279.                  (timeFlags & EB_UT_FL_CTIME) ? &ftCreated  : NULL,
  1280.                  (timeFlags & EB_UT_FL_ATIME) ? &ftAccessed : NULL,
  1281.                  (timeFlags & EB_UT_FL_MTIME) ? &ftModified : NULL))
  1282.          {
  1283.             DebugOut(TEXT("SetFileTime() failed [%u]"), GetLastError());
  1284.          }
  1285.  
  1286.       } else {
  1287.          DebugOut(TEXT("GetFileTimes() failed"));
  1288.       }
  1289.  
  1290.       // Close out file.
  1291.       CloseHandle(hFile);
  1292.  
  1293.    } else {
  1294.       DebugOut(TEXT("CreateFile() failed [%u]"), GetLastError());
  1295.    }
  1296.  
  1297.    // If the file was successfully written, then set the attributes.
  1298.    if (!pG->disk_full && !g_pExtractInfo->fAbort) {
  1299.       if (!SetFileAttributes(szFile, G.pInfo->file_attr & 0x7F)) {
  1300.          DebugOut(TEXT("SetFileAttributes() failed [%u]"), GetLastError());
  1301.       }
  1302.    }
  1303.  
  1304.    // Clear outfile so we know it is closed.
  1305.    pG->outfile = 0;
  1306.  
  1307.    return;
  1308. }
  1309.  
  1310. //******************************************************************************
  1311. // Called by PROCESS.C
  1312. char* do_wild(Uz_Globs *pG, char *wildspec) {
  1313.  
  1314.    // This is a very slimmed down version of do_wild() taken from WIN32.C.
  1315.    // Since we don't support wildcards, we basically just return the wildspec
  1316.    // passed in as the filename.
  1317.  
  1318.    // First call - must initialize everything.
  1319.    if (!pG->notfirstcall) {
  1320.       pG->notfirstcall = TRUE;
  1321.       return strcpy(pG->matchname, wildspec);
  1322.    }
  1323.  
  1324.    // Last time through - reset for new wildspec.
  1325.    pG->notfirstcall = FALSE;
  1326.  
  1327.    return (char*)NULL;
  1328. }
  1329.  
  1330. //******************************************************************************
  1331. // Called from EXTRACT.C
  1332. //
  1333. // returns:  1 - (on APPEND_NAME) truncated filename
  1334. //           2 - path doesn't exist, not allowed to create
  1335. //           3 - path doesn't exist, tried to create and failed; or
  1336. //               path exists and is not a directory, but is supposed to be
  1337. //           4 - path is too long
  1338. //          10 - can't allocate memory for filename buffers
  1339. //
  1340. // IZ_VOL_LABEL   - Path was a volume label, skip it.
  1341. // IZ_CREATED_DIR - Created a directory.
  1342. //
  1343. int mapname(Uz_Globs *pG, int renamed) {
  1344.  
  1345.    // mapname() is a great place to reset all our status counters for the next
  1346.    // file to be processed since it is called for every zip file member before
  1347.    // any work is done with that member.
  1348.    SetCurrentFile(pG);
  1349.  
  1350.    // If Volume Label, skip the "extraction" quietly
  1351.    if (pG->pInfo->vollabel) {
  1352.       return IZ_VOL_LABEL;
  1353.    }
  1354.  
  1355.    CHAR szBuffer[countof(pG->filename)] = "", *pIn, *pOut, *pLastSemi = NULL;
  1356.  
  1357.    // Initialize file path buffer with our "extract to" path.
  1358.    strcpy(szBuffer, g_szExtractToDirectory);
  1359.    pOut = szBuffer + strlen(szBuffer);
  1360.  
  1361.    // Point pIn to beginning of our internal pathname.
  1362.    // If we are junking paths, then locate the file portion of the path.
  1363.    pIn = (pG->UzO.jflag) ? (CHAR*)GetFileFromPath(pG->filename) : pG->filename;
  1364.  
  1365.    // Begin main loop through characters in filename.
  1366.    for ( ; *pIn; pIn++) {
  1367.  
  1368.       // Make sure we don't overflow our output buffer.
  1369.       if (pOut >= (szBuffer + countof(szBuffer) - 2)) {
  1370.          Info(slide, 1, ((char*)slide, "path too long: %s\n", pG->filename));
  1371.          return 4;
  1372.       }
  1373.  
  1374.       // Examine the next character in our input buffer.
  1375.       switch (*pIn) {
  1376.  
  1377.          // Check for a directory wack.
  1378.          case '/':
  1379.          case '\\':
  1380.             *pOut = '\0';
  1381.             if (!SmartCreateDirectory(pG, szBuffer)) {
  1382.                Info(slide, 1, ((char*)slide, "failure extracting: %s\n",
  1383.                     pG->filename));
  1384.                return 3;
  1385.             }
  1386.             *(pOut++) = '\\';
  1387.             pLastSemi = NULL;  // Leave any directory semi-colons alone
  1388.             break;
  1389.  
  1390.          // Check for illegal characters and replace with underscore.
  1391.          case ':':
  1392.          case '*':
  1393.          case '?':
  1394.          case '"':
  1395.          case '<':
  1396.          case '>':
  1397.          case '|':
  1398.             *(pOut++) = '_';
  1399.             break;
  1400.  
  1401.          // Check for start of VMS version.
  1402.          case ';':
  1403.             pLastSemi = pOut;  // Make note as to where we are.
  1404.             *(pOut++) = *pIn;  // Leave the semi-colon alone for now.
  1405.             break;
  1406.  
  1407.          default:
  1408.             // Allow European characters and spaces in filenames.
  1409.             *(pOut++) = ((*pIn >= 0x20) ? *pIn : '_');
  1410.       }
  1411.    }
  1412.  
  1413.    // Done with output buffer, terminate it.
  1414.    *pOut = '\0';
  1415.  
  1416.    // Remove any VMS version numbers if found (appended ";###").
  1417.    if (pLastSemi) {
  1418.  
  1419.       // Walk over all digits following the semi-colon.
  1420.       for (pOut = pLastSemi + 1; (*pOut >= '0') && (*pOut <= '9'); pOut++) {
  1421.       }
  1422.  
  1423.       // If we reached the end, then nuke the semi-colon and digits.
  1424.       if (!*pOut) {
  1425.          *pLastSemi = '\0';
  1426.       }
  1427.    }
  1428.  
  1429.    // Copy the mapped name back to the internal path buffer
  1430.    strcpy(pG->filename, szBuffer);
  1431.  
  1432.    // Fill in the mapped name buffer if the original caller requested us to.
  1433.    if (g_pExtractInfo->szMappedPath) {
  1434.       strcpy(g_pExtractInfo->szMappedPath, szBuffer);
  1435.    }
  1436.  
  1437.    // If it is a directory, then display the "creating" status text.
  1438.    if ((pOut > szBuffer) && (pOut[-1] == TEXT('\\'))) {
  1439.       Info(slide, 0, ((char *)slide, "creating: %s\n", pG->filename));
  1440.       return IZ_CREATED_DIR;
  1441.    }
  1442.  
  1443.    return PK_OK;
  1444. }
  1445.  
  1446. //******************************************************************************
  1447. // Called from EXTRACT.C
  1448. int test_NT(Uz_Globs *pG, uch *eb, unsigned eb_size) {
  1449.    // This function is called when an NT security descriptor is found in the
  1450.    // extra field.  We have nothing to do, so we just return success.
  1451.    return PK_OK;
  1452. }
  1453.  
  1454. //******************************************************************************
  1455. // Called from PROCESS.C
  1456. int checkdir(Uz_Globs *pG, char *pathcomp, int flag) {
  1457.    // This function is only called by free_G_buffers() from PROCESS.C with the
  1458.    // flag set to END.  We have nothing to do, so we just return success.
  1459.    return PK_OK;
  1460. }
  1461.  
  1462. //******************************************************************************
  1463. // Called from EXTRACT.C and LIST.C
  1464. int match(char *string, char *pattern, int ignore_case) {
  1465.    // match() for the other ports compares a file in the Zip file with some
  1466.    // command line file pattern.  In our case, we always pass in exact matches,
  1467.    // so we can simply do a string compare to see if we have a match.
  1468.    return (strcmp(string, pattern) == 0);
  1469. }
  1470.  
  1471. //******************************************************************************
  1472. // Called from PROCESS.C
  1473. int iswild(char *pattern) {
  1474.    // Our file patterns never contain wild characters.  They are always exact
  1475.    // matches of file names in our Zip file.
  1476.    return FALSE;
  1477. }
  1478.  
  1479. //******************************************************************************
  1480. //***** Functions to correct time stamp bugs on old file systems.
  1481. //******************************************************************************
  1482.  
  1483. //******************************************************************************
  1484. // Borrowed/Modified from win32.c
  1485. BOOL IsOldFileSystem(char *szPath) {
  1486.  
  1487. #ifdef _WIN32_WCE
  1488.  
  1489.    char szRoot[10];
  1490.  
  1491.    // Get the first nine characters of the path.
  1492.    strncpy(szRoot, szPath, 9);
  1493.    szRoot[9] = '\0';
  1494.  
  1495.    // Convert to uppercase to help with compare.
  1496.    _strupr(szRoot);
  1497.  
  1498.    // PC Cards are mounted off the root in a directory called "\PC Cards".
  1499.    // PC Cards are FAT, no CEOS.  We need to check if the file is being
  1500.    // extracted to the PC card.
  1501.    return !strcmp(szRoot, "\\PC CARD\\");
  1502.  
  1503. #else
  1504.  
  1505.    char szRoot[_MAX_PATH] = "\0\0\0", szFS[64];
  1506.  
  1507.    // Check to see if our path contains a drive letter.
  1508.    if (isalpha(szPath[0]) && (szPath[1] == ':') && (szPath[2] == '\\')) {
  1509.  
  1510.       // If so, then just copy the drive letter, colon, and wack to our root path.
  1511.       strncpy(szRoot, szPath, 3);
  1512.  
  1513.    } else {
  1514.  
  1515.       // Expand the path so we can get a drive letter.
  1516.       GetFullPathNameA(szPath, sizeof(szRoot), szRoot, NULL);
  1517.  
  1518.       // Make sure we actually got a drive letter back in our root path buffer..
  1519.       if (!isalpha(szRoot[0]) || (szRoot[1] != ':') || (szRoot[2] != '\\')) {
  1520.  
  1521.          // When in doubt, return TRUE.
  1522.          return TRUE;
  1523.       }
  1524.    }
  1525.  
  1526.    // NULL terminate after the wack to ensure we have just the root path.
  1527.    szRoot[3] = '\0';
  1528.  
  1529.    // Get the file system type string.
  1530.    GetVolumeInformationA(szRoot, NULL, 0, NULL, NULL, NULL, szFS, sizeof(szFS));
  1531.  
  1532.    // Ensure that the file system type string is uppercase.
  1533.    strupr(szFS);
  1534.  
  1535.    // Return true for (V)FAT and (OS/2) HPFS format.
  1536.    return !strncmp(szFS, "FAT",  3) ||
  1537.           !strncmp(szFS, "VFAT", 4) ||
  1538.           !strncmp(szFS, "HPFS", 4);
  1539.  
  1540. #endif // _WIN32_WCE
  1541. }
  1542.