/* Derived from source code of TrueCrypt 7.1a, which is Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0. Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2016 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "Tcdefs.h" #include "Inflate.h" #include "SelfExtract.h" #include "Wizard.h" #include "Setup.h" #include "Crc.h" #include "Endian.h" #include "Dlgcode.h" #include "Dir.h" #include "Language.h" #include "Resource.h" #include #include #ifndef SRC_POS #define SRC_POS (__FUNCTION__ ":" TC_TO_STRING(__LINE__)) #endif #define OutputPackageFile L"VeraCrypt Setup " _T(VERSION_STRING) L".exe" #define MAG_START_MARKER "TCINSTRT" #define MAG_END_MARKER_OBFUSCATED "T/C/I/N/S/C/R/C" #define PIPE_BUFFER_LEN (4 * BYTES_PER_KB) unsigned char MagEndMarker [sizeof (MAG_END_MARKER_OBFUSCATED)]; wchar_t DestExtractPath [TC_MAX_PATH]; DECOMPRESSED_FILE Decompressed_Files [NBR_COMPRESSED_FILES]; volatile char *PipeWriteBuf = NULL; volatile HANDLE hChildStdinWrite = INVALID_HANDLE_VALUE; unsigned char *DecompressedData = NULL; void SelfExtractStartupInit (void) { DeobfuscateMagEndMarker (); } // The end marker must be included in the self-extracting exe only once, not twice (used e.g. // by IsSelfExtractingPackage()) and that's why MAG_END_MARKER_OBFUSCATED is obfuscated and // needs to be deobfuscated using this function at startup. static void DeobfuscateMagEndMarker (void) { int i; for (i = 0; i < sizeof (MAG_END_MARKER_OBFUSCATED); i += 2) MagEndMarker [i/2] = MAG_END_MARKER_OBFUSCATED [i]; MagEndMarker [i/2] = 0; } static void PkgError (wchar_t *msg) { MessageBox (NULL, msg, L"VeraCrypt", MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); } static void PkgWarning (wchar_t *msg) { MessageBox (NULL, msg, L"VeraCrypt", MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST); } static void PkgInfo (wchar_t *msg) { MessageBox (NULL, msg, L"VeraCrypt", MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST); } // Returns 0 if decompression fails or, if successful, returns the size of the decompressed data static int DecompressBuffer (char *out, char *in, int len) { return (DecompressDeflatedData (out, in, len)); // Inflate } static void __cdecl PipeWriteThread (void *len) { int sendBufSize = PIPE_BUFFER_LEN, bytesSent = 0; int bytesToSend = *((int *) len), bytesSentTotal = 0; if (PipeWriteBuf == NULL || (HANDLE) hChildStdinWrite == INVALID_HANDLE_VALUE) { PkgError (L"Failed sending data to the STDIN pipe"); return; } while (bytesToSend > 0) { if (bytesToSend < PIPE_BUFFER_LEN) sendBufSize = bytesToSend; if (!WriteFile ((HANDLE) hChildStdinWrite, (char *) PipeWriteBuf + bytesSentTotal, sendBufSize, &bytesSent, NULL) || bytesSent == 0 || bytesSent != sendBufSize) { PkgError (L"Failed sending data to the STDIN pipe"); return; } bytesToSend -= bytesSent; bytesSentTotal += bytesSent; } // Closing the pipe causes the child process to stop reading from it if (!CloseHandle (hChildStdinWrite)) { PkgError (L"Cannot close pipe"); return; } } // Returns 0 if compression fails or, if successful, the size of the compressed data static int CompressBuffer (char *out, char *in, int len) { SECURITY_ATTRIBUTES securityAttrib; DWORD bytesReceived = 0; HANDLE hChildStdoutWrite = INVALID_HANDLE_VALUE; HANDLE hChildStdoutRead = INVALID_HANDLE_VALUE; HANDLE hChildStdinRead = INVALID_HANDLE_VALUE; STARTUPINFO startupInfo; PROCESS_INFORMATION procInfo; char pipeBuffer [PIPE_BUFFER_LEN]; int res_len = 0; BOOL bGzipHeaderRead = FALSE; wchar_t szGzipCmd[64]; ZeroMemory (&startupInfo, sizeof (startupInfo)); ZeroMemory (&procInfo, sizeof (procInfo)); // Pipe handle inheritance securityAttrib.bInheritHandle = TRUE; securityAttrib.nLength = sizeof (securityAttrib); securityAttrib.lpSecurityDescriptor = NULL; if (!CreatePipe (&hChildStdoutRead, &hChildStdoutWrite, &securityAttrib, 0)) { PkgError (L"Cannot create STDOUT pipe."); return 0; } SetHandleInformation (hChildStdoutRead, HANDLE_FLAG_INHERIT, 0); if (!CreatePipe (&hChildStdinRead, &((HANDLE) hChildStdinWrite), &securityAttrib, 0)) { PkgError (L"Cannot create STDIN pipe."); CloseHandle(hChildStdoutWrite); CloseHandle(hChildStdoutRead); return 0; } SetHandleInformation (hChildStdinWrite, HANDLE_FLAG_INHERIT, 0); // Create a child process that will compress the data startupInfo.wShowWindow = SW_HIDE; startupInfo.hStdInput = hChildStdinRead; startupInfo.hStdOutput = hChildStdoutWrite; startupInfo.cb = sizeof (startupInfo); startupInfo.hStdError = hChildStdoutWrite; startupInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; StringCchCopyW (szGzipCmd, ARRAYSIZE (szGzipCmd), L"gzip --best"); if (!CreateProcess (NULL, szGzipCmd, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &procInfo)) { PkgError (L"Error: Cannot run gzip.\n\nBefore you can create a self-extracting VeraCrypt package, you need to have the open-source 'gzip' compression tool placed in any directory in the search path for executable files (for example, in 'C:\\Windows\\').\n\nNote: gzip can be freely downloaded e.g. from www.gzip.org"); CloseHandle(hChildStdoutWrite); CloseHandle(hChildStdoutRead); CloseHandle(hChildStdinRead); CloseHandle(hChildStdinWrite); return 0; } CloseHandle (procInfo.hProcess); CloseHandle (procInfo.hThread); // Start sending the uncompressed data to the pipe (STDIN) PipeWriteBuf = in; _beginthread (PipeWriteThread, PIPE_BUFFER_LEN * 2, (void *) &len); if (!CloseHandle (hChildStdoutWrite)) { PkgError (L"Cannot close STDOUT write"); CloseHandle(hChildStdoutRead); CloseHandle(hChildStdinRead); return 0; } bGzipHeaderRead = FALSE; // Read the compressed data from the pipe (sent by the child process to STDOUT) while (TRUE) { if (!ReadFile (hChildStdoutRead, pipeBuffer, bGzipHeaderRead ? PIPE_BUFFER_LEN : 10, &bytesReceived, NULL)) break; if (bGzipHeaderRead) { memcpy (out + res_len, pipeBuffer, bytesReceived); res_len += bytesReceived; } else bGzipHeaderRead = TRUE; // Skip the 10-byte gzip header } CloseHandle(hChildStdoutRead); CloseHandle(hChildStdinRead); return res_len - 8; // A gzip stream ends with a CRC-32 hash and a 32-bit size (those 8 bytes need to be chopped off) } // Clears all bytes that change when an exe file is digitally signed, except the data that are appended. // If those bytes weren't cleared, CRC-32 checks would fail after signing. static void WipeSignatureAreas (char *buffer) { // Clear bytes 0x130-0x1ff memset (buffer + 0x130, 0, 0x200 - 0x130); } BOOL MakeSelfExtractingPackage (HWND hwndDlg, wchar_t *szDestDir) { int i, x; wchar_t inputFile [TC_MAX_PATH]; wchar_t outputFile [TC_MAX_PATH]; wchar_t szTmpFilePath [TC_MAX_PATH]; unsigned char szTmp32bit [4] = {0}; unsigned char *szTmp32bitPtr = szTmp32bit; unsigned char *buffer = NULL, *compressedBuffer = NULL; unsigned char *bufIndex = NULL; wchar_t tmpStr [2048]; int bufLen = 0, compressedDataLen = 0, uncompressedDataLen = 0; x = wcslen (szDestDir); if (x < 2) goto err; if (szDestDir[x - 1] != L'\\') StringCbCatW (szDestDir, MAX_PATH, L"\\"); GetModuleFileName (NULL, inputFile, ARRAYSIZE (inputFile)); StringCchCopyW (outputFile, ARRAYSIZE(outputFile), szDestDir); StringCchCatW (outputFile, ARRAYSIZE(outputFile), OutputPackageFile); // Clone 'VeraCrypt Setup.exe' to create the base of the new self-extracting archive if (!TCCopyFile (inputFile, outputFile)) { handleWin32Error (hwndDlg, SRC_POS); PkgError (L"Cannot copy 'VeraCrypt Setup.exe' to the package"); goto err; } // Determine the buffer size needed for all the files and meta data and check if all required files exist bufLen = 0; for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) { StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); if (!FileExists (szTmpFilePath)) { wchar_t tmpstr [1000]; StringCbPrintfW (tmpstr, sizeof(tmpstr), L"File not found:\n\n'%s'", szTmpFilePath); if (_wremove (outputFile)) StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); PkgError (tmpstr); goto err; } bufLen += (int) GetFileSize64 (szTmpFilePath); bufLen += 2; // 16-bit filename length bufLen += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); // Filename bufLen += 4; // CRC-32 bufLen += 4; // 32-bit file length } buffer = malloc (bufLen + 524288); // + 512K reserve if (buffer == NULL) { PkgError (L"Cannot allocate memory for uncompressed data"); if (_wremove (outputFile)) PkgError (L"Cannot allocate memory for uncompressed data.\nFailed also to delete package file"); else PkgError (L"Cannot allocate memory for uncompressed data"); goto err; } // Write the start marker if (!SaveBufferToFile (MAG_START_MARKER, outputFile, strlen (MAG_START_MARKER), TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write the start marker\nFailed also to delete package file"); else PkgError (L"Cannot write the start marker"); goto err; } bufIndex = buffer; // Copy all required files and their meta data to the buffer for (i = 0; i < sizeof (szCompressedFiles) / sizeof (szCompressedFiles[0]); i++) { DWORD tmpFileSize; unsigned char *tmpBuffer; StringCbPrintfW (szTmpFilePath, sizeof(szTmpFilePath), L"%s%s", szDestDir, szCompressedFiles[i]); tmpBuffer = LoadFile (szTmpFilePath, &tmpFileSize); if (tmpBuffer == NULL) { wchar_t tmpstr [1000]; StringCbPrintfW (tmpstr, sizeof(tmpstr), L"Cannot load file \n'%s'", szTmpFilePath); if (_wremove (outputFile)) StringCbCatW (tmpstr, sizeof(tmpstr), L"\nFailed also to delete package file"); PkgError (tmpstr); goto err; } // Copy the filename length to the main buffer mputWord (bufIndex, (WORD) wcslen(szCompressedFiles[i])); // Copy the filename to the main buffer wmemcpy ((wchar_t*)bufIndex, szCompressedFiles[i], wcslen(szCompressedFiles[i])); bufIndex += (wcslen(szCompressedFiles[i]) * sizeof (wchar_t)); // Compute CRC-32 hash of the uncompressed file and copy it to the main buffer mputLong (bufIndex, GetCrc32 (tmpBuffer, tmpFileSize)); // Copy the file length to the main buffer mputLong (bufIndex, (unsigned __int32) tmpFileSize); // Copy the file contents to the main buffer memcpy (bufIndex, tmpBuffer, tmpFileSize); bufIndex += tmpFileSize; free (tmpBuffer); } // Calculate the total size of the uncompressed data uncompressedDataLen = (int) (bufIndex - buffer); // Write total size of the uncompressed data szTmp32bitPtr = szTmp32bit; mputLong (szTmp32bitPtr, (unsigned __int32) uncompressedDataLen); if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write the total size of the uncompressed data.\nFailed also to delete package file"); else PkgError (L"Cannot write the total size of the uncompressed data"); goto err; } // Compress all the files and meta data in the buffer to create a solid archive // Test to make Coverity happy. It will always be false if (uncompressedDataLen >= (INT_MAX - 524288)) { if (_wremove (outputFile)) PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); else PkgError (L"Cannot allocate memory for compressed data"); goto err; } compressedBuffer = malloc (uncompressedDataLen + 524288); // + 512K reserve if (compressedBuffer == NULL) { if (_wremove (outputFile)) PkgError (L"Cannot allocate memory for compressed data.\nFailed also to delete package file"); else PkgError (L"Cannot allocate memory for compressed data"); goto err; } compressedDataLen = CompressBuffer (compressedBuffer, buffer, uncompressedDataLen); if (compressedDataLen <= 0) { if (_wremove (outputFile)) PkgError (L"Failed to compress the data.\nFailed also to delete package file"); else PkgError (L"Failed to compress the data"); goto err; } free (buffer); buffer = NULL; // Write the total size of the compressed data szTmp32bitPtr = szTmp32bit; mputLong (szTmp32bitPtr, (unsigned __int32) compressedDataLen); if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); else PkgError (L"Cannot write the total size of the compressed data"); goto err; } // Write the compressed data if (!SaveBufferToFile (compressedBuffer, outputFile, compressedDataLen, TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write compressed data to the package.\nFailed also to delete package file"); else PkgError (L"Cannot write compressed data to the package"); goto err; } // Write the end marker if (!SaveBufferToFile (MagEndMarker, outputFile, strlen (MagEndMarker), TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write the end marker.\nFailed also to delete package file"); else PkgError (L"Cannot write the end marker"); goto err; } free (compressedBuffer); compressedBuffer = NULL; // Compute and write CRC-32 hash of the entire package { DWORD tmpFileSize; char *tmpBuffer; tmpBuffer = LoadFile (outputFile, &tmpFileSize); if (tmpBuffer == NULL) { handleWin32Error (hwndDlg, SRC_POS); if (_wremove (outputFile)) PkgError (L"Cannot load the package to compute CRC.\nFailed also to delete package file"); else PkgError (L"Cannot load the package to compute CRC"); goto err; } // Zero all bytes that change when the exe is digitally signed (except appended blocks). WipeSignatureAreas (tmpBuffer); szTmp32bitPtr = szTmp32bit; mputLong (szTmp32bitPtr, GetCrc32 (tmpBuffer, tmpFileSize)); free (tmpBuffer); if (!SaveBufferToFile (szTmp32bit, outputFile, sizeof (szTmp32bit), TRUE, FALSE)) { if (_wremove (outputFile)) PkgError (L"Cannot write the total size of the compressed data.\nFailed also to delete package file"); else PkgError (L"Cannot write the total size of the compressed data"); goto err; } } StringCbPrintfW (tmpStr, sizeof(tmpStr), L"Self-extracting package successfully created (%s)", outputFile); PkgInfo (tmpStr); return TRUE; err: if (buffer) free (buffer); if (compressedBuffer) free (compressedBuffer); return FALSE; } // Verifies the CRC-32 of the whole self-extracting package (except the digital signature areas, if present) BOOL VerifyPackageIntegrity (void) { int fileDataEndPos = 0; int fileDataStartPos = 0; unsigned __int32 crc = 0; unsigned char *tmpBuffer; int tmpFileSize; wchar_t path [TC_MAX_PATH]; GetModuleFileName (NULL, path, ARRAYSIZE (path)); fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); if (fileDataEndPos < 0) { Error ("DIST_PACKAGE_CORRUPTED", NULL); return FALSE; } fileDataEndPos--; fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); if (fileDataStartPos < 0) { Error ("DIST_PACKAGE_CORRUPTED", NULL); return FALSE; } fileDataStartPos += strlen (MAG_START_MARKER); if (!LoadInt32 (path, &crc, fileDataEndPos + strlen (MagEndMarker) + 1)) { Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); return FALSE; } // Compute the CRC-32 hash of the whole file (except the digital signature area, if present) tmpBuffer = LoadFile (path, &tmpFileSize); if (tmpBuffer == NULL) { Error ("CANT_VERIFY_PACKAGE_INTEGRITY", NULL); return FALSE; } // Zero all bytes that change when an exe is digitally signed (except appended blocks). WipeSignatureAreas (tmpBuffer); if (crc != GetCrc32 (tmpBuffer, fileDataEndPos + 1 + strlen (MagEndMarker))) { free (tmpBuffer); Error ("DIST_PACKAGE_CORRUPTED", NULL); return FALSE; } free (tmpBuffer); return TRUE; } // Determines whether we are a self-extracting package BOOL IsSelfExtractingPackage (void) { wchar_t path [TC_MAX_PATH]; GetModuleFileName (NULL, path, ARRAYSIZE (path)); return (FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)) != -1); } static void FreeAllFileBuffers (void) { int fileNo; if (DecompressedData != NULL) { free (DecompressedData); DecompressedData = NULL; } for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) { Decompressed_Files[fileNo].fileName = NULL; Decompressed_Files[fileNo].fileContent = NULL; Decompressed_Files[fileNo].fileNameLength = 0; Decompressed_Files[fileNo].fileLength = 0; Decompressed_Files[fileNo].crc = 0; } } // Assumes that VerifyPackageIntegrity() has been used. Returns TRUE, if successful (otherwise FALSE). // Creates a table of pointers to buffers containing the following objects for each file: // filename size, filename (not null-terminated!), file size, file CRC-32, uncompressed file contents. // For details, see the definition of the DECOMPRESSED_FILE structure. BOOL SelfExtractInMemory (wchar_t *path) { int filePos = 0, fileNo = 0; int fileDataEndPos = 0; int fileDataStartPos = 0; int uncompressedLen = 0; int compressedLen = 0; unsigned char *compressedData = NULL; unsigned char *bufPos = NULL, *bufEndPos = NULL; FreeAllFileBuffers(); fileDataEndPos = (int) FindStringInFile (path, MagEndMarker, strlen (MagEndMarker)); if (fileDataEndPos < 0) { Error ("CANNOT_READ_FROM_PACKAGE", NULL); return FALSE; } fileDataEndPos--; fileDataStartPos = (int) FindStringInFile (path, MAG_START_MARKER, strlen (MAG_START_MARKER)); if (fileDataStartPos < 0) { Error ("CANNOT_READ_FROM_PACKAGE", NULL); return FALSE; } fileDataStartPos += strlen (MAG_START_MARKER); filePos = fileDataStartPos; // Read the stored total size of the uncompressed data if (!LoadInt32 (path, &uncompressedLen, filePos)) { Error ("CANNOT_READ_FROM_PACKAGE", NULL); return FALSE; } filePos += 4; // Read the stored total size of the compressed data if (!LoadInt32 (path, &compressedLen, filePos)) { Error ("CANNOT_READ_FROM_PACKAGE", NULL); return FALSE; } filePos += 4; if (compressedLen != fileDataEndPos - fileDataStartPos - 8 + 1) { Error ("DIST_PACKAGE_CORRUPTED", NULL); } DecompressedData = malloc (uncompressedLen + 524288); // + 512K reserve if (DecompressedData == NULL) { Error ("ERR_MEM_ALLOC", NULL); return FALSE; } bufPos = DecompressedData; bufEndPos = bufPos + uncompressedLen - 1; compressedData = LoadFileBlock (path, filePos, compressedLen); if (compressedData == NULL) { free (DecompressedData); DecompressedData = NULL; Error ("CANNOT_READ_FROM_PACKAGE", NULL); return FALSE; } // Decompress the data if (DecompressBuffer (DecompressedData, compressedData, compressedLen) != uncompressedLen) { Error ("DIST_PACKAGE_CORRUPTED", NULL); goto sem_end; } while (bufPos <= bufEndPos && fileNo < NBR_COMPRESSED_FILES) { // Filename length Decompressed_Files[fileNo].fileNameLength = mgetWord (bufPos); // Filename Decompressed_Files[fileNo].fileName = (wchar_t*) bufPos; bufPos += (Decompressed_Files[fileNo].fileNameLength * sizeof (wchar_t)); // CRC-32 of the file Decompressed_Files[fileNo].crc = mgetLong (bufPos); // File length Decompressed_Files[fileNo].fileLength = mgetLong (bufPos); // File content Decompressed_Files[fileNo].fileContent = bufPos; bufPos += Decompressed_Files[fileNo].fileLength; // Verify CRC-32 of the file (to verify that it didn't get corrupted while creating the solid archive). if (Decompressed_Files[fileNo].crc != GetCrc32 (Decompressed_Files[fileNo].fileContent, Decompressed_Files[fileNo].fileLength)) { Error ("DIST_PACKAGE_CORRUPTED", NULL); goto sem_end; } fileNo++; } if (fileNo < NBR_COMPRESSED_FILES) { Error ("DIST_PACKAGE_CORRUPTED", NULL); goto sem_end; } free (compressedData); return TRUE; sem_end: FreeAllFileBuffers(); free (compressedData); return FALSE; } void __cdecl ExtractAllFilesThread (void *hwndDlg) { int fileNo; BOOL bSuccess = FALSE; wchar_t packageFile [TC_MAX_PATH]; InvalidateRect (GetDlgItem (GetParent (hwndDlg), IDD_INSTL_DLG), NULL, TRUE); ClearLogWindow (hwndDlg); GetModuleFileName (NULL, packageFile, ARRAYSIZE (packageFile)); if (!(bSuccess = SelfExtractInMemory (packageFile))) goto eaf_end; if (mkfulldir (DestExtractPath, TRUE) != 0) { if (mkfulldir (DestExtractPath, FALSE) != 0) { wchar_t szTmp[TC_MAX_PATH]; handleWin32Error (hwndDlg, SRC_POS); StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("CANT_CREATE_FOLDER"), DestExtractPath); MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONHAND); bSuccess = FALSE; goto eaf_end; } } for (fileNo = 0; fileNo < NBR_COMPRESSED_FILES; fileNo++) { wchar_t fileName [TC_MAX_PATH] = {0}; wchar_t filePath [TC_MAX_PATH] = {0}; // Filename StringCchCopyNW (fileName, ARRAYSIZE(fileName), Decompressed_Files[fileNo].fileName, Decompressed_Files[fileNo].fileNameLength); StringCchCopyW (filePath, ARRAYSIZE(filePath), DestExtractPath); StringCchCatW (filePath, ARRAYSIZE(filePath), fileName); StatusMessageParam (hwndDlg, "EXTRACTING_VERB", filePath); // Write the file if (!SaveBufferToFile ( Decompressed_Files[fileNo].fileContent, filePath, Decompressed_Files[fileNo].fileLength, FALSE, FALSE)) { wchar_t szTmp[512]; StringCbPrintfW (szTmp, sizeof (szTmp), GetString ("CANNOT_WRITE_FILE_X"), filePath); MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); bSuccess = FALSE; goto eaf_end; } UpdateProgressBarProc ((int) (100 * ((float) fileNo / NBR_COMPRESSED_FILES))); } eaf_end: FreeAllFileBuffers(); if (bSuccess) PostMessage (MainDlg, TC_APPMSG_EXTRACTION_SUCCESS, 0, 0); else PostMessage (MainDlg, TC_APPMSG_EXTRACTION_FAILURE, 0, 0); } href='#n556'>556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
/* infback.c -- inflate using a call-back interface
 * Copyright (C) 1995-2011 Mark Adler
 * For conditions of distribution and use, see copyright notice in zlib.h
 */

/*
   This code is largely copied from inflate.c.  Normally either infback.o or
   inflate.o would be linked into an application--not both.  The interface
   with inffast.c is retained so that optimized assembler-coded versions of
   inflate_fast() can be used with either inflate.c or infback.c.
 */

#include "zutil.h"
#include "inftrees.h"
#include "inflate.h"
#include "inffast.h"

/* function prototypes */
local void fixedtables OF((struct inflate_state FAR *state));

/*
   strm provides memory allocation functions in zalloc and zfree, or
   Z_NULL to use the library memory allocation functions.

   windowBits is in the range 8..15, and window is a user-supplied
   window and output buffer that is 2**windowBits bytes.
 */
int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
z_streamp strm;
int windowBits;
unsigned char FAR *window;
const char *version;
int stream_size;
{
    struct inflate_state FAR *state;

    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
        stream_size != (int)(sizeof(z_stream)))
        return Z_VERSION_ERROR;
    if (strm == Z_NULL || window == Z_NULL ||
        windowBits < 8 || windowBits > 15)
        return Z_STREAM_ERROR;
    strm->msg = Z_NULL;                 /* in case we return an error */
    if (strm->zalloc == (alloc_func)0) {
#ifdef Z_SOLO
        return Z_STREAM_ERROR;
#else
        strm->zalloc = zcalloc;
        strm->opaque = (voidpf)0;
#endif
    }
    if (strm->zfree == (free_func)0)
#ifdef Z_SOLO
        return Z_STREAM_ERROR;
#else
    strm->zfree = zcfree;
#endif
    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
                                               sizeof(struct inflate_state));
    if (state == Z_NULL) return Z_MEM_ERROR;
    Tracev((stderr, "inflate: allocated\n"));
    strm->state = (struct internal_state FAR *)state;
    state->dmax = 32768U;
    state->wbits = windowBits;
    state->wsize = 1U << windowBits;
    state->window = window;
    state->wnext = 0;
    state->whave = 0;
    return Z_OK;
}

/*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
 */
local void fixedtables(state)
struct inflate_state FAR *state;
{
#ifdef BUILDFIXED
    static int virgin = 1;
    static code *lenfix, *distfix;
    static code fixed[544];

    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
        unsigned sym, bits;
        static code *next;

        /* literal/length table */
        sym = 0;
        while (sym < 144) state->lens[sym++] = 8;
        while (sym < 256) state->lens[sym++] = 9;
        while (sym < 280) state->lens[sym++] = 7;
        while (sym < 288) state->lens[sym++] = 8;
        next = fixed;
        lenfix = next;
        bits = 9;
        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);

        /* distance table */
        sym = 0;
        while (sym < 32) state->lens[sym++] = 5;
        distfix = next;
        bits = 5;
        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);

        /* do this just once */
        virgin = 0;
    }
#else /* !BUILDFIXED */
#   include "inffixed.h"
#endif /* BUILDFIXED */
    state->lencode = lenfix;
    state->lenbits = 9;
    state->distcode = distfix;
    state->distbits = 5;
}

/* Macros for inflateBack(): */

/* Load returned state from inflate_fast() */
#define LOAD() \
    do { \
        put = strm->next_out; \
        left = strm->avail_out; \
        next = strm->next_in; \
        have = strm->avail_in; \
        hold = state->hold; \
        bits = state->bits; \
    } while (0)

/* Set state from registers for inflate_fast() */
#define RESTORE() \
    do { \
        strm->next_out = put; \
        strm->avail_out = left; \
        strm->next_in = next; \
        strm->avail_in = have; \
        state->hold = hold; \
        state->bits = bits; \
    } while (0)

/* Clear the input bit accumulator */
#define INITBITS() \
    do { \
        hold = 0; \
        bits = 0; \
    } while (0)

/* Assure that some input is available.  If input is requested, but denied,
   then return a Z_BUF_ERROR from inflateBack(). */
#define PULL() \
    do { \
        if (have == 0) { \
            have = in(in_desc, &next); \
            if (have == 0) { \
                next = Z_NULL; \
                ret = Z_BUF_ERROR; \
                goto inf_leave; \
            } \
        } \
    } while (0)

/* Get a byte of input into the bit accumulator, or return from inflateBack()
   with an error if there is no input available. */
#define PULLBYTE() \
    do { \
        PULL(); \
        have--; \
        hold += (unsigned long)(*next++) << bits; \
        bits += 8; \
    } while (0)

/* Assure that there are at least n bits in the bit accumulator.  If there is
   not enough available input to do that, then return from inflateBack() with
   an error. */
#define NEEDBITS(n) \
    do { \
        while (bits < (unsigned)(n)) \
            PULLBYTE(); \
    } while (0)

/* Return the low n bits of the bit accumulator (n < 16) */
#define BITS(n) \
    ((unsigned)hold & ((1U << (n)) - 1))

/* Remove n bits from the bit accumulator */
#define DROPBITS(n) \
    do { \
        hold >>= (n); \
        bits -= (unsigned)(n); \
    } while (0)

/* Remove zero to seven bits as needed to go to a byte boundary */
#define BYTEBITS() \
    do { \
        hold >>= bits & 7; \
        bits -= bits & 7; \
    } while (0)

/* Assure that some output space is available, by writing out the window
   if it's full.  If the write fails, return from inflateBack() with a
   Z_BUF_ERROR. */
#define ROOM() \
    do { \
        if (left == 0) { \
            put = state->window; \
            left = state->wsize; \
            state->whave = left; \
            if (out(out_desc, put, left)) { \
                ret = Z_BUF_ERROR; \
                goto inf_leave; \
            } \
        } \
    } while (0)

/*
   strm provides the memory allocation functions and window buffer on input,
   and provides information on the unused input on return.  For Z_DATA_ERROR
   returns, strm will also provide an error message.

   in() and out() are the call-back input and output functions.  When
   inflateBack() needs more input, it calls in().  When inflateBack() has
   filled the window with output, or when it completes with data in the
   window, it calls out() to write out the data.  The application must not
   change the provided input until in() is called again or inflateBack()
   returns.  The application must not change the window/output buffer until
   inflateBack() returns.

   in() and out() are called with a descriptor parameter provided in the
   inflateBack() call.  This parameter can be a structure that provides the
   information required to do the read or write, as well as accumulated
   information on the input and output such as totals and check values.

   in() should return zero on failure.  out() should return non-zero on
   failure.  If either in() or out() fails, than inflateBack() returns a
   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
   was in() or out() that caused in the error.  Otherwise,  inflateBack()
   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
   error, or Z_MEM_ERROR if it could not allocate memory for the state.
   inflateBack() can also return Z_STREAM_ERROR if the input parameters
   are not correct, i.e. strm is Z_NULL or the state was not initialized.
 */
int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
z_streamp strm;
in_func in;
void FAR *in_desc;
out_func out;
void FAR *out_desc;
{
    struct inflate_state FAR *state;
    z_const unsigned char FAR *next;    /* next input */
    unsigned char FAR *put;     /* next output */
    unsigned have, left;        /* available input and output */
    unsigned long hold;         /* bit buffer */
    unsigned bits;              /* bits in bit buffer */
    unsigned copy;              /* number of stored or match bytes to copy */
    unsigned char FAR *from;    /* where to copy match bytes from */
    code here;                  /* current decoding table entry */
    code last;                  /* parent table entry */
    unsigned len;               /* length to copy for repeats, bits to drop */
    int ret;                    /* return code */
    static const unsigned short order[19] = /* permutation of code lengths */
        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};

    /* Check that the strm exists and that the state was initialized */
    if (strm == Z_NULL || strm->state == Z_NULL)
        return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;

    /* Reset the state */
    strm->msg = Z_NULL;
    state->mode = TYPE;
    state->last = 0;
    state->whave = 0;
    next = strm->next_in;
    have = next != Z_NULL ? strm->avail_in : 0;
    hold = 0;
    bits = 0;
    put = state->window;
    left = state->wsize;

    /* Inflate until end of block marked as last */
    for (;;)
        switch (state->mode) {
        case TYPE:
            /* determine and dispatch block type */
            if (state->last) {
                BYTEBITS();
                state->mode = DONE;
                break;
            }
            NEEDBITS(3);
            state->last = BITS(1);
            DROPBITS(1);
            switch (BITS(2)) {
            case 0:                             /* stored block */
                Tracev((stderr, "inflate:     stored block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = STORED;
                break;
            case 1:                             /* fixed block */
                fixedtables(state);
                Tracev((stderr, "inflate:     fixed codes block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = LEN;              /* decode codes */
                break;
            case 2:                             /* dynamic block */
                Tracev((stderr, "inflate:     dynamic codes block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = TABLE;
                break;
            case 3:
                strm->msg = (char *)"invalid block type";
                state->mode = BAD;
            }
            DROPBITS(2);
            break;

        case STORED:
            /* get and verify stored block length */
            BYTEBITS();                         /* go to byte boundary */
            NEEDBITS(32);
            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
                strm->msg = (char *)"invalid stored block lengths";
                state->mode = BAD;
                break;
            }
            state->length = (unsigned)hold & 0xffff;
            Tracev((stderr, "inflate:       stored length %u\n",
                    state->length));
            INITBITS();

            /* copy stored block from input to output */
            while (state->length != 0) {
                copy = state->length;
                PULL();
                ROOM();
                if (copy > have) copy = have;
                if (copy > left) copy = left;
                zmemcpy(put, next, copy);
                have -= copy;
                next += copy;
                left -= copy;
                put += copy;
                state->length -= copy;
            }
            Tracev((stderr, "inflate:       stored end\n"));
            state->mode = TYPE;
            break;

        case TABLE:
            /* get dynamic table entries descriptor */
            NEEDBITS(14);
            state->nlen = BITS(5) + 257;
            DROPBITS(5);
            state->ndist = BITS(5) + 1;
            DROPBITS(5);
            state->ncode = BITS(4) + 4;
            DROPBITS(4);
#ifndef PKZIP_BUG_WORKAROUND
            if (state->nlen > 286 || state->ndist > 30) {
                strm->msg = (char *)"too many length or distance symbols";
                state->mode = BAD;
                break;
            }
#endif
            Tracev((stderr, "inflate:       table sizes ok\n"));

            /* get code length code lengths (not a typo) */
            state->have = 0;
            while (state->have < state->ncode) {
                NEEDBITS(3);
                state->lens[order[state->have++]] = (unsigned short)BITS(3);
                DROPBITS(3);
            }
            while (state->have < 19)
                state->lens[order[state->have++]] = 0;
            state->next = state->codes;
            state->lencode = (code const FAR *)(state->next);
            state->lenbits = 7;
            ret = inflate_table(CODES, state->lens, 19, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid code lengths set";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, "inflate:       code lengths ok\n"));

            /* get length and distance code code lengths */
            state->have = 0;
            while (state->have < state->nlen + state->ndist) {
                for (;;) {
                    here = state->lencode[BITS(state->lenbits)];
                    if ((unsigned)(here.bits) <= bits) break;
                    PULLBYTE();
                }
                if (here.val < 16) {
                    DROPBITS(here.bits);
                    state->lens[state->have++] = here.val;
                }
                else {
                    if (here.val == 16) {
                        NEEDBITS(here.bits + 2);
                        DROPBITS(here.bits);
                        if (state->have == 0) {
                            strm->msg = (char *)"invalid bit length repeat";
                            state->mode = BAD;
                            break;
                        }
                        len = (unsigned)(state->lens[state->have - 1]);
                        copy = 3 + BITS(2);
                        DROPBITS(2);
                    }
                    else if (here.val == 17) {
                        NEEDBITS(here.bits + 3);
                        DROPBITS(here.bits);
                        len = 0;
                        copy = 3 + BITS(3);
                        DROPBITS(3);
                    }
                    else {
                        NEEDBITS(here.bits + 7);
                        DROPBITS(here.bits);
                        len = 0;
                        copy = 11 + BITS(7);
                        DROPBITS(7);
                    }
                    if (state->have + copy > state->nlen + state->ndist) {
                        strm->msg = (char *)"invalid bit length repeat";
                        state->mode = BAD;
                        break;
                    }
                    while (copy--)
                        state->lens[state->have++] = (unsigned short)len;
                }
            }

            /* handle error breaks in while */
            if (state->mode == BAD) break;

            /* check for end-of-block code (better have one) */
            if (state->lens[256] == 0) {
                strm->msg = (char *)"invalid code -- missing end-of-block";
                state->mode = BAD;
                break;
            }

            /* build code tables -- note: do not change the lenbits or distbits
               values here (9 and 6) without reading the comments in inftrees.h
               concerning the ENOUGH constants, which depend on those values */
            state->next = state->codes;
            state->lencode = (code const FAR *)(state->next);
            state->lenbits = 9;
            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid literal/lengths set";
                state->mode = BAD;
                break;
            }
            state->distcode = (code const FAR *)(state->next);
            state->distbits = 6;
            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
                            &(state->next), &(state->distbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid distances set";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, "inflate:       codes ok\n"));
            state->mode = LEN;

        case LEN:
            /* use inflate_fast() if we have enough input and output */
            if (have >= 6 && left >= 258) {
                RESTORE();
                if (state->whave < state->wsize)
                    state->whave = state->wsize - left;
                inflate_fast(strm, state->wsize);
                LOAD();
                break;
            }

            /* get a literal, length, or end-of-block code */
            for (;;) {
                here = state->lencode[BITS(state->lenbits)];
                if ((unsigned)(here.bits) <= bits) break;
                PULLBYTE();
            }
            if (here.op && (here.op & 0xf0) == 0) {
                last = here;
                for (;;) {
                    here = state->lencode[last.val +
                            (BITS(last.bits + last.op) >> last.bits)];
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                    PULLBYTE();
                }
                DROPBITS(last.bits);
            }
            DROPBITS(here.bits);
            state->length = (unsigned)here.val;

            /* process literal */
            if (here.op == 0) {
                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                        "inflate:         literal '%c'\n" :
                        "inflate:         literal 0x%02x\n", here.val));
                ROOM();
                *put++ = (unsigned char)(state->length);
                left--;
                state->mode = LEN;
                break;
            }

            /* process end of block */
            if (here.op & 32) {
                Tracevv((stderr, "inflate:         end of block\n"));
                state->mode = TYPE;
                break;
            }

            /* invalid code */
            if (here.op & 64) {
                strm->msg = (char *)"invalid literal/length code";
                state->mode = BAD;
                break;
            }

            /* length code -- get extra bits, if any */
            state->extra = (unsigned)(here.op) & 15;
            if (state->extra != 0) {
                NEEDBITS(state->extra);
                state->length += BITS(state->extra);
                DROPBITS(state->extra);
            }
            Tracevv((stderr, "inflate:         length %u\n", state->length));

            /* get distance code */
            for (;;) {
                here = state->distcode[BITS(state->distbits)];
                if ((unsigned)(here.bits) <= bits) break;
                PULLBYTE();
            }
            if ((here.op & 0xf0) == 0) {
                last = here;
                for (;;) {
                    here = state->distcode[last.val +
                            (BITS(last.bits + last.op) >> last.bits)];
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                    PULLBYTE();
                }
                DROPBITS(last.bits);
            }
            DROPBITS(here.bits);
            if (here.op & 64) {
                strm->msg = (char *)"invalid distance code";
                state->mode = BAD;
                break;
            }
            state->offset = (unsigned)here.val;

            /* get distance extra bits, if any */
            state->extra = (unsigned)(here.op) & 15;
            if (state->extra != 0) {
                NEEDBITS(state->extra);
                state->offset += BITS(state->extra);
                DROPBITS(state->extra);
            }
            if (state->offset > state->wsize - (state->whave < state->wsize ?
                                                left : 0)) {
                strm->msg = (char *)"invalid distance too far back";
                state->mode = BAD;
                break;
            }
            Tracevv((stderr, "inflate:         distance %u\n", state->offset));

            /* copy match from window to output */
            do {
                ROOM();
                copy = state->wsize - state->offset;
                if (copy < left) {
                    from = put + copy;
                    copy = left - copy;
                }
                else {
                    from = put - state->offset;
                    copy = left;
                }
                if (copy > state->length) copy = state->length;
                state->length -= copy;
                left -= copy;
                do {
                    *put++ = *from++;
                } while (--copy);
            } while (state->length != 0);
            break;

        case DONE:
            /* inflate stream terminated properly -- write leftover output */
            ret = Z_STREAM_END;
            if (left < state->wsize) {
                if (out(out_desc, state->window, state->wsize - left))
                    ret = Z_BUF_ERROR;
            }
            goto inf_leave;

        case BAD:
            ret = Z_DATA_ERROR;
            goto inf_leave;

        default:                /* can't happen, but makes compilers happy */
            ret = Z_STREAM_ERROR;
            goto inf_leave;
        }

    /* Return unused input */
  inf_leave:
    strm->next_in = next;
    strm->avail_in = have;
    return ret;
}

int ZEXPORT inflateBackEnd(strm)
z_streamp strm;
{
    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
        return Z_STREAM_ERROR;
    ZFREE(strm, strm->state);
    strm->state = Z_NULL;
    Tracev((stderr, "inflate: end\n"));
    return Z_OK;
}