VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Common/libzip/zip_utf-8.c
blob: 678912f6b4beeea3d22fbffeb0b20e1349e77730 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
  zip_utf-8.c -- UTF-8 support functions for libzip
  Copyright (C) 2011-2021 Dieter Baron and Thomas Klausner

  This file is part of libzip, a library to manipulate ZIP archives.
  The authors can be contacted at <info@libzip.org>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
  3. The names of the authors may not be used to endorse or promote
     products derived from this software without specific prior
     written permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "zipint.h"

#include <stdlib.h>


static const zip_uint16_t _cp437_to_unicode[256] = {
    /* 0x00 - 0x0F */
    0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C,

    /* 0x10 - 0x1F */
    0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,

    /* 0x20 - 0x2F */
    0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,

    /* 0x30 - 0x3F */
    0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,

    /* 0x40 - 0x4F */
    0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,

    /* 0x50 - 0x5F */
    0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F,

    /* 0x60 - 0x6F */
    0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,

    /* 0x70 - 0x7F */
    0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302,

    /* 0x80 - 0x8F */
    0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,

    /* 0x90 - 0x9F */
    0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,

    /* 0xA0 - 0xAF */
    0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,

    /* 0xB0 - 0xBF */
    0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,

    /* 0xC0 - 0xCF */
    0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,

    /* 0xD0 - 0xDF */
    0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,

    /* 0xE0 - 0xEF */
    0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,

    /* 0xF0 - 0xFF */
    0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0};

#define UTF_8_LEN_2_MASK 0xe0
#define UTF_8_LEN_2_MATCH 0xc0
#define UTF_8_LEN_3_MASK 0xf0
#define UTF_8_LEN_3_MATCH 0xe0
#define UTF_8_LEN_4_MASK 0xf8
#define UTF_8_LEN_4_MATCH 0xf0
#define UTF_8_CONTINUE_MASK 0xc0
#define UTF_8_CONTINUE_MATCH 0x80


zip_encoding_type_t
_zip_guess_encoding(zip_string_t *str, zip_encoding_type_t expected_encoding) {
    zip_encoding_type_t enc;
    const zip_uint8_t *name;
    zip_uint32_t i, j, ulen;

    if (str == NULL)
        return ZIP_ENCODING_ASCII;

    name = str->raw;

    if (str->encoding != ZIP_ENCODING_UNKNOWN)
        enc = str->encoding;
    else {
        enc = ZIP_ENCODING_ASCII;
        for (i = 0; i < str->length; i++) {
            if ((name[i] > 31 && name[i] < 128) || name[i] == '\r' || name[i] == '\n' || name[i] == '\t')
                continue;

            enc = ZIP_ENCODING_UTF8_GUESSED;
            if ((name[i] & UTF_8_LEN_2_MASK) == UTF_8_LEN_2_MATCH)
                ulen = 1;
            else if ((name[i] & UTF_8_LEN_3_MASK) == UTF_8_LEN_3_MATCH)
                ulen = 2;
            else if ((name[i] & UTF_8_LEN_4_MASK) == UTF_8_LEN_4_MATCH)
                ulen = 3;
            else {
                enc = ZIP_ENCODING_CP437;
                break;
            }

            if (i + ulen >= str->length) {
                enc = ZIP_ENCODING_CP437;
                break;
            }

            for (j = 1; j <= ulen; j++) {
                if ((name[i + j] & UTF_8_CONTINUE_MASK) != UTF_8_CONTINUE_MATCH) {
                    enc = ZIP_ENCODING_CP437;
                    goto done;
                }
            }
            i += ulen;
        }
    }

done:
    str->encoding = enc;

    if (expected_encoding != ZIP_ENCODING_UNKNOWN) {
        if (expected_encoding == ZIP_ENCODING_UTF8_KNOWN && enc == ZIP_ENCODING_UTF8_GUESSED)
            str->encoding = enc = ZIP_ENCODING_UTF8_KNOWN;

        if (expected_encoding != enc && enc != ZIP_ENCODING_ASCII)
            return ZIP_ENCODING_ERROR;
    }

    return enc;
}


static zip_uint32_t
_zip_unicode_to_utf8_len(zip_uint32_t codepoint) {
    if (codepoint < 0x0080)
        return 1;
    if (codepoint < 0x0800)
        return 2;
    if (codepoint < 0x10000)
        return 3;
    return 4;
}


static zip_uint32_t
_zip_unicode_to_utf8(zip_uint32_t codepoint, zip_uint8_t *buf) {
    if (codepoint < 0x0080) {
        buf[0] = codepoint & 0xff;
        return 1;
    }
    if (codepoint < 0x0800) {
        buf[0] = (zip_uint8_t)(UTF_8_LEN_2_MATCH | ((codepoint >> 6) & 0x1f));
        buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
        return 2;
    }
    if (codepoint < 0x10000) {
        buf[0] = (zip_uint8_t)(UTF_8_LEN_3_MATCH | ((codepoint >> 12) & 0x0f));
        buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f));
        buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
        return 3;
    }
    buf[0] = (zip_uint8_t)(UTF_8_LEN_4_MATCH | ((codepoint >> 18) & 0x07));
    buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 12) & 0x3f));
    buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f));
    buf[3] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
    return 4;
}


zip_uint8_t *
_zip_cp437_to_utf8(const zip_uint8_t *const _cp437buf, zip_uint32_t len, zip_uint32_t *utf8_lenp, zip_error_t *error) {
    zip_uint8_t *cp437buf = (zip_uint8_t *)_cp437buf;
    zip_uint8_t *utf8buf;
    zip_uint32_t buflen, i, offset;

    if (len == 0) {
        if (utf8_lenp)
            *utf8_lenp = 0;
        return NULL;
    }

    buflen = 1;
    for (i = 0; i < len; i++)
        buflen += _zip_unicode_to_utf8_len(_cp437_to_unicode[cp437buf[i]]);

    if ((utf8buf = (zip_uint8_t *)malloc(buflen)) == NULL) {
        zip_error_set(error, ZIP_ER_MEMORY, 0);
        return NULL;
    }

    offset = 0;
    for (i = 0; i < len; i++)
        offset += _zip_unicode_to_utf8(_cp437_to_unicode[cp437buf[i]], utf8buf + offset);

    utf8buf[buflen - 1] = 0;
    if (utf8_lenp)
        *utf8_lenp = buflen - 1;
    return utf8buf;
}
pan> SYSENC_STATUS_NONE = 0, SYSENC_STATUS_PRETEST = 200, // This may also mean that the OS is to be (or has been) copied to a hidden volume (to create a hidden OS). SYSENC_STATUS_ENCRYPTING = 400, SYSENC_STATUS_DECRYPTING = 600 }; enum vol_creation_wizard_modes { WIZARD_MODE_FILE_CONTAINER = 0, WIZARD_MODE_NONSYS_DEVICE, WIZARD_MODE_SYS_DEVICE }; typedef struct { BOOL VolumeIsOpen; CRYPTO_INFO *CryptoInfo; BOOL IsDevice; HANDLE HostFileHandle; uint64 HostSize; BOOL TimestampsValid; FILETIME CreationTime; FILETIME LastWriteTime; FILETIME LastAccessTime; } OpenVolumeContext; typedef enum BitLockerEncryptionStatus { BL_Status_Unknown = 0, BL_Status_Unprotected, BL_Status_Protected } BitLockerEncryptionStatus; #define DEFAULT_VOL_CREATION_WIZARD_MODE WIZARD_MODE_FILE_CONTAINER #define ICON_HAND MB_ICONHAND #define YES_NO MB_YESNO #define ISO_BURNER_TOOL L"isoburn.exe" #define PRINT_TOOL L"notepad.exe" void InitGlobalLocks (); void FinalizeGlobalLocks (); void cleanup ( void ); void LowerCaseCopy ( wchar_t *lpszDest , const wchar_t *lpszSource ); void UpperCaseCopy ( wchar_t *lpszDest , size_t cbDest, const wchar_t *lpszSource ); BOOL IsNullTerminateString (const wchar_t* str, size_t cbSize); void CreateFullVolumePath ( wchar_t *lpszDiskFile , size_t cbDiskFile, const wchar_t *lpszFileName , BOOL *bDevice ); int FakeDosNameForDevice ( const wchar_t *lpszDiskFile , wchar_t *lpszDosDevice , size_t cbDosDevice, wchar_t *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly ); int RemoveFakeDosName ( wchar_t *lpszDiskFile , wchar_t *lpszDosDevice ); void AbortProcessDirect ( wchar_t *abortMsg ); void AbortProcess ( char *stringId ); void AbortProcessSilent ( void ); void *err_malloc ( size_t size ); char *err_strdup ( char *lpszText ); DWORD handleWin32Error ( HWND hwndDlg, const char* srcPos ); BOOL IsDiskReadError (DWORD error); BOOL IsDiskWriteError (DWORD error); BOOL IsDiskError (DWORD error); BOOL translateWin32Error ( wchar_t *lpszMsgBuf , int nWSizeOfBuf ); BOOL CALLBACK AboutDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); void DisplayStaticModelessWaitDlg (HWND parent); void CloseStaticModelessWaitDlg (void); BOOL IsButtonChecked ( HWND hButton ); void CheckButton ( HWND hButton ); void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler); void InitDialog ( HWND hwndDlg ); void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess); HDC CreateMemBitmap ( HINSTANCE hInstance , HWND hwnd , wchar_t *resource ); HBITMAP RenderBitmap ( wchar_t *resource , HWND hwndDest , int x , int y , int nWidth , int nHeight , BOOL bDirectRender , BOOL bKeepAspectRatio); LRESULT CALLBACK RedTick ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); BOOL RegisterRedTick ( HINSTANCE hInstance ); BOOL UnregisterRedTick ( HINSTANCE hInstance ); LRESULT CALLBACK SplashDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); void WaitCursor ( void ); void NormalCursor ( void ); void ArrowWaitCursor ( void ); void HandCursor (); void AddComboPair (HWND hComboBox, const wchar_t *lpszItem, int value); void SelectAlgo ( HWND hComboBox , int *nCipher ); void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption, BOOL bHeaderWipe); wchar_t *GetWipeModeName (WipeAlgorithmId modeId); wchar_t *GetPathType (const wchar_t *path, BOOL bUpperCase, BOOL *bIsPartition); LRESULT CALLBACK CustomDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam ); BOOL TCCreateMutex (volatile HANDLE *hMutex, wchar_t *name); void TCCloseMutex (volatile HANDLE *hMutex); BOOL MutexExistsOnSystem (wchar_t *name); BOOL CreateSysEncMutex (void); BOOL InstanceHasSysEncMutex (void); void CloseSysEncMutex (void); BOOL CreateNonSysInplaceEncMutex (void); BOOL InstanceHasNonSysInplaceEncMutex (void); void CloseNonSysInplaceEncMutex (void); BOOL NonSysInplaceEncInProgressElsewhere (void); BOOL CreateDriverSetupMutex (void); void CloseDriverSetupMutex (void); BOOL CreateAppSetupMutex (void); BOOL InstanceHasAppSetupMutex (void); void CloseAppSetupMutex (void); BOOL IsTrueCryptInstallerRunning (void); uint32 ReadDriverConfigurationFlags (); uint32 ReadServiceConfigurationFlags (); uint32 ReadEncryptionThreadPoolFreeCpuCountLimit (); BOOL LoadSysEncSettings (); int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm); void RemoveNonSysInPlaceEncNotifications (void); void SavePostInstallTasksSettings (int command); void DoPostInstallTasks (HWND hwndDlg); void InitOSVersionInfo (); void InitApp ( HINSTANCE hInstance, wchar_t *lpszCommandLine ); void FinalizeApp (void); void InitHelpFileName (void); BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL computeVolumeID); void NotifyDriverOfPortableMode (void); int GetAvailableFixedDisks ( HWND hComboBox , char *lpszRootPath ); int GetAvailableRemovables ( HWND hComboBox , char *lpszRootPath ); int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired); int IsNonSysPartitionOnSysDrive (const wchar_t *path); BOOL CALLBACK RawDevicesDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam ); BOOL CALLBACK TextEditDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); INT_PTR TextInfoDialogBox (int nID); BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); char * GetLegalNotices (); BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); void UserEnrichRandomPool (HWND hwndDlg); BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); int DriverAttach ( void ); BOOL CALLBACK CipherTestDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam ); void ResetCipherTest ( HWND hwndDlg , int idTestCipher ); void ResetCurrentDirectory (); BOOL BrowseFiles (HWND hwndDlg, char *stringId, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter); BOOL BrowseDirectories (HWND hWnd, char *lpszTitle, wchar_t *dirName); void handleError ( HWND hwndDlg , int code, const char* srcPos ); BOOL CheckFileStreamWriteErrors (HWND hwndDlg, FILE *file, const wchar_t *fileName); void LocalizeDialog ( HWND hwnd, char *stringId ); void OpenVolumeExplorerWindow (int driveNo); static BOOL CALLBACK CloseVolumeExplorerWindowsEnum( HWND hwnd, LPARAM driveNo); BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo); BOOL UpdateDriveCustomLabel (int driveNo, wchar_t* effectiveLabel, BOOL bSetValue); BOOL CheckCapsLock (HWND hwnd, BOOL quiet); BOOL CheckFileExtension (wchar_t *fileName); BOOL IsTrueCryptFileExtension (wchar_t *fileName); void CorrectFileName (wchar_t* fileName); void CorrectURL (wchar_t* fileName); void IncreaseWrongPwdRetryCount (int count); void ResetWrongPwdRetryCount (void); BOOL WrongPwdRetryCountOverLimit (void); DWORD GetUsedLogicalDrives (void); int GetFirstAvailableDrive (); int GetLastAvailableDrive (); BOOL IsDriveAvailable (int driveNo); BOOL IsDeviceMounted (wchar_t *deviceName); int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced); void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap); int MountVolume (HWND hwndDlg, int driveNo, wchar_t *volumePath, Password *password, int pkcs5, int pim, BOOL truecryptMode, BOOL cachePassword, BOOL cachePim, BOOL sharedAccess, const MountOptions* const mountOptions, BOOL quiet, BOOL bReportWrongPassword); BOOL UnmountVolume (HWND hwndDlg , int nDosDriveNo, BOOL forceUnmount); BOOL UnmountVolumeAfterFormatExCall (HWND hwndDlg, int nDosDriveNo); BOOL IsPasswordCacheEmpty (void); BOOL IsMountedVolumeID (BYTE volumeID[VOLUME_ID_SIZE]); BOOL IsMountedVolume (const wchar_t *volname); int GetMountedVolumeDriveNo (wchar_t *volname); BOOL IsAdmin (void); BOOL IsBuiltInAdmin (); BOOL IsUacSupported (); BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName); int GetDiskDeviceDriveLetter (PWSTR deviceName); int FileSystemAppearsEmpty (const wchar_t *devicePath); __int64 GetStatsFreeSpaceOnPartition (const wchar_t *devicePath, float *percent, __int64 *occupiedBytes, BOOL silent); __int64 GetDeviceSize (const wchar_t *devicePath); HANDLE DismountDrive (wchar_t *devName, wchar_t *devicePath); int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset); BOOL FileExists (const wchar_t *filePathPtr); __int64 FindStringInFile (const wchar_t *filePath, const char *str, int strLen); BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile); BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed); typedef void (_cdecl *ProgressFn) ( HWND hwndDlg , const wchar_t *txt ); BOOL DecompressZipToDir (const unsigned char *inputBuffer, DWORD inputLength, const wchar_t *destinationFile, ProgressFn progressFnPtr, HWND hwndDlg); BOOL TCFlushFile (FILE *f); BOOL PrintHardCopyTextUTF16 (wchar_t *text, wchar_t *title, size_t byteLen); void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr); BOOL IsNonInstallMode (); BOOL DriverUnload (); LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state); BOOL GetCheckBox (HWND hwndDlg, int dlgItem); void SetListScrollHPos (HWND hList, int topMostVisibleItem); void ManageStartupSeq (void); void ManageStartupSeqWiz (BOOL bRemove, const wchar_t *arg); void CleanLastVisitedMRU (void); void ClearHistory (HWND hwndDlgItem); LRESULT ListItemAdd (HWND list, int index, const wchar_t *string); LRESULT ListSubItemSet (HWND list, int index, int subIndex, const wchar_t *string); BOOL GetMountList (MOUNT_LIST_STRUCT *list); int GetDriverRefCount (); void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr); __int64 GetFileSize64 (const wchar_t *path); BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset); BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset); char *LoadFile (const wchar_t *fileName, DWORD *size); char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count); wchar_t *GetModPath (wchar_t *path, int maxSize); wchar_t *GetConfigPath (wchar_t *fileName); wchar_t *GetProgramConfigPath (wchar_t *fileName); wchar_t GetSystemDriveLetter (void); void OpenPageHelp (HWND hwndDlg, int nPage); void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning); void InfoBalloon (char *headingStringId, char *textStringId, HWND hwnd); void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); void WarningBalloon (char *headingStringId, char *textStringId, HWND hwnd); void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString, HWND hwnd); int Info (char *stringId, HWND hwnd); int InfoTopMost (char *stringId, HWND hwnd); int InfoDirect (const wchar_t *msg, HWND hwnd); int Warning (char *stringId, HWND hwnd); int WarningTopMost (char *stringId, HWND hwnd); int WarningDirect (const wchar_t *warnMsg, HWND hwnd); int Error (char *stringId, HWND hwnd); int ErrorRetryCancel (char *stringId, HWND hwnd); int ErrorDirect (const wchar_t *errMsg, HWND hwnd); int ErrorTopMost (char *stringId, HWND hwnd); int AskYesNo (char *stringId, HWND hwnd); int AskYesNoString (const wchar_t *str, HWND hwnd); int AskYesNoTopmost (char *stringId, HWND hwnd); int AskNoYes (char *stringId, HWND hwnd); int AskNoYesString (const wchar_t *string, HWND hwnd); int AskOkCancel (char *stringId, HWND hwnd); int AskWarnYesNo (char *stringId, HWND hwnd); int AskWarnYesNoString (const wchar_t *string, HWND hwnd); int AskWarnYesNoTopmost (char *stringId, HWND hwnd); int AskWarnYesNoStringTopmost (const wchar_t *string, HWND hwnd); int AskWarnNoYes (char *stringId, HWND hwnd); int AskWarnNoYesString (const wchar_t *string, HWND hwnd); int AskWarnNoYesTopmost (char *stringId, HWND hwnd); int AskWarnOkCancel (char *stringId, HWND hwnd); int AskWarnCancelOk (char *stringId, HWND hwnd); int AskErrYesNo (char *stringId, HWND hwnd); int AskErrNoYes (char *stringId, HWND hwnd); int AskMultiChoice (void *strings[], BOOL bBold, HWND hwnd); BOOL ConfigWriteBegin (); BOOL ConfigWriteEnd (HWND hwnd); BOOL ConfigWriteString (char *configKey, char *configValue); BOOL ConfigWriteStringW (char *configKey, wchar_t *configValue); BOOL ConfigWriteInt (char *configKey, int configValue); int ConfigReadInt (char *configKey, int defaultValue); char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen); void ConfigReadCompareInt(char *configKey, int defaultValue, int* pOutputValue, BOOL bOnlyCheckModified, BOOL* pbModified); void ConfigReadCompareString (char *configKey, char *defaultValue, char *str, int maxLen, BOOL bOnlyCheckModified, BOOL *pbModified); void RestoreDefaultKeyFilesParam (void); BOOL LoadDefaultKeyFilesParam (void); void Debug (char *format, ...); void DebugMsgBox (char *format, ...); BOOL IsOSAtLeast (OSVersionEnum reqMinOS); BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack); BOOL Is64BitOs (); BOOL IsARM(); BOOL IsServerOS (); BOOL IsHiddenOSRunning (void); BOOL EnableWow64FsRedirection (BOOL enable); BOOL RestartComputer (BOOL bShutdown); void Applink (const char *dest); wchar_t *RelativePath2Absolute (wchar_t *szFileName); void HandleDriveNotReadyError (HWND hwnd); BOOL CALLBACK CloseTCWindowsEnum( HWND hwnd, LPARAM lParam); BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam); BYTE *MapResource (wchar_t *resourceType, int resourceId, PDWORD size); void InconsistencyResolved (char *msg); void ReportUnexpectedState (const char *techInfo); BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, wchar_t *lpszFileName, size_t cbFileName, BOOL keepHistory); BOOL SelectMultipleFilesNext (wchar_t *lpszFileName, size_t cbFileName); void OpenOnlineHelp (); BOOL GetPartitionInfo (const wchar_t *deviceName, PPARTITION_INFORMATION rpartInfo); BOOL GetDeviceInfo (const wchar_t *deviceName, DISK_PARTITION_INFO_STRUCT *info); BOOL GetDriveGeometry (const wchar_t *deviceName, PDISK_GEOMETRY_EX diskGeometry); BOOL GetPhysicalDriveGeometry (int driveNumber, PDISK_GEOMETRY diskGeometry); BOOL IsVolumeDeviceHosted (const wchar_t *lpszDiskFile); int CompensateXDPI (int val); int CompensateYDPI (int val); int CompensateDPIFont (int val); int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont); BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId); BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont); void DisableCloseButton (HWND hwndDlg); void EnableCloseButton (HWND hwndDlg); void ToBootPwdField (HWND hwndDlg, UINT ctrlId); void ToNormalPwdField (HWND hwndDlg, UINT ctrlId); void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont); BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize); BOOL GetSysDevicePaths (HWND hwndDlg); BOOL DoDriverInstall (HWND hwndDlg); int OpenVolume (OpenVolumeContext *context, const wchar_t *volumePath, Password *password, int pkcs5_prf, int pim, BOOL truecryptMode, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader); void CloseVolume (OpenVolumeContext *context); int ReEncryptVolumeHeader (HWND hwndDlg, char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, int pim, BOOL wipeMode); BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly); BOOL IsPagingFileWildcardActive (); BOOL DisablePagingFile (); BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); BOOL InitSecurityTokenLibrary (HWND hwndDlg); BOOL FileHasReadOnlyAttribute (const wchar_t *path); BOOL IsFileOnReadOnlyFilesystem (const wchar_t *path); void CheckFilesystem (HWND hwndDlg, int driveNo, BOOL fixErrors); BOOL BufferContainsPattern (const byte *buffer, size_t bufferSize, const byte *pattern, size_t patternSize); BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str); BOOL BufferContainsWideString (const byte *buffer, size_t bufferSize, const wchar_t *str); int AskNonSysInPlaceEncryptionResume (HWND hwndDlg, BOOL* pbDecrypt); BOOL RemoveDeviceWriteProtection (HWND hwndDlg, wchar_t *devicePath); void EnableElevatedCursorChange (HWND parent); BOOL DisableFileCompression (HANDLE file); BOOL VolumePathExists (const wchar_t *volumePath); BOOL IsWindowsIsoBurnerAvailable (); BOOL LaunchWindowsIsoBurner (HWND hwnd, const wchar_t *isoPath); BOOL IsApplicationInstalled (const wchar_t *appName); int GetPim (HWND hwndDlg, UINT ctrlId, int defaultPim); void SetPim (HWND hwndDlg, UINT ctrlId, int pim); BOOL GetPassword (HWND hwndDlg, UINT ctrlID, char* passValue, int bufSize, BOOL bLegacyPassword, BOOL bShowError); void SetPassword (HWND hwndDlg, UINT ctrlID, char* passValue); void HandleShowPasswordFieldAction (HWND hwndDlg, UINT checkBoxId, UINT edit1Id, UINT edit2Id); HKEY OpenDeviceClassRegKey (const GUID *deviceClassGuid); LSTATUS DeleteRegistryKey (HKEY, LPCTSTR); HIMAGELIST CreateImageList(int cx, int cy, UINT flags, int cInitial, int cGrow); int AddBitmapToImageList(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask); HRESULT VCStrDupW(LPCWSTR psz, LPWSTR *ppwsz); void ProcessEntropyEstimate (HWND hProgress, DWORD* pdwInitialValue, DWORD dwCounter, DWORD dwMaxLevel, DWORD* pdwEntropy); void AllowMessageInUIPI (UINT msg); BOOL IsRepeatedByteArray (byte value, const byte* buffer, size_t bufferSize); BOOL TranslateVolumeID (HWND hwndDlg, wchar_t* pathValue, size_t cchPathValue); BOOL CopyTextToClipboard (const wchar_t* txtValue); BOOL LaunchElevatedProcess (HWND hwndDlg, const wchar_t* szModPath, const wchar_t* args); BOOL GetFreeDriveLetter(WCHAR* pCh); BOOL SetPrivilege(LPTSTR szPrivilegeName, BOOL bEnable); BOOL DeleteDirectory (const wchar_t* szDirName); BOOL IsThreadInSecureDesktop(DWORD dwThreadID); INT_PTR SecureDesktopDialogBoxParam (HINSTANCE, LPCWSTR, HWND, DLGPROC, LPARAM); BOOL VerifyModuleSignature (const wchar_t* path); void GetInstallationPath (HWND hwndDlg, wchar_t* szInstallPath, DWORD cchSize, BOOL* pbInstallPathDetermined); BOOL GetSetupconfigLocation (wchar_t* path, DWORD cchSize); BOOL BufferHasPattern (const unsigned char* buffer, size_t bufferLen, const void* pattern, size_t patternLen); BOOL EnableProcessProtection(); void SafeOpenURL (LPCWSTR szUrl); BitLockerEncryptionStatus GetBitLockerEncryptionStatus(WCHAR driveLetter); #ifdef _WIN64 void GetAppRandomSeed (unsigned char* pbRandSeed, size_t cbRandSeed); #endif #ifdef __cplusplus } #include <vector> #include <string> typedef std::vector<unsigned char> ByteArray; struct HostDevice { HostDevice () : Bootable (false), ContainsSystem (false), DynamicVolume (false), Floppy (false), IsPartition (false), IsVirtualPartition (false), HasUnencryptedFilesystem (false), Removable (false), Size (0), SystemNumber((uint32) -1), HasVolumeIDs (false) { ZeroMemory (VolumeIDs, sizeof (VolumeIDs)); } HostDevice (const HostDevice& device) : Bootable (device.Bootable), ContainsSystem (device.ContainsSystem), DynamicVolume (device.DynamicVolume), Floppy (device.Floppy), IsPartition (device.IsPartition), IsVirtualPartition (device.IsVirtualPartition), HasUnencryptedFilesystem (device.HasUnencryptedFilesystem), MountPoint (device.MountPoint), Name (device.Name), Path (device.Path), Removable (device.Removable), Size (device.Size), SystemNumber (device.SystemNumber), HasVolumeIDs (device.HasVolumeIDs), Partitions (device.Partitions) { memcpy (VolumeIDs, device.VolumeIDs, sizeof (VolumeIDs)); } ~HostDevice () {} HostDevice& operator= (const HostDevice& device) { if (this != &device) { Bootable = device.Bootable; ContainsSystem = device.ContainsSystem; DynamicVolume = device.DynamicVolume; Floppy = device.Floppy; IsPartition = device.IsPartition; IsVirtualPartition = device.IsVirtualPartition; HasUnencryptedFilesystem = device.HasUnencryptedFilesystem; MountPoint = device.MountPoint; Name = device.Name; Path = device.Path; Removable = device.Removable; Size = device.Size; SystemNumber = device.SystemNumber; HasVolumeIDs = device.HasVolumeIDs; Partitions = device.Partitions; memcpy (VolumeIDs, device.VolumeIDs, sizeof (VolumeIDs)); } return *this; } bool Bootable; bool ContainsSystem; bool DynamicVolume; bool Floppy; bool IsPartition; bool IsVirtualPartition; bool HasUnencryptedFilesystem; std::wstring MountPoint; std::wstring Name; std::wstring Path; bool Removable; uint64 Size; uint32 SystemNumber; BYTE VolumeIDs[TC_VOLUME_TYPE_COUNT][VOLUME_ID_SIZE]; bool HasVolumeIDs; std::vector <HostDevice> Partitions; }; struct RawDevicesDlgParam { std::vector <HostDevice> devices; wchar_t *pszFileName; }; BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, wchar_t *initialDir, wchar_t *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter, const wchar_t *initialFileName = NULL, const wchar_t *defaultExtension = NULL); std::wstring SingleStringToWide (const std::string &singleString); std::wstring Utf8StringToWide (const std::string &utf8String); std::string WideToUtf8String (const std::wstring &wideString); std::vector <HostDevice> GetAvailableHostDevices (bool noDeviceProperties = false, bool singleList = false, bool noFloppy = true, bool detectUnencryptedFilesystems = false); std::wstring ToUpperCase (const std::wstring &str); std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg); std::wstring GetWindowsEdition (); std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path); std::wstring GetServiceConfigPath (const wchar_t *fileName, bool useLegacy); std::wstring VolumeGuidPathToDevicePath (std::wstring volumeGuidPath); std::wstring HarddiskVolumePathToPartitionPath (const std::wstring &harddiskVolumePath); std::wstring FindLatestFileOrDirectory (const std::wstring &directory, const wchar_t *namePattern, bool findDirectory, bool findFile); std::wstring GetUserFriendlyVersionString (int version); std::wstring IntToWideString (int val); std::wstring ArrayToHexWideString (const unsigned char* pbData, int cbData); bool HexWideStringToArray (const wchar_t* hexStr, std::vector<byte>& arr); std::wstring FindDeviceByVolumeID (const BYTE volumeID [VOLUME_ID_SIZE], BOOL bFromService); void RegisterDriverInf (bool registerFilter, const std::string& filter, const std::string& filterReg, HWND ParentWindow, HKEY regKey); std::wstring GetTempPathString (); void CorrectFileName (std::wstring& fileName); inline std::wstring AppendSrcPos (const wchar_t* msg, const char* srcPos) { return std::wstring (msg? msg : L"") + L"\n\nSource: " + SingleStringToWide (srcPos); } void UpdateMountableHostDeviceList (); INT_PTR TextEditDialogBox (BOOL readOnly, HWND parent, const WCHAR* Title, std::string& text); // Display a wait dialog while calling the provided callback with the given parameter typedef void (CALLBACK* WaitThreadProc)(void* pArg, HWND hWaitDlg); void BringToForeground(HWND hWnd); void ShowWaitDialog(HWND hwnd, BOOL bUseHwndAsParent, WaitThreadProc callback, void* pArg); // classes used to implement support for password drag-n-drop from KeePass Password Safe // Implementation based the following source code with many modifications to fix isses and add features // URL: https://www.codeguru.com/cpp/misc/misc/draganddrop/article.php/c349/Drag-And-Drop-between-Window-Controls.htm interface GenericDropTarget : public IDropTarget { public: GenericDropTarget(CLIPFORMAT* pFormats, size_t count); ~GenericDropTarget(); // basic IUnknown stuff HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject); ULONG STDMETHODCALLTYPE AddRef(void); ULONG STDMETHODCALLTYPE Release(void); HRESULT STDMETHODCALLTYPE DragEnter(struct IDataObject *,unsigned long,struct _POINTL,unsigned long *); HRESULT STDMETHODCALLTYPE DragOver(unsigned long,struct _POINTL,unsigned long *); HRESULT STDMETHODCALLTYPE DragLeave(void); HRESULT STDMETHODCALLTYPE Drop(struct IDataObject *,unsigned long,struct _POINTL,unsigned long *); // called by parents BOOL Register(HWND hWnd); void Revoke(); // call parent we have goodies virtual void GotDrop(CLIPFORMAT format); virtual DWORD GotDrag(void); virtual void GotLeave(void); virtual DWORD GotEnter(void); public: BYTE *m_Data; POINT m_DropPoint; DWORD m_KeyState; protected: HWND m_DropTargetWnd; std::vector<CLIPFORMAT> m_SupportedFormat; volatile LONG m_dwRefCount; }; class PasswordEditDropTarget : public GenericDropTarget { public: PasswordEditDropTarget(); // called by child we have drop void GotDrop(CLIPFORMAT format); DWORD GotDrag(void); void GotLeave(void); DWORD GotEnter(void); }; BOOL GetHibernateStatus (BOOL& bHibernateEnabled, BOOL& bHiberbootEnabled); #endif // __cplusplus #endif // TC_HEADER_DLGCODE