/* Legal Notice: Some portions of the source code contained in this file were derived from the source code of TrueCrypt 7.1a, which is Copyright (c) 2003-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0, also from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License Agreement for Encryption for the Masses' Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 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<windowsx.h>#include<dbghelp.h>#include<dbt.h>#include<Setupapi.h>#include<fcntl.h>#include<io.h>#include<math.h>#include<shlobj.h>#include<sys/stat.h>#include<stdlib.h>#include<time.h>#include<tchar.h>#include<Richedit.h>#if defined (TCMOUNT) || defined (VOLFORMAT)#include<Shlwapi.h>#include<process.h>#include<Tlhelp32.h>#endif#include"Resource.h"#include"Platform/Finally.h"#include"Platform/ForEach.h"#include"Apidrvr.h"#include"BootEncryption.h"#include"Combo.h"#include"Crc.h"#include"Crypto.h"#include"Dictionary.h"#include"Dlgcode.h"#include"EncryptionThreadPool.h"#include"Endian.h"#include"Format/Inplace.h"#include"Language.h"#include"Keyfiles.h"#include"Pkcs5.h"#include"Random.h"#include"Registry.h"#include"SecurityToken.h"#include"Tests.h"#include"Volumes.h"#include"Wipe.h"#include"Xml.h"#include"Xts.h"#include"Boot/Windows/BootCommon.h"#include"Progress.h"#include"zip.h"#ifdef TCMOUNT#include"Mount/Mount.h"#include"Mount/resource.h"#endif#ifdef VOLFORMAT#include"Format/Tcformat.h"#endif#ifdef SETUP#include"Setup/Setup.h"#endif#include<Setupapi.h>#include<strsafe.h>#pragma comment( lib, "setupapi.lib" )/* GPT Partition Type GUIDs */#define LOCAL_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) const GUID name = {l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8}LOCAL_DEFINE_GUID(PARTITION_ENTRY_UNUSED_GUID,0x00000000L,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00);// Entry unusedLOCAL_DEFINE_GUID(PARTITION_SYSTEM_GUID,0xC12A7328L,0xF81F,0x11D2,0xBA,0x4B,0x00,0xA0,0xC9,0x3E,0xC9,0x3B);// EFI system partitionLOCAL_DEFINE_GUID(PARTITION_MSFT_RESERVED_GUID,0xE3C9E316L,0x0B5C,0x4DB8,0x81,0x7D,0xF9,0x2D,0xF0,0x02,0x15,0xAE);// Microsoft reserved space LOCAL_DEFINE_GUID(PARTITION_BASIC_DATA_GUID,0xEBD0A0A2L,0xB9E5,0x4433,0x87,0xC0,0x68,0xB6,0xB7,0x26,0x99,0xC7);// Basic data partitionLOCAL_DEFINE_GUID(PARTITION_LDM_METADATA_GUID,0x5808C8AAL,0x7E8F,0x42E0,0x85,0xD2,0xE1,0xE9,0x04,0x34,0xCF,0xB3);// Logical Disk Manager metadata partitionLOCAL_DEFINE_GUID(PARTITION_LDM_DATA_GUID,0xAF9B60A0L,0x1431,0x4F62,0xBC,0x68,0x33,0x11,0x71,0x4A,0x69,0xAD);// Logical Disk Manager data partitionLOCAL_DEFINE_GUID(PARTITION_MSFT_RECOVERY_GUID,0xDE94BBA4L,0x06D1,0x4D40,0xA1,0x6A,0xBF,0xD5,0x01,0x79,0xD6,0xAC);// Microsoft recovery partitionLOCAL_DEFINE_GUID(PARTITION_CLUSTER_GUID,0xdb97dba9L,0x0840,0x4bae,0x97,0xf0,0xff,0xb9,0xa3,0x27,0xc7,0xe1);// Cluster metadata partitionusingnamespaceVeraCrypt;LONGDriverVersion;char*LastDialogId;wchar_tszHelpFile[TC_MAX_PATH];wchar_tszHelpFile2[TC_MAX_PATH];wchar_tSecurityTokenLibraryPath[TC_MAX_PATH];charCmdTokenPin[TC_MAX_PATH]={0};HFONThFixedDigitFont=NULL;HFONThBoldFont=NULL;HFONThTitleFont=NULL;HFONThFixedFont=NULL;HFONThUserFont=NULL;HFONThUserUnderlineFont=NULL;HFONThUserBoldFont=NULL;HFONThUserUnderlineBoldFont=NULL;HFONTWindowTitleBarFont;WCHAREditPasswordChar=0;intScreenDPI=USER_DEFAULT_SCREEN_DPI;doubleDPIScaleFactorX=1;doubleDPIScaleFactorY=1;doubleDlgAspectRatio=1;HWNDMainDlg=NULL;wchar_t*lpszTitle=NULL;BOOLSilent=FALSE;BOOLbPreserveTimestamp=TRUE;BOOLbShowDisconnectedNetworkDrives=FALSE;BOOLbHideWaitingDialog=FALSE;BOOLbCmdHideWaitingDialog=FALSE;BOOLbCmdHideWaitingDialogValid=FALSE;BOOLbUseSecureDesktop=FALSE;BOOLbCmdUseSecureDesktop=FALSE;BOOLbCmdUseSecureDesktopValid=FALSE;BOOLbStartOnLogon=FALSE;BOOLbMountDevicesOnLogon=FALSE;BOOLbMountFavoritesOnLogon=FALSE;BOOLbHistory=FALSE;// Status of detection of hidden sectors (whole-system-drive encryption). // 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash).intHiddenSectorDetectionStatus=0;OSVersionEnumnCurrentOS=WIN_UNKNOWN;intCurrentOSMajor=0;intCurrentOSMinor=0;intCurrentOSServicePack=0;BOOLRemoteSession=FALSE;BOOLUacElevated=FALSE;BOOLbPortableModeConfirmed=FALSE;// TRUE if it is certain that the instance is running in portable modeBOOLbInPlaceEncNonSysPending=FALSE;// TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup./* Globals used by Mount and Format (separately per instance) */BOOLPimEnable=FALSE;BOOLKeyFilesEnable=FALSE;KeyFile*FirstKeyFile=NULL;KeyFilesDlgParamdefaultKeyFilesParam;BOOLIgnoreWmDeviceChange=FALSE;BOOLDeviceChangeBroadcastDisabled=FALSE;BOOLLastMountedVolumeDirty;BOOLMountVolumesAsSystemFavorite=FALSE;BOOLFavoriteMountOnArrivalInProgress=FALSE;BOOLMultipleMountOperationInProgress=FALSE;BOOLWaitDialogDisplaying=FALSE;/* Handle to the device driver */HANDLEhDriver=INVALID_HANDLE_VALUE;/* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */volatileHANDLEhSysEncMutex=NULL;/* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes,such as whether an app should prompt the user whether to resume scheduled process. */volatileHANDLEhNonSysInplaceEncMutex=NULL;/* This mutex is used to prevent multiple instances of the wizard or main app from trying to install orregister the driver or from trying to launch it in portable mode at the same time. */volatileHANDLEhDriverSetupMutex=NULL;/* This mutex is used to prevent users from running the main TrueCrypt app or the wizard while an instanceof the TrueCrypt installer is running (which is also useful for enforcing restart before the apps can be used). */volatileHANDLEhAppSetupMutex=NULL;/* Critical section used to protect access to global variables used in WNetGetConnection calls */CRITICAL_SECTIONcsWNetCalls;/* Critical section used to protect access to global list of physical drives */CRITICAL_SECTIONcsMountableDevices;CRITICAL_SECTIONcsVolumeIdCandidates;staticstd::vector<HostDevice>mountableDevices;staticstd::vector<HostDevice>rawHostDeviceList;HINSTANCEhInst=NULL;HCURSORhCursor=NULL;ATOMhDlgClass,hSplashClass;/* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it(others may still read it though). */intSystemEncryptionStatus=SYSENC_STATUS_NONE;/* Only the wizard can change this value (others may only read it). */WipeAlgorithmIdnWipeMode=TC_WIPE_NONE;BOOLbSysPartitionSelected=FALSE;/* TRUE if the user selected the system partition via the Select Device dialog */BOOLbSysDriveSelected=FALSE;/* TRUE if the user selected the system drive via the Select Device dialog *//* To populate these arrays, call GetSysDevicePaths(). If they contain valid paths, bCachedSysDevicePathsValid is TRUE. */wchar_tSysPartitionDevicePath[TC_MAX_PATH];wchar_tSysDriveDevicePath[TC_MAX_PATH];wstringExtraBootPartitionDevicePath;charbCachedSysDevicePathsValid=FALSE;BOOLbHyperLinkBeingTracked=FALSE;intWrongPwdRetryCounter=0;staticFILE*ConfigFileHandle;char*ConfigBuffer;BOOLSystemFileSelectorCallPending=FALSE;DWORDSystemFileSelectorCallerThreadId;#define RANDPOOL_DISPLAY_REFRESH_INTERVAL 30#define RANDPOOL_DISPLAY_ROWS 16#define RANDPOOL_DISPLAY_COLUMNS 20HMODULEhRichEditDll=NULL;HMODULEhComctl32Dll=NULL;HMODULEhSetupDll=NULL;HMODULEhShlwapiDll=NULL;HMODULEhProfApiDll=NULL;HMODULEhUsp10Dll=NULL;HMODULEhCryptSpDll=NULL;HMODULEhUXThemeDll=NULL;HMODULEhUserenvDll=NULL;HMODULEhRsaenhDll=NULL;HMODULEhimm32dll=NULL;HMODULEhMSCTFdll=NULL;HMODULEhfltlibdll=NULL;HMODULEhframedyndll=NULL;HMODULEhpsapidll=NULL;HMODULEhsecur32dll=NULL;HMODULEhnetapi32dll=NULL;HMODULEhauthzdll=NULL;HMODULEhxmllitedll=NULL;HMODULEhmprdll=NULL;HMODULEhsppdll=NULL;HMODULEvssapidll=NULL;HMODULEhvsstracedll=NULL;HMODULEhcfgmgr32dll=NULL;HMODULEhdevobjdll=NULL;HMODULEhpowrprofdll=NULL;HMODULEhsspiclidll=NULL;HMODULEhcryptbasedll=NULL;HMODULEhdwmapidll=NULL;HMODULEhmsasn1dll=NULL;HMODULEhcrypt32dll=NULL;HMODULEhbcryptdll=NULL;HMODULEhbcryptprimitivesdll=NULL;HMODULEhMsls31=NULL;HMODULEhntmartadll=NULL;HMODULEhwinscarddll=NULL;#define FREE_DLL(h) if (h) { FreeLibrary (h); h = NULL;}#ifndef BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE#define BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE 0x00000001#endif#ifndef BASE_SEARCH_PATH_PERMANENT#define BASE_SEARCH_PATH_PERMANENT 0x00008000#endif#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800#endiftypedefBOOL(WINAPI*SetDllDirectoryPtr)(LPCWSTRlpPathName);typedefBOOL(WINAPI*SetSearchPathModePtr)(DWORDFlags);typedefBOOL(WINAPI*SetDefaultDllDirectoriesPtr)(DWORDDirectoryFlags);typedefvoid(WINAPI*InitCommonControlsPtr)(void);typedefHIMAGELIST(WINAPI*ImageList_CreatePtr)(intcx,intcy,UINTflags,intcInitial,intcGrow);typedefint(WINAPI*ImageList_AddPtr)(HIMAGELISThiml,HBITMAPhbmImage,HBITMAPhbmMask);typedefVOID(WINAPI*SetupCloseInfFilePtr)(HINFInfHandle);typedefHKEY(WINAPI*SetupDiOpenClassRegKeyPtr)(CONSTGUID*ClassGuid,REGSAMsamDesired);typedefBOOL(WINAPI*SetupInstallFromInfSectionWPtr)(HWND,HINF,PCWSTR,UINT,HKEY,PCWSTR,UINT,PSP_FILE_CALLBACK_W,PVOID,HDEVINFO,PSP_DEVINFO_DATA);typedefHINF(WINAPI*SetupOpenInfFileWPtr)(PCWSTRFileName,PCWSTRInfClass,DWORDInfStyle,PUINTErrorLine);typedefLSTATUS(STDAPICALLTYPE*SHDeleteKeyWPtr)(HKEYhkey,LPCWSTRpszSubKey);typedefHRESULT(STDAPICALLTYPE*SHStrDupWPtr)(LPCWSTRpsz,LPWSTR*ppwsz);// ChangeWindowMessageFiltertypedefBOOL(WINAPI*ChangeWindowMessageFilterPtr)(UINT,DWORD);SetDllDirectoryPtrSetDllDirectoryFn=NULL;SetSearchPathModePtrSetSearchPathModeFn=NULL;SetDefaultDllDirectoriesPtrSetDefaultDllDirectoriesFn=NULL;ImageList_CreatePtrImageList_CreateFn=NULL;ImageList_AddPtrImageList_AddFn=NULL;SetupCloseInfFilePtrSetupCloseInfFileFn=NULL;SetupDiOpenClassRegKeyPtrSetupDiOpenClassRegKeyFn=NULL;SetupInstallFromInfSectionWPtrSetupInstallFromInfSectionWFn=NULL;SetupOpenInfFileWPtrSetupOpenInfFileWFn=NULL;SHDeleteKeyWPtrSHDeleteKeyWFn=NULL;SHStrDupWPtrSHStrDupWFn=NULL;ChangeWindowMessageFilterPtrChangeWindowMessageFilterFn=NULL;/* Windows dialog class */#define WINDOWS_DIALOG_CLASS L"#32770"/* Custom class names */#define TC_DLG_CLASS L"VeraCryptCustomDlg"#define TC_SPLASH_CLASS L"VeraCryptSplashDlg"/* constant used by ChangeWindowMessageFilter calls */#ifndef MSGFLT_ADD#define MSGFLT_ADD 1#endif/* undocumented message sent during drag-n-drop */#ifndef WM_COPYGLOBALDATA#define WM_COPYGLOBALDATA 0x0049#endif/* Benchmarks */#ifndef SETUP#define BENCHMARK_MAX_ITEMS 100#define BENCHMARK_DEFAULT_BUF_SIZE BYTES_PER_MB#define HASH_FNC_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.#define PKCS5_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.#if PKCS5_BENCHMARKS && HASH_FNC_BENCHMARKS#error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE).#endifenum{BENCHMARK_TYPE_ENCRYPTION=0,BENCHMARK_TYPE_PRF,BENCHMARK_TYPE_HASH};enum{BENCHMARK_SORT_BY_NAME=0,BENCHMARK_SORT_BY_SPEED};typedefstruct{intid;wchar_tname[100];unsigned__int64encSpeed;unsigned__int64decSpeed;unsigned__int64meanBytesPerSec;}BENCHMARK_REC;BENCHMARK_RECbenchmarkTable[BENCHMARK_MAX_ITEMS];intbenchmarkTotalItems=0;intbenchmarkBufferSize=BENCHMARK_DEFAULT_BUF_SIZE;intbenchmarkLastBufferSize=BENCHMARK_DEFAULT_BUF_SIZE;intbenchmarkSortMethod=BENCHMARK_SORT_BY_SPEED;LARGE_INTEGERbenchmarkPerformanceFrequency;intbenchmarkType=BENCHMARK_TYPE_ENCRYPTION;intbenchmarkPim=-1;BOOLbenchmarkPreBoot=FALSE;BOOLbenchmarkGPT=FALSE;#endif // #ifndef SETUPtypedefstruct{void*strings;BOOLbold;}MULTI_CHOICE_DLGPROC_PARAMS;voidInitGlobalLocks(){InitializeCriticalSection(&csWNetCalls);InitializeCriticalSection(&csMountableDevices);InitializeCriticalSection(&csVolumeIdCandidates);}voidFinalizeGlobalLocks(){DeleteCriticalSection(&csWNetCalls);DeleteCriticalSection(&csMountableDevices);DeleteCriticalSection(&csVolumeIdCandidates);}voidcleanup(){burn(&CmdTokenPin,sizeof(CmdTokenPin));/* Cleanup the GDI fonts */if(hFixedFont!=NULL)DeleteObject(hFixedFont);if(hFixedDigitFont!=NULL)DeleteObject(hFixedDigitFont);if(hBoldFont!=NULL)DeleteObject(hBoldFont);if(hTitleFont!=NULL)DeleteObject(hTitleFont);if(hUserFont!=NULL)DeleteObject(hUserFont);if(hUserUnderlineFont!=NULL)DeleteObject(hUserUnderlineFont);if(hUserBoldFont!=NULL)DeleteObject(hUserBoldFont);if(hUserUnderlineBoldFont!=NULL)DeleteObject(hUserUnderlineBoldFont);/* Cleanup our dialog class */if(hDlgClass)UnregisterClassW(TC_DLG_CLASS,hInst);if(hSplashClass)UnregisterClassW(TC_SPLASH_CLASS,hInst);/* Close the device driver handle */if(hDriver!=INVALID_HANDLE_VALUE){// Unload driver mode if possible (non-install mode) if(IsNonInstallMode()){// If a dismount was forced in the lifetime of the driver, Windows may later prevent it to be loaded again from// the same path. Therefore, the driver will not be unloaded even though it was loaded in non-install mode.intdriverUnloadDisabled;DWORDdwResult;if(!DeviceIoControl(hDriver,TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED,NULL,0,&driverUnloadDisabled,sizeof(driverUnloadDisabled),&dwResult,NULL))driverUnloadDisabled=0;if(!driverUnloadDisabled)DriverUnload();else{CloseHandle(hDriver);hDriver=INVALID_HANDLE_VALUE;}}else{CloseHandle(hDriver);hDriver=INVALID_HANDLE_VALUE;}}if(ConfigBuffer!=NULL){free(ConfigBuffer);ConfigBuffer=NULL;}CoUninitialize();CloseSysEncMutex();#ifndef SETUPtry{if(SecurityToken::IsInitialized())SecurityToken::CloseLibrary();}catch(...){}EncryptionThreadPoolStop();#endifFinalizeGlobalLocks();}voidLowerCaseCopy(wchar_t*lpszDest,constwchar_t*lpszSource){size_ti=wcslen(lpszSource)+1;lpszDest[i-1]=0;while(--i>0){lpszDest[i-1]=(wchar_t)towlower(lpszSource[i-1]);}}voidUpperCaseCopy(wchar_t*lpszDest,size_tcbDest,constwchar_t*lpszSource){if(lpszDest&&cbDest){size_ti=wcslen(lpszSource);if(i>=cbDest)i=cbDest-1;lpszDest[i]=0;i++;while(--i>0){lpszDest[i-1]=(wchar_t)towupper(lpszSource[i-1]);}}}std::wstringToUpperCase(conststd::wstring&str){wstringu;foreach(wchar_tc,str){u+=(wchar_t)towupper(c);}returnu;}size_tTrimWhiteSpace(wchar_t*str){wchar_t*end,*ptr=str;size_tout_size;if(!str||*str==0)return0;// Trim leading spacewhile(iswspace(*ptr))ptr++;if(*ptr==0)// All spaces?{*str=0;return0;}// Trim trailing spaceend=str+wcslen(str)-1;while(end>ptr&&iswspace(*end))end--;end++;// Set output size to trimmed string lengthout_size=(end-ptr);// Copy trimmed string and add null terminatorwmemmove(str,ptr,out_size);str[out_size]=0;returnout_size;}BOOLIsNullTerminateString(constwchar_t*str,size_tcbSize){if(str&&cbSize){for(size_ti=0;i<cbSize;i++){if(str[i]==0)returnTRUE;}}returnFALSE;}// check the validity of a file nameBOOLIsValidFileName(constwchar_t*str){staticwchar_tinvalidChars[9]={L'<',L'>',L':',L'"',L'/',L'\\',L'|',L'?',L'*'};wchar_tc;inti;BOOLbNotDotOnly=FALSE;while((c=*str)){if(c!=L'.')bNotDotOnly=TRUE;for(i=0;i<ARRAYSIZE(invalidChars);i++)if(c==invalidChars[i])returnFALSE;str++;}returnbNotDotOnly;}BOOLIsVolumeDeviceHosted(constwchar_t*lpszDiskFile){returnwcsstr(lpszDiskFile,L"\\Device\\")==lpszDiskFile||wcsstr(lpszDiskFile,L"\\DEVICE\\")==lpszDiskFile;}voidCreateFullVolumePath(wchar_t*lpszDiskFile,size_tcbDiskFile,constwchar_t*lpszFileName,BOOL*bDevice){UpperCaseCopy(lpszDiskFile,cbDiskFile,lpszFileName);*bDevice=FALSE;if(wmemcmp(lpszDiskFile,L"\\DEVICE",7)==0){*bDevice=TRUE;}StringCbCopyW(lpszDiskFile,cbDiskFile,lpszFileName);#if _DEBUGOutputDebugString(L"CreateFullVolumePath: ");OutputDebugString(lpszDiskFile);OutputDebugString(L"\n");#endif}intFakeDosNameForDevice(constwchar_t*lpszDiskFile,wchar_t*lpszDosDevice,size_tcbDosDevice,wchar_t*lpszCFDevice,size_tcbCFDevice,BOOLbNameOnly){BOOLbDosLinkCreated=TRUE;StringCbPrintfW(lpszDosDevice,cbDosDevice,L"veracrypt%lu",GetCurrentProcessId());if(bNameOnly==FALSE)bDosLinkCreated=DefineDosDevice(DDD_RAW_TARGET_PATH,lpszDosDevice,lpszDiskFile);if(bDosLinkCreated==FALSE)returnERR_OS_ERROR;elseStringCbPrintfW(lpszCFDevice,cbCFDevice,L"\\\\.\\%s",lpszDosDevice);return0;}intRemoveFakeDosName(wchar_t*lpszDiskFile,wchar_t*lpszDosDevice){BOOLbDosLinkRemoved=DefineDosDevice(DDD_RAW_TARGET_PATH|DDD_EXACT_MATCH_ON_REMOVE|DDD_REMOVE_DEFINITION,lpszDosDevice,lpszDiskFile);if(bDosLinkRemoved==FALSE){returnERR_OS_ERROR;}return0;}voidAbortProcessDirect(wchar_t*abortMsg){// Note that this function also causes localcleanup() to be called (see atexit())MessageBeep(MB_ICONEXCLAMATION);MessageBoxW(NULL,abortMsg,lpszTitle,ICON_HAND);FREE_DLL(hRichEditDll);FREE_DLL(hComctl32Dll);FREE_DLL(hSetupDll);FREE_DLL(hShlwapiDll);FREE_DLL(hProfApiDll);FREE_DLL(hUsp10Dll);FREE_DLL(hCryptSpDll);FREE_DLL(hUXThemeDll);FREE_DLL(hUserenvDll);FREE_DLL(hRsaenhDll);FREE_DLL(himm32dll);FREE_DLL(hMSCTFdll);FREE_DLL(hfltlibdll);FREE_DLL(hframedyndll);FREE_DLL(hpsapidll);FREE_DLL(hsecur32dll);FREE_DLL(hnetapi32dll);FREE_DLL(hauthzdll);FREE_DLL(hxmllitedll);FREE_DLL(hmprdll);FREE_DLL(hsppdll);FREE_DLL(vssapidll);FREE_DLL(hvsstracedll);FREE_DLL(hCryptSpDll);FREE_DLL(hcfgmgr32dll);FREE_DLL(hdevobjdll);FREE_DLL(hpowrprofdll);FREE_DLL(hsspiclidll);FREE_DLL(hcryptbasedll);FREE_DLL(hdwmapidll);FREE_DLL(hmsasn1dll);FREE_DLL(hcrypt32dll);FREE_DLL(hbcryptdll);FREE_DLL(hbcryptprimitivesdll);FREE_DLL(hMsls31);FREE_DLL(hntmartadll);FREE_DLL(hwinscarddll);exit(1);}voidAbortProcess(char*stringId){// Note that this function also causes localcleanup() to be called (see atexit())AbortProcessDirect(GetString(stringId));}voidAbortProcessSilent(void){FREE_DLL(hRichEditDll);FREE_DLL(hComctl32Dll);FREE_DLL(hSetupDll);FREE_DLL(hShlwapiDll);FREE_DLL(hProfApiDll);FREE_DLL(hUsp10Dll);FREE_DLL(hCryptSpDll);FREE_DLL(hUXThemeDll);FREE_DLL(hUserenvDll);FREE_DLL(hRsaenhDll);FREE_DLL(himm32dll);FREE_DLL(hMSCTFdll);FREE_DLL(hfltlibdll);FREE_DLL(hframedyndll);FREE_DLL(hpsapidll);FREE_DLL(hsecur32dll);FREE_DLL(hnetapi32dll);FREE_DLL(hauthzdll);FREE_DLL(hxmllitedll);FREE_DLL(hmprdll);FREE_DLL(hsppdll);FREE_DLL(vssapidll);FREE_DLL(hvsstracedll);FREE_DLL(hCryptSpDll);FREE_DLL(hcfgmgr32dll);FREE_DLL(hdevobjdll);FREE_DLL(hpowrprofdll);FREE_DLL(hsspiclidll);FREE_DLL(hcryptbasedll);FREE_DLL(hdwmapidll);FREE_DLL(hmsasn1dll);FREE_DLL(hcrypt32dll);FREE_DLL(hbcryptdll);FREE_DLL(hbcryptprimitivesdll);FREE_DLL(hMsls31);FREE_DLL(hntmartadll);FREE_DLL(hwinscarddll);// Note that this function also causes localcleanup() to be called (see atexit())exit(1);}#pragma warning(push)#pragma warning(disable:4702)void*err_malloc(size_tsize){void*z=(void*)TCalloc(size);if(z)returnz;AbortProcess("OUTOFMEMORY");return0;}#pragma warning(pop)char*err_strdup(char*lpszText){size_tj=(strlen(lpszText)+1)*sizeof(char);char*z=(char*)err_malloc(j);memmove(z,lpszText,j);returnz;}BOOLIsDiskReadError(DWORDerror){return(error==ERROR_CRC||error==ERROR_IO_DEVICE||error==ERROR_BAD_CLUSTERS||error==ERROR_SECTOR_NOT_FOUND||error==ERROR_READ_FAULT||error==ERROR_INVALID_FUNCTION// I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers||error==ERROR_SEM_TIMEOUT);// I/O operation timeout may be reported as ERROR_SEM_TIMEOUT}BOOLIsDiskWriteError(DWORDerror){return(error==ERROR_IO_DEVICE||error==ERROR_BAD_CLUSTERS||error==ERROR_SECTOR_NOT_FOUND||error==ERROR_WRITE_FAULT||error==ERROR_INVALID_FUNCTION// I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers||error==ERROR_SEM_TIMEOUT);// I/O operation timeout may be reported as ERROR_SEM_TIMEOUT}BOOLIsDiskError(DWORDerror){returnIsDiskReadError(error)||IsDiskWriteError(error);}DWORDhandleWin32Error(HWNDhwndDlg,constchar*srcPos){PWSTRlpMsgBuf;DWORDdwError=GetLastError();wchar_tszErrorValue[32];wchar_t*pszDesc;if(Silent||dwError==0||dwError==ERROR_INVALID_WINDOW_HANDLE)returndwError;// Access deniedif(dwError==ERROR_ACCESS_DENIED&&!IsAdmin()){ErrorDirect(AppendSrcPos(GetString("ERR_ACCESS_DENIED"),srcPos).c_str(),hwndDlg);SetLastError(dwError);// Preserve the original error codereturndwError;}FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,NULL,dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),/* Default language */(PWSTR)&lpMsgBuf,0,NULL);if(lpMsgBuf)pszDesc=(wchar_t*)lpMsgBuf;else{StringCchPrintfW(szErrorValue,ARRAYSIZE(szErrorValue),L"Error 0x%.8X",dwError);pszDesc=szErrorValue;}MessageBoxW(hwndDlg,AppendSrcPos(pszDesc,srcPos).c_str(),lpszTitle,ICON_HAND);if(lpMsgBuf)LocalFree(lpMsgBuf);// User-friendly hardware error explanationif(IsDiskError(dwError))Error("ERR_HARDWARE_ERROR",hwndDlg);// Device not readyif(dwError==ERROR_NOT_READY)HandleDriveNotReadyError(hwndDlg);SetLastError(dwError);// Preserve the original error codereturndwError;}BOOLtranslateWin32Error(wchar_t*lpszMsgBuf,intnWSizeOfBuf){DWORDdwError=GetLastError();if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,NULL,dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),/* Default language */lpszMsgBuf,nWSizeOfBuf,NULL)){SetLastError(dwError);// Preserve the original error codereturnTRUE;}SetLastError(dwError);// Preserve the original error codereturnFALSE;}// If the user has a non-default screen DPI, all absolute font sizes must be// converted using this function.intCompensateDPIFont(intval){if(ScreenDPI==USER_DEFAULT_SCREEN_DPI)returnval;else{doubletmpVal=(double)val*DPIScaleFactorY*DlgAspectRatio*0.999;if(tmpVal>0)return(int)floor(tmpVal);elsereturn(int)ceil(tmpVal);}}// If the user has a non-default screen DPI, some screen coordinates and sizes must// be converted using this functionintCompensateXDPI(intval){if(ScreenDPI==USER_DEFAULT_SCREEN_DPI)returnval;else{doubletmpVal=(double)val*DPIScaleFactorX;if(tmpVal>0)return(int)floor(tmpVal);elsereturn(int)ceil(tmpVal);}}// If the user has a non-default screen DPI, some screen coordinates and sizes must// be converted using this functionintCompensateYDPI(intval){if(ScreenDPI==USER_DEFAULT_SCREEN_DPI)returnval;else{doubletmpVal=(double)val*DPIScaleFactorY;if(tmpVal>0)return(int)floor(tmpVal);elsereturn(int)ceil(tmpVal);}}intGetTextGfxWidth(HWNDhwndDlgItem,constwchar_t*text,HFONThFont){SIZEsizes;TEXTMETRICtextMetrics;HDChdc=GetDC(hwndDlgItem);SelectObject(hdc,(HGDIOBJ)hFont);GetTextExtentPoint32W(hdc,text,(int)wcslen(text),&sizes);GetTextMetrics(hdc,&textMetrics);// Necessary for non-TrueType raster fonts (tmOverhang)ReleaseDC(hwndDlgItem,hdc);return((int)sizes.cx-(int)textMetrics.tmOverhang);}intGetTextGfxHeight(HWNDhwndDlgItem,constwchar_t*text,HFONThFont){SIZEsizes;HDChdc=GetDC(hwndDlgItem);SelectObject(hdc,(HGDIOBJ)hFont);GetTextExtentPoint32W(hdc,text,(int)wcslen(text),&sizes);ReleaseDC(hwndDlgItem,hdc);return((int)sizes.cy);}std::wstringFitPathInGfxWidth(HWNDhwnd,HFONThFont,LONGwidth,conststd::wstring&path){wstringnewPath;RECTrect;rect.left=0;rect.top=0;rect.right=width;rect.bottom=LONG_MAX;HDChdc=GetDC(hwnd);SelectObject(hdc,(HGDIOBJ)hFont);wchar_tpathBuf[TC_MAX_PATH];StringCchCopyW(pathBuf,ARRAYSIZE(pathBuf),path.c_str());if(DrawText(hdc,pathBuf,(int)path.size(),&rect,DT_CALCRECT|DT_MODIFYSTRING|DT_PATH_ELLIPSIS|DT_SINGLELINE)!=0)newPath=pathBuf;ReleaseDC(hwnd,hdc);returnnewPath;}staticLRESULTCALLBACKHyperlinkProc(HWNDhwnd,UINTmessage,WPARAMwParam,LPARAMlParam){WNDPROCwp=(WNDPROC)GetWindowLongPtrW(hwnd,GWLP_USERDATA);switch(message){caseWM_SETCURSOR:if(!bHyperLinkBeingTracked){TRACKMOUSEEVENTtrackMouseEvent;trackMouseEvent.cbSize=sizeof(trackMouseEvent);trackMouseEvent.dwFlags=TME_LEAVE;trackMouseEvent.hwndTrack=hwnd;bHyperLinkBeingTracked=TrackMouseEvent(&trackMouseEvent);HandCursor();}return0;caseWM_MOUSELEAVE:bHyperLinkBeingTracked=FALSE;NormalCursor();return0;}returnCallWindowProcW(wp,hwnd,message,wParam,lParam);}BOOLToHyperlink(HWNDhwndDlg,UINTctrlId){returnToCustHyperlink(hwndDlg,ctrlId,hUserUnderlineFont);}BOOLToCustHyperlink(HWNDhwndDlg,UINTctrlId,HFONThFont){HWNDhwndCtrl=GetDlgItem(hwndDlg,ctrlId);SendMessageW(hwndCtrl,WM_SETFONT,(WPARAM)hFont,0);SetWindowLongPtrW(hwndCtrl,GWLP_USERDATA,(LONG_PTR)GetWindowLongPtrW(hwndCtrl,GWLP_WNDPROC));SetWindowLongPtrW(hwndCtrl,GWLP_WNDPROC,(LONG_PTR)HyperlinkProc);// Resize the field according to its actual size in pixels and move it if centered or right-aligned.// This should be done again if the link text changes.AccommodateTextField(hwndDlg,ctrlId,TRUE,hFont);returnTRUE;}// Resizes a text field according to its actual width and height in pixels (font size is taken into account) and moves// it accordingly if the field is centered or right-aligned. Should be used on all hyperlinks upon dialog init// after localization (bFirstUpdate should be TRUE) and later whenever a hyperlink text changes (bFirstUpdate// must be FALSE).voidAccommodateTextField(HWNDhwndDlg,UINTctrlId,BOOLbFirstUpdate,HFONThFont){RECTrec,wrec,trec;HWNDhwndCtrl=GetDlgItem(hwndDlg,ctrlId);intwidth,origWidth,height,origHeight;inthorizSubOffset,vertSubOffset,vertOffset,alignPosDiff=0;wchar_ttext[MAX_URL_LENGTH];WINDOWINFOwindowInfo;BOOLbBorderlessWindow=!(GetWindowLongPtrW(hwndDlg,GWL_STYLE)&(WS_BORDER|WS_DLGFRAME));// Resize the field according to its length and font size and move if centered or right-alignedGetWindowTextW(hwndCtrl,text,sizeof(text)/sizeof(wchar_t));width=GetTextGfxWidth(hwndCtrl,text,hFont);height=GetTextGfxHeight(hwndCtrl,text,hFont);GetClientRect(hwndCtrl,&rec);origWidth=rec.right;origHeight=rec.bottom;if(width>=0&&(!bFirstUpdate||origWidth>width))// The original width of the field is the maximum allowed size {horizSubOffset=origWidth-width;vertSubOffset=origHeight-height;// Window coordsGetWindowRect(hwndDlg,&wrec);GetClientRect(hwndDlg,&trec);// Vertical "title bar" offsetvertOffset=wrec.bottom-wrec.top-trec.bottom-(bBorderlessWindow?0:GetSystemMetrics(SM_CYFIXEDFRAME));// Text field coordsGetWindowRect(hwndCtrl,&rec);// Alignment offsetwindowInfo.cbSize=sizeof(windowInfo);GetWindowInfo(hwndCtrl,&windowInfo);if(windowInfo.dwStyle&SS_CENTER)alignPosDiff=horizSubOffset/2;elseif(windowInfo.dwStyle&SS_RIGHT)alignPosDiff=horizSubOffset;// Resize/moveif(alignPosDiff>0){// Resize and move the text fieldMoveWindow(hwndCtrl,rec.left-wrec.left-(bBorderlessWindow?0:GetSystemMetrics(SM_CXFIXEDFRAME))+alignPosDiff,rec.top-wrec.top-vertOffset,origWidth-horizSubOffset,origHeight-vertSubOffset,TRUE);}else{// Resize the text fieldSetWindowPos(hwndCtrl,0,0,0,origWidth-horizSubOffset,origHeight-vertSubOffset,SWP_NOMOVE|SWP_NOZORDER);}SetWindowPos(hwndCtrl,HWND_BOTTOM,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);InvalidateRect(hwndCtrl,NULL,TRUE);}}// Note that the user can still close the window by right-clicking its taskbar icon and selecting 'Close window', or by pressing Alt-F4, or using the Task Manager.voidDisableCloseButton(HWNDhwndDlg){EnableMenuItem(GetSystemMenu(hwndDlg,FALSE),SC_CLOSE,MF_BYCOMMAND|MF_DISABLED|MF_GRAYED);}voidEnableCloseButton(HWNDhwndDlg){EnableMenuItem(GetSystemMenu(hwndDlg,FALSE),SC_CLOSE,MF_BYCOMMAND|MF_ENABLED);}// Protects an input field from having its content updated by a Paste action (call ToBootPwdField() to use this).staticLRESULTCALLBACKBootPwdFieldProc(HWNDhwnd,UINTmessage,WPARAMwParam,LPARAMlParam){WNDPROCwp=(WNDPROC)GetWindowLongPtrW(hwnd,GWLP_USERDATA);switch(message){caseWM_PASTE:return1;}returnCallWindowProcW(wp,hwnd,message,wParam,lParam);}// Protects an input field from having its content updated by a Paste action. Used for pre-boot password// input fields (only the US keyboard layout is supported in pre-boot environment so we must prevent the // user from pasting a password typed using a non-US keyboard layout).voidToBootPwdField(HWNDhwndDlg,UINTctrlId){HWNDhwndCtrl=GetDlgItem(hwndDlg,ctrlId);SetWindowLongPtrW(hwndCtrl,GWLP_USERDATA,(LONG_PTR)GetWindowLongPtrW(hwndCtrl,GWLP_WNDPROC));SetWindowLongPtrW(hwndCtrl,GWLP_WNDPROC,(LONG_PTR)BootPwdFieldProc);}// This function currently serves the following purposes:// - Determines scaling factors for current screen DPI and GUI aspect ratio.// - Determines how Windows skews the GUI aspect ratio (which happens when the user has a non-default DPI).// The determined values must be used when performing some GUI operations and calculations.BOOLCALLBACKAuxiliaryDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){switch(msg){caseWM_INITDIALOG:{HDChDC=GetDC(hwndDlg);if(hDC){ScreenDPI=GetDeviceCaps(hDC,LOGPIXELSY);ReleaseDC(hwndDlg,hDC);}DPIScaleFactorX=1;DPIScaleFactorY=1;DlgAspectRatio=1;if(ScreenDPI!=USER_DEFAULT_SCREEN_DPI){// Windows skews the GUI aspect ratio if the user has a non-default DPI. Hence, working with // actual screen DPI is redundant and leads to incorrect results. What really matters here is// how Windows actually renders our GUI. This is determined by comparing the expected and current// sizes of a hidden calibration text field.RECTtrec;trec.right=0;trec.bottom=0;GetClientRect(GetDlgItem(hwndDlg,IDC_ASPECT_RATIO_CALIBRATION_BOX),&trec);if(trec.right!=0&&trec.bottom!=0){// The size of the 282x282 IDC_ASPECT_RATIO_CALIBRATION_BOX rendered at the default DPI (96) is 423x458DPIScaleFactorX=(double)trec.right/423;DPIScaleFactorY=(double)trec.bottom/458;DlgAspectRatio=DPIScaleFactorX/DPIScaleFactorY;}}EndDialog(hwndDlg,0);return1;}caseWM_CLOSE:EndDialog(hwndDlg,0);return1;}return0;}/* Except in response to the WM_INITDIALOG message, the dialog box procedure should return nonzero if it processes the message, and zero if it does not. - see DialogProc */BOOLCALLBACKAboutDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){WORDlw=LOWORD(wParam);staticHBITMAPhbmTextualLogoBitmapRescaled=NULL;switch(msg){caseWM_INITDIALOG:{wchar_tszTmp[100];RECTrec;LocalizeDialog(hwndDlg,"IDD_ABOUT_DLG");// HyperlinkSetWindowText(GetDlgItem(hwndDlg,IDC_HOMEPAGE),L"www.idrix.fr");ToHyperlink(hwndDlg,IDC_HOMEPAGE);// Logo area background (must not keep aspect ratio; must retain Windows-imposed distortion)GetClientRect(GetDlgItem(hwndDlg,IDC_ABOUT_LOGO_AREA),&rec);SetWindowPos(GetDlgItem(hwndDlg,IDC_ABOUT_BKG),HWND_TOP,0,0,rec.right,rec.bottom,SWP_NOMOVE);// Resize the logo bitmap if the user has a non-default DPI if(ScreenDPI!=USER_DEFAULT_SCREEN_DPI){// Logo (must recreate and keep the original aspect ratio as Windows distorts it)hbmTextualLogoBitmapRescaled=RenderBitmap(MAKEINTRESOURCE(IDB_TEXTUAL_LOGO_288DPI),GetDlgItem(hwndDlg,IDC_TEXTUAL_LOGO_IMG),0,0,0,0,FALSE,TRUE);SetWindowPos(GetDlgItem(hwndDlg,IDC_ABOUT_BKG),HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);}// VersionSendMessage(GetDlgItem(hwndDlg,IDT_ABOUT_VERSION),WM_SETFONT,(WPARAM)hUserBoldFont,0);StringCbPrintfW(szTmp,sizeof(szTmp),L"VeraCrypt %s",_T(VERSION_STRING));#ifdef _WIN64StringCbCatW(szTmp,sizeof(szTmp),L" (64-bit)");#elseStringCbCatW(szTmp,sizeof(szTmp),L" (32-bit)");#endif#if (defined(_DEBUG) || defined(DEBUG))StringCbCatW(szTmp,sizeof(szTmp),L" (debug)");#endifSetDlgItemText(hwndDlg,IDT_ABOUT_VERSION,szTmp);SetDlgItemText(hwndDlg,IDT_ABOUT_RELEASE,TC_STR_RELEASED_BY);// CreditsSendMessage(GetDlgItem(hwndDlg,IDC_ABOUT_CREDITS),WM_SETFONT,(WPARAM)hUserFont,(LPARAM)0);SendMessage(hwndDlg,WM_APP,0,0);return1;}caseWM_APP:SetWindowText(GetDlgItem(hwndDlg,IDC_ABOUT_CREDITS),L"Based on TrueCrypt 7.1a, freely available at http://www.truecrypt.org/ .\r\n\r\n"L"Portions of this software:\r\n"L"Copyright \xA9 2013-2017 IDRIX. All rights reserved.\r\n"L"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\r\n"L"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\r\n"L"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\r\n"L"Copyright \xA9 1995-2017 Jean-loup Gailly and Mark Adler.\r\n"L"Copyright \xA9 2016 Disk Cryptography Services for EFI (DCS), Alex Kolotnikov.\r\n"L"Copyright \xA9 Dieter Baron and Thomas Klausner.\r\n"L"Copyright \xA9 2013, Alexey Degtyarev. All rights reserved.\r\n"L"Copyright \xA9 1999-2013,2014,2015,2016 Jack Lloyd. All rights reserved.\r\n\r\n"L"This software as a whole:\r\n"L"Copyright \xA9 2013-2017 IDRIX. All rights reserved.\r\n\r\n"L"An IDRIX Release");return1;caseWM_COMMAND:if(lw==IDOK||lw==IDCANCEL){PostMessage(hwndDlg,WM_CLOSE,0,0);return1;}if(lw==IDC_HOMEPAGE){Applink("main");return1;}// Disallow modification of creditsif(HIWORD(wParam)==EN_UPDATE){SendMessage(hwndDlg,WM_APP,0,0);return1;}return0;caseWM_CLOSE:/* Delete buffered bitmaps (if any) */if(hbmTextualLogoBitmapRescaled!=NULL){DeleteObject((HGDIOBJ)hbmTextualLogoBitmapRescaled);hbmTextualLogoBitmapRescaled=NULL;}EndDialog(hwndDlg,0);return1;}return0;}staticHWNDStaticModelessWaitDlgHandle=NULL;// Call DisplayStaticModelessWaitDlg() to open this dialog and CloseStaticModelessWaitDlg() to close it.staticBOOLCALLBACKStaticModelessWaitDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){WORDlw=LOWORD(wParam);switch(msg){caseWM_INITDIALOG:{LocalizeDialog(hwndDlg,NULL);return0;}caseWM_COMMAND:if(lw==IDOK||lw==IDCANCEL)return1;return0;caseWM_CLOSE:StaticModelessWaitDlgHandle=NULL;EndDialog(hwndDlg,0);return1;}return0;}// Opens a dialog window saying "Please wait..." which is not modal and does not need any GUI refresh after initialization.voidDisplayStaticModelessWaitDlg(HWNDparent){if(StaticModelessWaitDlgHandle!=NULL)return;// Already shownStaticModelessWaitDlgHandle=CreateDialogParamW(hInst,MAKEINTRESOURCEW(IDD_STATIC_MODELESS_WAIT_DLG),parent,(DLGPROC)StaticModelessWaitDlgProc,(LPARAM)0);ShowWindow(StaticModelessWaitDlgHandle,SW_SHOWNORMAL);// Allow synchronous use with the GUI being instantly and fully renderedProcessPaintMessages(StaticModelessWaitDlgHandle,500);}voidCloseStaticModelessWaitDlg(void){if(StaticModelessWaitDlgHandle==NULL)return;// Not shownDestroyWindow(StaticModelessWaitDlgHandle);}BOOLIsButtonChecked(HWNDhButton){if(SendMessage(hButton,BM_GETCHECK,0,0)==BST_CHECKED)returnTRUE;elsereturnFALSE;}voidCheckButton(HWNDhButton){SendMessage(hButton,BM_SETCHECK,BST_CHECKED,0);}voidLeftPadString(wchar_t*szTmp,intlen,inttargetLen,wchar_tfiller){inti;if(targetLen<=len)return;for(i=targetLen-1;i>=(targetLen-len);i--)szTmp[i]=szTmp[i-(targetLen-len)];wmemset(szTmp,filler,targetLen-len);szTmp[targetLen]=0;}/* InitDialog - initialize the applications main dialog, this function should be called only once in the dialogs WM_INITDIALOG message handler */voidInitDialog(HWNDhwndDlg){NONCLIENTMETRICSWmetric;staticBOOLaboutMenuAppended=FALSE;intnHeight;LOGFONTWlf;HMENUhMenu;Font*font;/* Fonts */memset(&lf,0,sizeof(lf));// Normalfont=GetFont("font_normal");metric.cbSize=sizeof(metric);SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,sizeof(metric),&metric,0);WindowTitleBarFont=CreateFontIndirectW(&metric.lfCaptionFont);metric.lfMessageFont.lfHeight=CompensateDPIFont(!font?-11:-font->Size);metric.lfMessageFont.lfWidth=0;if(font&&wcscmp(font->FaceName,L"default")!=0){StringCbCopyW((WCHAR*)metric.lfMessageFont.lfFaceName,sizeof(metric.lfMessageFont.lfFaceName),font->FaceName);}elseif(IsOSAtLeast(WIN_VISTA)){// Vista's new default font (size and spacing) breaks compatibility with Windows 2k/XP applications.// Force use of Tahoma (as Microsoft does in many dialogs) until a native Vista look is implemented.StringCbCopyW((WCHAR*)metric.lfMessageFont.lfFaceName,sizeof(metric.lfMessageFont.lfFaceName),L"Tahoma");}hUserFont=CreateFontIndirectW(&metric.lfMessageFont);metric.lfMessageFont.lfUnderline=TRUE;hUserUnderlineFont=CreateFontIndirectW(&metric.lfMessageFont);metric.lfMessageFont.lfUnderline=FALSE;metric.lfMessageFont.lfWeight=FW_BOLD;hUserBoldFont=CreateFontIndirectW(&metric.lfMessageFont);metric.lfMessageFont.lfUnderline=TRUE;metric.lfMessageFont.lfWeight=FW_BOLD;hUserUnderlineBoldFont=CreateFontIndirectW(&metric.lfMessageFont);// Fixed-size (hexadecimal digits)nHeight=CompensateDPIFont(-12);lf.lfHeight=nHeight;lf.lfWidth=0;lf.lfEscapement=0;lf.lfOrientation=0;lf.lfWeight=FW_NORMAL;lf.lfItalic=FALSE;lf.lfUnderline=FALSE;lf.lfStrikeOut=FALSE;lf.lfCharSet=DEFAULT_CHARSET;lf.lfOutPrecision=OUT_DEFAULT_PRECIS;lf.lfClipPrecision=CLIP_DEFAULT_PRECIS;lf.lfQuality=PROOF_QUALITY;lf.lfPitchAndFamily=FF_DONTCARE;StringCbCopyW(lf.lfFaceName,sizeof(lf.lfFaceName),L"Courier New");hFixedDigitFont=CreateFontIndirectW(&lf);if(hFixedDigitFont==NULL){handleWin32Error(hwndDlg,SRC_POS);AbortProcess("NOFONT");}// Boldfont=GetFont("font_bold");nHeight=CompensateDPIFont(!font?-13:-font->Size);lf.lfHeight=nHeight;lf.lfWeight=FW_BLACK;StringCbCopyW(lf.lfFaceName,sizeof(lf.lfFaceName),!font?L"Arial":font->FaceName);hBoldFont=CreateFontIndirectW(&lf);if(hBoldFont==NULL){handleWin32Error(hwndDlg,SRC_POS);AbortProcess("NOFONT");}// Titlefont=GetFont("font_title");nHeight=CompensateDPIFont(!font?-21:-font->Size);lf.lfHeight=nHeight;lf.lfWeight=FW_REGULAR;StringCbCopyW(lf.lfFaceName,sizeof(lf.lfFaceName),!font?L"Times New Roman":font->FaceName);hTitleFont=CreateFontIndirectW(&lf);if(hTitleFont==NULL){handleWin32Error(hwndDlg,SRC_POS);AbortProcess("NOFONT");}// Fixed-sizefont=GetFont("font_fixed");nHeight=CompensateDPIFont(!font?-12:-font->Size);lf.lfHeight=nHeight;lf.lfWidth=0;lf.lfEscapement=0;lf.lfOrientation=0;lf.lfWeight=FW_NORMAL;lf.lfItalic=FALSE;lf.lfUnderline=FALSE;lf.lfStrikeOut=FALSE;lf.lfCharSet=DEFAULT_CHARSET;lf.lfOutPrecision=OUT_DEFAULT_PRECIS;lf.lfClipPrecision=CLIP_DEFAULT_PRECIS;lf.lfQuality=PROOF_QUALITY;lf.lfPitchAndFamily=FF_DONTCARE;StringCbCopyW(lf.lfFaceName,sizeof(lf.lfFaceName),!font?L"Lucida Console":font->FaceName);hFixedFont=CreateFontIndirectW(&lf);if(hFixedFont==NULL){handleWin32Error(hwndDlg,SRC_POS);AbortProcess("NOFONT");}if(!aboutMenuAppended){hMenu=GetSystemMenu(hwndDlg,FALSE);AppendMenu(hMenu,MF_SEPARATOR,0,L"");AppendMenuW(hMenu,MF_ENABLED|MF_STRING,IDC_ABOUT,GetString("ABOUTBOX"));aboutMenuAppended=TRUE;}}// The parameter maxMessagesToProcess prevents endless processing of paint messagesvoidProcessPaintMessages(HWNDhwnd,intmaxMessagesToProcess){MSGpaintMsg;intmsgCounter=maxMessagesToProcess;while(PeekMessageW(&paintMsg,hwnd,0,0,PM_REMOVE|PM_QS_PAINT)!=0&&msgCounter-->0){DispatchMessageW(&paintMsg);}}HDCCreateMemBitmap(HINSTANCEhInstance,HWNDhwnd,wchar_t*resource){HBITMAPpicture=LoadBitmap(hInstance,resource);HDCviewDC=GetDC(hwnd),dcMem;dcMem=CreateCompatibleDC(viewDC);SetMapMode(dcMem,MM_TEXT);SelectObject(dcMem,picture);DeleteObject(picture);ReleaseDC(hwnd,viewDC);returndcMem;}/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied). If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest areretrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted thesame way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.)is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly inboth directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored. This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should bedeleted by calling DeleteObject() with the handle passed as the parameter. Known Windows issues: - For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels. - Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */HBITMAPRenderBitmap(wchar_t*resource,HWNDhwndDest,intx,inty,intnWidth,intnHeight,BOOLbDirectRender,BOOLbKeepAspectRatio){LRESULTlResult=0;HDChdcSrc=CreateMemBitmap(hInst,hwndDest,resource);if(!hdcSrc)returnNULL;HGDIOBJpicture=GetCurrentObject(hdcSrc,OBJ_BITMAP);HBITMAPhbmpRescaled=NULL;BITMAPbitmap;HDChdcRescaled;if(!bDirectRender&&nWidth==0&&nHeight==0){RECTrec;GetClientRect(hwndDest,&rec);if(bKeepAspectRatio){if(DlgAspectRatio>1){// Do not fix this, it's correct. We use the Y scale factor intentionally for both// directions to maintain aspect ratio (see above for more info).nWidth=CompensateYDPI(rec.right);nHeight=CompensateYDPI(rec.bottom);}else{// Do not fix this, it's correct. We use the X scale factor intentionally for both// directions to maintain aspect ratio (see above for more info).nWidth=CompensateXDPI(rec.right);nHeight=CompensateXDPI(rec.bottom);}}else{nWidth=CompensateXDPI(rec.right);nHeight=CompensateYDPI(rec.bottom);}}GetObject(picture,sizeof(BITMAP),&bitmap);hdcRescaled=CreateCompatibleDC(hdcSrc);if(hdcRescaled){hbmpRescaled=CreateCompatibleBitmap(hdcSrc,nWidth,nHeight);SelectObject(hdcRescaled,hbmpRescaled);/* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000. TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */SetStretchBltMode(hdcRescaled,HALFTONE);StretchBlt(hdcRescaled,0,0,nWidth,nHeight,hdcSrc,0,0,bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);DeleteDC(hdcSrc);if(bDirectRender){HDChdcDest=GetDC(hwndDest);if(hdcDest){BitBlt(hdcDest,x,y,nWidth,nHeight,hdcRescaled,0,0,SRCCOPY);ReleaseDC(hwndDest,hdcDest);}}else{lResult=SendMessage(hwndDest,(UINT)STM_SETIMAGE,(WPARAM)IMAGE_BITMAP,(LPARAM)(HANDLE)hbmpRescaled);}if((HGDIOBJ)lResult!=NULL&&(HGDIOBJ)lResult!=(HGDIOBJ)hbmpRescaled)DeleteObject((HGDIOBJ)lResult);DeleteDC(hdcRescaled);}returnhbmpRescaled;}LRESULTCALLBACKRedTick(HWNDhwnd,UINTuMsg,WPARAMwParam,LPARAMlParam){if(uMsg==WM_CREATE){}elseif(uMsg==WM_DESTROY){}elseif(uMsg==WM_TIMER){}elseif(uMsg==WM_PAINT){PAINTSTRUCTtmp;HPENhPen;HDChDC;BOOLbEndPaint;RECTRect;if(GetUpdateRect(hwnd,NULL,FALSE)){hDC=BeginPaint(hwnd,&tmp);bEndPaint=TRUE;if(hDC==NULL)returnDefWindowProcW(hwnd,uMsg,wParam,lParam);}else{hDC=GetDC(hwnd);bEndPaint=FALSE;}GetClientRect(hwnd,&Rect);hPen=CreatePen(PS_SOLID,2,RGB(0,255,0));if(hPen!=NULL){HGDIOBJhObj=SelectObject(hDC,hPen);WORDbx=LOWORD(GetDialogBaseUnits());WORDby=HIWORD(GetDialogBaseUnits());MoveToEx(hDC,(Rect.right-Rect.left)/2,Rect.bottom,NULL);LineTo(hDC,Rect.right,Rect.top);MoveToEx(hDC,(Rect.right-Rect.left)/2,Rect.bottom,NULL);LineTo(hDC,(3*bx)/4,(2*by)/8);SelectObject(hDC,hObj);DeleteObject(hPen);}if(bEndPaint)EndPaint(hwnd,&tmp);elseReleaseDC(hwnd,hDC);returnTRUE;}returnDefWindowProcW(hwnd,uMsg,wParam,lParam);}BOOLRegisterRedTick(HINSTANCEhInstance){WNDCLASSWwc;ULONGrc;memset(&wc,0,sizeofwc);wc.style=CS_HREDRAW|CS_VREDRAW;wc.cbClsExtra=0;wc.cbWndExtra=4;wc.hInstance=hInstance;wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);wc.hCursor=NULL;wc.hbrBackground=(HBRUSH)GetStockObject(LTGRAY_BRUSH);wc.lpszClassName=L"VCREDTICK";wc.lpfnWndProc=&RedTick;rc=(ULONG)RegisterClassW(&wc);returnrc==0?FALSE:TRUE;}BOOLUnregisterRedTick(HINSTANCEhInstance){returnUnregisterClassW(L"VCREDTICK",hInstance);}LRESULTCALLBACKSplashDlgProc(HWNDhwnd,UINTuMsg,WPARAMwParam,LPARAMlParam){returnDefDlgProcW(hwnd,uMsg,wParam,lParam);}staticintg_waitCursorCounter=0;voidWaitCursor(){staticHCURSORhcWait;if(hcWait==NULL)hcWait=LoadCursor(NULL,IDC_WAIT);if((g_waitCursorCounter==0)||(hCursor!=hcWait)){SetCursor(hcWait);hCursor=hcWait;}g_waitCursorCounter++;}voidNormalCursor(){staticHCURSORhcArrow;if(hcArrow==NULL)hcArrow=LoadCursor(NULL,IDC_ARROW);if(g_waitCursorCounter>0)g_waitCursorCounter--;if(g_waitCursorCounter==0){SetCursor(hcArrow);hCursor=NULL;}}voidArrowWaitCursor(){staticHCURSORhcArrowWait;if(hcArrowWait==NULL)hcArrowWait=LoadCursor(NULL,IDC_APPSTARTING);if((g_waitCursorCounter==0)||(hCursor!=hcArrowWait)){SetCursor(hcArrowWait);hCursor=hcArrowWait;}g_waitCursorCounter++;}voidHandCursor(){staticHCURSORhcHand;if(hcHand==NULL)hcHand=LoadCursor(NULL,IDC_HAND);SetCursor(hcHand);hCursor=hcHand;}voidAddComboPair(HWNDhComboBox,constwchar_t*lpszItem,intvalue){LPARAMnIndex;nIndex=SendMessage(hComboBox,CB_ADDSTRING,0,(LPARAM)lpszItem);nIndex=SendMessage(hComboBox,CB_SETITEMDATA,nIndex,(LPARAM)value);}voidSelectAlgo(HWNDhComboBox,int*algo_id){LPARAMnCount=SendMessage(hComboBox,CB_GETCOUNT,0,0);LPARAMx,i;for(i=0;i<nCount;i++){x=SendMessage(hComboBox,CB_GETITEMDATA,i,0);if(x==(LPARAM)*algo_id){SendMessage(hComboBox,CB_SETCURSEL,i,0);return;}}/* Something went wrong ; couldn't find the requested algo id so we drop back to a default */*algo_id=(int)SendMessage(hComboBox,CB_GETITEMDATA,0,0);SendMessage(hComboBox,CB_SETCURSEL,0,0);}voidPopulateWipeModeCombo(HWNDhComboBox,BOOLbNA,BOOLbInPlaceEncryption,BOOLbHeaderWipe){if(bNA){AddComboPair(hComboBox,GetString("NOT_APPLICABLE_OR_NOT_AVAILABLE"),TC_WIPE_NONE);}else{if(!bHeaderWipe){AddComboPair(hComboBox,GetString("WIPE_MODE_NONE"),TC_WIPE_NONE);}AddComboPair(hComboBox,GetString("WIPE_MODE_1_RAND"),TC_WIPE_1_RAND);AddComboPair(hComboBox,GetString("WIPE_MODE_3_DOD_5220"),TC_WIPE_3_DOD_5220);AddComboPair(hComboBox,GetString("WIPE_MODE_7_DOD_5220"),TC_WIPE_7_DOD_5220);AddComboPair(hComboBox,GetString("WIPE_MODE_35_GUTMANN"),TC_WIPE_35_GUTMANN);if(bHeaderWipe)AddComboPair(hComboBox,GetString("WIPE_MODE_256"),TC_WIPE_256);// paranoid wipe for volume header}}wchar_t*GetWipeModeName(WipeAlgorithmIdmodeId){switch(modeId){caseTC_WIPE_NONE:returnGetString("WIPE_MODE_NONE");caseTC_WIPE_1_RAND:returnGetString("WIPE_MODE_1_RAND");caseTC_WIPE_3_DOD_5220:returnGetString("WIPE_MODE_3_DOD_5220");caseTC_WIPE_7_DOD_5220:returnGetString("WIPE_MODE_7_DOD_5220");caseTC_WIPE_35_GUTMANN:returnGetString("WIPE_MODE_35_GUTMANN");caseTC_WIPE_256:returnGetString("WIPE_MODE_256");default:returnGetString("NOT_APPLICABLE_OR_NOT_AVAILABLE");}}wchar_t*GetPathType(constwchar_t*path,BOOLbUpperCase,BOOL*bIsPartition){if(wcsstr(path,L"Partition")&&wcsstr(path,L"Partition0")==NULL){*bIsPartition=TRUE;returnGetString(bUpperCase?"PARTITION_UPPER_CASE":"PARTITION_LOWER_CASE");}elseif(wcsstr(path,L"HarddiskVolume")){*bIsPartition=TRUE;returnGetString(bUpperCase?"VOLUME_UPPER_CASE":"VOLUME_LOWER_CASE");}*bIsPartition=FALSE;returnGetString(bUpperCase?"DEVICE_UPPER_CASE":"DEVICE_LOWER_CASE");}LRESULTCALLBACKCustomDlgProc(HWNDhwnd,UINTuMsg,WPARAMwParam,LPARAMlParam){if(uMsg==WM_SETCURSOR&&hCursor!=NULL){SetCursor(hCursor);returnTRUE;}returnDefDlgProcW(hwnd,uMsg,wParam,lParam);}/*static BOOL IsReturnAddress (DWORD64 address){ static size_t codeEnd = 0; byte *sp = (byte *) address; if (codeEnd == 0) { MEMORY_BASIC_INFORMATION mi; if (VirtualQuery ((LPCVOID) 0x401000, &mi, sizeof (mi)) >= sizeof (mi)) codeEnd = (size_t) mi.BaseAddress + mi.RegionSize; } if (address < 0x401000 + 8 || address > codeEnd) return FALSE; return sp[-5] == 0xe8 // call ADDR || (sp[-6] == 0xff && sp[-5] == 0x15) // call [ADDR] || (sp[-2] == 0xff && (sp[-1] & 0xf0) == 0xd0); // call REG}*/typedefstruct{EXCEPTION_POINTERS*ExceptionPointers;HANDLEExceptionThread;}ExceptionHandlerThreadArgs;voidExceptionHandlerThread(void*threadArg){ExceptionHandlerThreadArgs*args=(ExceptionHandlerThreadArgs*)threadArg;EXCEPTION_POINTERS*ep=args->ExceptionPointers;//DWORD addr;DWORDexCode=ep->ExceptionRecord->ExceptionCode;// SYSTEM_INFO si;// wchar_t msg[8192];// char modPath[MAX_PATH];// int crc = 0;// char url[MAX_URL_LENGTH];// char lpack[128];// stringstream callStack;// addr = (DWORD) ep->ExceptionRecord->ExceptionAddress;// PDWORD sp = (PDWORD) ep->ContextRecord->Esp;// int frameNumber = 0;switch(exCode){caseSTATUS_IN_PAGE_ERROR:case0xeedfade:// Exception not caused by VeraCryptMessageBoxW(0,GetString("EXCEPTION_REPORT_EXT"),GetString("EXCEPTION_REPORT_TITLE"),MB_ICONERROR|MB_OK|MB_SETFOREGROUND|MB_TOPMOST);return;}// Call stack/* HMODULE dbgDll = LoadLibrary ("dbghelp.dll"); if (dbgDll) { typedef DWORD (__stdcall *SymGetOptions_t) (); typedef DWORD (__stdcall *SymSetOptions_t) (DWORD SymOptions); typedef BOOL (__stdcall *SymInitialize_t) (HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess); typedef BOOL (__stdcall *StackWalk64_t) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); typedef BOOL (__stdcall * SymFromAddr_t) (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol); SymGetOptions_t DbgHelpSymGetOptions = (SymGetOptions_t) GetProcAddress (dbgDll, "SymGetOptions"); SymSetOptions_t DbgHelpSymSetOptions = (SymSetOptions_t) GetProcAddress (dbgDll, "SymSetOptions"); SymInitialize_t DbgHelpSymInitialize = (SymInitialize_t) GetProcAddress (dbgDll, "SymInitialize"); PFUNCTION_TABLE_ACCESS_ROUTINE64 DbgHelpSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress (dbgDll, "SymFunctionTableAccess64"); PGET_MODULE_BASE_ROUTINE64 DbgHelpSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress (dbgDll, "SymGetModuleBase64"); StackWalk64_t DbgHelpStackWalk64 = (StackWalk64_t) GetProcAddress (dbgDll, "StackWalk64"); SymFromAddr_t DbgHelpSymFromAddr = (SymFromAddr_t) GetProcAddress (dbgDll, "SymFromAddr"); if (DbgHelpSymGetOptions && DbgHelpSymSetOptions && DbgHelpSymInitialize && DbgHelpSymFunctionTableAccess64 && DbgHelpSymGetModuleBase64 && DbgHelpStackWalk64 && DbgHelpSymFromAddr) { DbgHelpSymSetOptions (DbgHelpSymGetOptions() | SYMOPT_DEFERRED_LOADS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_NO_CPP); if (DbgHelpSymInitialize (GetCurrentProcess(), NULL, TRUE)) { STACKFRAME64 frame; memset (&frame, 0, sizeof (frame)); frame.AddrPC.Offset = ep->ContextRecord->Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Offset = ep->ContextRecord->Esp; frame.AddrStack.Mode = AddrModeFlat; frame.AddrFrame.Offset = ep->ContextRecord->Ebp; frame.AddrFrame.Mode = AddrModeFlat; string lastSymbol; while (frameNumber < 32 && DbgHelpStackWalk64 (IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), args->ExceptionThread, &frame, ep->ContextRecord, NULL, DbgHelpSymFunctionTableAccess64, DbgHelpSymGetModuleBase64, NULL)) { if (!frame.AddrPC.Offset) continue; ULONG64 symbolBuffer[(sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR) + sizeof (ULONG64) - 1) / sizeof (ULONG64)]; memset (symbolBuffer, 0, sizeof (symbolBuffer)); PSYMBOL_INFO symbol = (PSYMBOL_INFO) symbolBuffer; symbol->SizeOfStruct = sizeof (SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; if (DbgHelpSymFromAddr (GetCurrentProcess(), frame.AddrPC.Offset, NULL, symbol) && symbol->NameLen > 0) { for (size_t i = 0; i < symbol->NameLen; ++i) { if (!isalnum (symbol->Name[i])) symbol->Name[i] = '_'; } if (symbol->Name != lastSymbol) callStack << "&st" << frameNumber++ << "=" << symbol->Name; lastSymbol = symbol->Name; } else if (frameNumber == 0 || IsReturnAddress (frame.AddrPC.Offset)) { callStack << "&st" << frameNumber++ << "=0x" << hex << frame.AddrPC.Offset << dec; } } } } } // StackWalk64() may fail due to missing frame pointers list <DWORD> retAddrs; if (frameNumber == 0) retAddrs.push_back (ep->ContextRecord->Eip); retAddrs.push_back (0); MEMORY_BASIC_INFORMATION mi; VirtualQuery (sp, &mi, sizeof (mi)); PDWORD stackTop = (PDWORD)((byte *) mi.BaseAddress + mi.RegionSize); int i = 0; while (retAddrs.size() < 16 && &sp[i] < stackTop) { if (IsReturnAddress (sp[i])) { bool duplicate = false; foreach (DWORD prevAddr, retAddrs) { if (sp[i] == prevAddr) { duplicate = true; break; } } if (!duplicate) retAddrs.push_back (sp[i]); } i++; } if (retAddrs.size() > 1) { foreach (DWORD addr, retAddrs) { callStack << "&st" << frameNumber++ << "=0x" << hex << addr << dec; } } // Checksum of the module if (GetModuleFileName (NULL, modPath, sizeof (modPath))) { HANDLE h = CreateFile (modPath, FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (h != INVALID_HANDLE_VALUE) { BY_HANDLE_FILE_INFORMATION fi; if (GetFileInformationByHandle (h, &fi)) { char *buf = (char *) malloc (fi.nFileSizeLow); if (buf) { DWORD bytesRead; if (ReadFile (h, buf, fi.nFileSizeLow, &bytesRead, NULL) && bytesRead == fi.nFileSizeLow) crc = GetCrc32 ((unsigned char *) buf, fi.nFileSizeLow); free (buf); } } CloseHandle (h); } } GetSystemInfo (&si); if (LocalizationActive) sprintf_s (lpack, sizeof (lpack), "&langpack=%s_%s", GetPreferredLangId (), GetActiveLangPackVersion ()); else lpack[0] = 0; sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x" , lpack , GetWindowsEdition().c_str() , CurrentOSMajor , CurrentOSMinor , CurrentOSServicePack , Is64BitOs () ? "x64" : "x86" , si.dwNumberOfProcessors#ifdef TCMOUNT ,"main"#endif#ifdef VOLFORMAT ,"format"#endif#ifdef SETUP ,"setup"#endif , crc , LastDialogId ? LastDialogId : "-" , exCode , addr); string urlStr = url + callStack.str(); _snwprintf (msg, array_capacity (msg), GetString ("EXCEPTION_REPORT"), urlStr.c_str()); if (IDYES == MessageBoxW (0, msg, GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1)) ShellExecute (NULL, "open", urlStr.c_str(), NULL, NULL, SW_SHOWNORMAL); else */UnhandledExceptionFilter(ep);}LONG__stdcallExceptionHandler(EXCEPTION_POINTERS*ep){SetUnhandledExceptionFilter(NULL);if(SystemFileSelectorCallPending&&SystemFileSelectorCallerThreadId==GetCurrentThreadId()){MessageBoxW(NULL,GetString("EXCEPTION_REPORT_EXT_FILESEL"),GetString("EXCEPTION_REPORT_TITLE"),MB_ICONERROR|MB_OK|MB_SETFOREGROUND|MB_TOPMOST);UnhandledExceptionFilter(ep);returnEXCEPTION_EXECUTE_HANDLER;}ExceptionHandlerThreadArgsargs;args.ExceptionPointers=ep;args.ExceptionThread=GetCurrentThread();WaitForSingleObject((HANDLE)_beginthread(ExceptionHandlerThread,0,&args),INFINITE);returnEXCEPTION_EXECUTE_HANDLER;}voidInvalidParameterHandler(constwchar_t*expression,constwchar_t*function,constwchar_t*file,unsignedintline,uintptr_treserved){TC_THROW_FATAL_EXCEPTION;}staticLRESULTCALLBACKNonInstallUacWndProc(HWNDhWnd,UINTmessage,WPARAMwParam,LPARAMlParam){returnDefWindowProcW(hWnd,message,wParam,lParam);}BOOLLaunchElevatedProcess(HWNDhwndDlg,constwchar_t*szModPath,constwchar_t*args){wchar_tnewCmdLine[4096];WNDCLASSEXWwcex;HWNDhWnd;memset(&wcex,0,sizeof(wcex));wcex.cbSize=sizeof(WNDCLASSEX);wcex.lpfnWndProc=(WNDPROC)NonInstallUacWndProc;wcex.hInstance=hInst;wcex.lpszClassName=L"VeraCrypt";RegisterClassExW(&wcex);// A small transparent window is necessary to bring the new instance to foregroundhWnd=CreateWindowExW(WS_EX_TOOLWINDOW|WS_EX_LAYERED,L"VeraCrypt",L"VeraCrypt",0,GetSystemMetrics(SM_CXSCREEN)/2,GetSystemMetrics(SM_CYSCREEN)/2,1,1,NULL,NULL,hInst,NULL);SetLayeredWindowAttributes(hWnd,0,0,LWA_ALPHA);ShowWindow(hWnd,SW_SHOWNORMAL);StringCbCopyW(newCmdLine,sizeof(newCmdLine),L"/q UAC ");StringCbCatW(newCmdLine,sizeof(newCmdLine),args);if((int)ShellExecuteW(hWnd,L"runas",szModPath,newCmdLine,NULL,SW_SHOWNORMAL)<=32){if(hwndDlg)handleWin32Error(hwndDlg,SRC_POS);returnFALSE;}else{Sleep(2000);returnTRUE;}}// Mutex handling to prevent multiple instances of the wizard or main app from dealing with system encryption.// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOLCreateSysEncMutex(void){returnTCCreateMutex(&hSysEncMutex,TC_MUTEX_NAME_SYSENC);}BOOLInstanceHasSysEncMutex(void){return(hSysEncMutex!=NULL);}// Mutex handling to prevent multiple instances of the wizard from dealing with system encryptionvoidCloseSysEncMutex(void){TCCloseMutex(&hSysEncMutex);}// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOLCreateNonSysInplaceEncMutex(void){returnTCCreateMutex(&hNonSysInplaceEncMutex,TC_MUTEX_NAME_NONSYS_INPLACE_ENC);}BOOLInstanceHasNonSysInplaceEncMutex(void){return(hNonSysInplaceEncMutex!=NULL);}voidCloseNonSysInplaceEncMutex(void){TCCloseMutex(&hNonSysInplaceEncMutex);}// Returns TRUE if another instance of the wizard is preparing, resuming or performing non-system in-place encryptionBOOLNonSysInplaceEncInProgressElsewhere(void){return(!InstanceHasNonSysInplaceEncMutex()&&MutexExistsOnSystem(TC_MUTEX_NAME_NONSYS_INPLACE_ENC));}// Mutex handling to prevent multiple instances of the wizard or main app from trying to install// or register the driver or from trying to launch it in portable mode at the same time.// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOLCreateDriverSetupMutex(void){returnTCCreateMutex(&hDriverSetupMutex,TC_MUTEX_NAME_DRIVER_SETUP);}voidCloseDriverSetupMutex(void){TCCloseMutex(&hDriverSetupMutex);}BOOLCreateAppSetupMutex(void){returnTCCreateMutex(&hAppSetupMutex,TC_MUTEX_NAME_APP_SETUP);}voidCloseAppSetupMutex(void){TCCloseMutex(&hAppSetupMutex);}BOOLIsTrueCryptInstallerRunning(void){return(MutexExistsOnSystem(TC_MUTEX_NAME_APP_SETUP));}// Returns TRUE if the mutex is (or had been) successfully acquired (otherwise FALSE). BOOLTCCreateMutex(volatileHANDLE*hMutex,wchar_t*name){if(*hMutex!=NULL)returnTRUE;// This instance already has the mutex*hMutex=CreateMutex(NULL,TRUE,name);if(*hMutex==NULL){// In multi-user configurations, the OS returns "Access is denied" here when a user attempts// to acquire the mutex if another user already has. However, on Vista, "Access is denied" is// returned also if the mutex is owned by a process with admin rights while we have none.returnFALSE;}if(GetLastError()==ERROR_ALREADY_EXISTS){ReleaseMutex(*hMutex);CloseHandle(*hMutex);*hMutex=NULL;returnFALSE;}returnTRUE;}voidTCCloseMutex(volatileHANDLE*hMutex){if(*hMutex!=NULL){if(ReleaseMutex(*hMutex)&&CloseHandle(*hMutex))*hMutex=NULL;}}// Returns TRUE if a process running on the system has the specified mutex (otherwise FALSE). BOOLMutexExistsOnSystem(wchar_t*name){if(name[0]==0)returnFALSE;HANDLEhMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,name);if(hMutex==NULL){if(GetLastError()==ERROR_FILE_NOT_FOUND)returnFALSE;if(GetLastError()==ERROR_ACCESS_DENIED)// On Vista, this is returned if the owner of the mutex is elevated while we are notreturnTRUE;// The call failed and it is not certain whether the mutex exists or notreturnFALSE;}CloseHandle(hMutex);returnTRUE;}uint32ReadDriverConfigurationFlags(){DWORDconfigMap;if(!ReadLocalMachineRegistryDword(L"SYSTEM\\CurrentControlSet\\Services\\veracrypt",TC_DRIVER_CONFIG_REG_VALUE_NAME,&configMap))configMap=0;returnconfigMap;}uint32ReadEncryptionThreadPoolFreeCpuCountLimit(){DWORDcount;if(!ReadLocalMachineRegistryDword(L"SYSTEM\\CurrentControlSet\\Services\\veracrypt",TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME,&count))count=0;returncount;}BOOLLoadSysEncSettings(){BOOLstatus=TRUE;DWORDsize=0;char*sysEncCfgFileBuf=LoadFile(GetConfigPath(TC_APPD_FILENAME_SYSTEM_ENCRYPTION),&size);char*xml=sysEncCfgFileBuf;charparamName[100],paramVal[MAX_PATH];// DefaultsintnewSystemEncryptionStatus=SYSENC_STATUS_NONE;WipeAlgorithmIdnewnWipeMode=TC_WIPE_NONE;if(!FileExists(GetConfigPath(TC_APPD_FILENAME_SYSTEM_ENCRYPTION))){SystemEncryptionStatus=newSystemEncryptionStatus;nWipeMode=newnWipeMode;}if(xml==NULL){returnFALSE;}while(xml=XmlFindElement(xml,"config")){XmlGetAttributeText(xml,"key",paramName,sizeof(paramName));XmlGetNodeText(xml,paramVal,sizeof(paramVal));if(strcmp(paramName,"SystemEncryptionStatus")==0){newSystemEncryptionStatus=atoi(paramVal);}elseif(strcmp(paramName,"WipeMode")==0){newnWipeMode=(WipeAlgorithmId)atoi(paramVal);}xml++;}SystemEncryptionStatus=newSystemEncryptionStatus;nWipeMode=newnWipeMode;free(sysEncCfgFileBuf);returnstatus;}// Returns the number of partitions where non-system in-place encryption is progress or had been in progress// but was interrupted. In addition, via the passed pointer, returns the last selected wipe algorithm ID.intLoadNonSysInPlaceEncSettings(WipeAlgorithmId*wipeAlgorithm){char*fileBuf=NULL;char*fileBuf2=NULL;DWORDsize,size2;intcount;*wipeAlgorithm=TC_WIPE_NONE;if(!FileExists(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC)))return0;if((fileBuf=LoadFile(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC),&size))==NULL)return0;if(FileExists(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE))){if((fileBuf2=LoadFile(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE),&size2))!=NULL)*wipeAlgorithm=(WipeAlgorithmId)atoi(fileBuf2);}count=atoi(fileBuf);if(fileBuf!=NULL)TCfree(fileBuf);if(fileBuf2!=NULL)TCfree(fileBuf2);return(count);}voidRemoveNonSysInPlaceEncNotifications(void){if(FileExists(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC)))_wremove(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC));if(FileExists(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))_wremove(GetConfigPath(TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));if(!IsNonInstallMode()&&SystemEncryptionStatus==SYSENC_STATUS_NONE)ManageStartupSeqWiz(TRUE,L"");}voidSavePostInstallTasksSettings(intcommand){FILE*f=NULL;if(IsNonInstallMode()&&command!=TC_POST_INSTALL_CFG_REMOVE_ALL)return;switch(command){caseTC_POST_INSTALL_CFG_REMOVE_ALL:_wremove(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL));_wremove(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES));_wremove(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK));break;caseTC_POST_INSTALL_CFG_TUTORIAL:f=_wfopen(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL),L"w");break;caseTC_POST_INSTALL_CFG_RELEASE_NOTES:f=_wfopen(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES),L"w");break;caseTC_POST_INSTALL_CFG_RESCUE_DISK:f=_wfopen(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK),L"w");break;default:return;}if(f==NULL)return;if(fputws(L"1",f)<0){// Errorfclose(f);return;}TCFlushFile(f);fclose(f);}voidDoPostInstallTasks(HWNDhwndDlg){BOOLbDone=FALSE;if(FileExists(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_TUTORIAL))){if(AskYesNo("AFTER_INSTALL_TUTORIAL",hwndDlg)==IDYES)Applink("beginnerstutorial");bDone=TRUE;}if(FileExists(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RELEASE_NOTES))){if(AskYesNo("AFTER_UPGRADE_RELEASE_NOTES",hwndDlg)==IDYES)Applink("releasenotes");bDone=TRUE;}if(FileExists(GetConfigPath(TC_APPD_FILENAME_POST_INSTALL_TASK_RESCUE_DISK))){if(AskYesNo("AFTER_UPGRADE_RESCUE_DISK",hwndDlg)==IDYES)PostMessage(hwndDlg,VC_APPMSG_CREATE_RESCUE_DISK,0,0);bDone=TRUE;}if(bDone)SavePostInstallTasksSettings(TC_POST_INSTALL_CFG_REMOVE_ALL);}/* * Use RtlGetVersion to get Windows version because GetVersionEx is affected by application manifestation. */typedefNTSTATUS(WINAPI*RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);staticBOOLGetWindowsVersion(LPOSVERSIONINFOWlpVersionInformation){BOOLbRet=FALSE;RtlGetVersionPtrRtlGetVersionFn=(RtlGetVersionPtr)GetProcAddress(GetModuleHandle(L"ntdll.dll"),"RtlGetVersion");if(RtlGetVersionFn!=NULL){if(ERROR_SUCCESS==RtlGetVersionFn(lpVersionInformation))bRet=TRUE;}if(!bRet)bRet=GetVersionExW(lpVersionInformation);returnbRet;}voidInitOSVersionInfo(){OSVERSIONINFOEXWos;os.dwOSVersionInfoSize=sizeof(OSVERSIONINFOEXW);if(GetWindowsVersion((LPOSVERSIONINFOW)&os)==FALSE)AbortProcess("NO_OS_VER");CurrentOSMajor=os.dwMajorVersion;CurrentOSMinor=os.dwMinorVersion;CurrentOSServicePack=os.wServicePackMajor;if(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==5&&CurrentOSMinor==0)nCurrentOS=WIN_2000;elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==5&&CurrentOSMinor==1)nCurrentOS=WIN_XP;elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==5&&CurrentOSMinor==2){if(os.wProductType==VER_NT_SERVER||os.wProductType==VER_NT_DOMAIN_CONTROLLER)nCurrentOS=WIN_SERVER_2003;elsenCurrentOS=WIN_XP64;}elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==6&&CurrentOSMinor==0){if(os.wProductType!=VER_NT_WORKSTATION)nCurrentOS=WIN_SERVER_2008;elsenCurrentOS=WIN_VISTA;}elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==6&&CurrentOSMinor==1)nCurrentOS=((os.wProductType!=VER_NT_WORKSTATION)?WIN_SERVER_2008_R2:WIN_7);elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==6&&CurrentOSMinor==2)nCurrentOS=((os.wProductType!=VER_NT_WORKSTATION)?WIN_SERVER_2012:WIN_8);elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==6&&CurrentOSMinor==3)nCurrentOS=((os.wProductType!=VER_NT_WORKSTATION)?WIN_SERVER_2012_R2:WIN_8_1);elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==10&&CurrentOSMinor==0)nCurrentOS=((os.wProductType!=VER_NT_WORKSTATION)?WIN_SERVER_2016:WIN_10);elseif(os.dwPlatformId==VER_PLATFORM_WIN32_NT&&CurrentOSMajor==4)nCurrentOS=WIN_NT4;elseif(os.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS&&os.dwMajorVersion==4&&os.dwMinorVersion==0)nCurrentOS=WIN_95;elseif(os.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS&&os.dwMajorVersion==4&&os.dwMinorVersion==10)nCurrentOS=WIN_98;elseif(os.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS&&os.dwMajorVersion==4&&os.dwMinorVersion==90)nCurrentOS=WIN_ME;elseif(os.dwPlatformId==VER_PLATFORM_WIN32s)nCurrentOS=WIN_31;elsenCurrentOS=WIN_UNKNOWN;}staticvoidLoadSystemDll(LPCTSTRszModuleName,HMODULE*pHandle,BOOLbIgnoreError,constchar*srcPos){wchar_tdllPath[MAX_PATH];/* Load dll explictely from System32 to avoid Dll hijacking attacks*/if(!GetSystemDirectory(dllPath,MAX_PATH))StringCbCopyW(dllPath,sizeof(dllPath),L"C:\\Windows\\System32");StringCbCatW(dllPath,sizeof(dllPath),L"\\");StringCbCatW(dllPath,sizeof(dllPath),szModuleName);if(((*pHandle=LoadLibrary(dllPath))==NULL)&&!bIgnoreError){// This error is fatalhandleWin32Error(NULL,srcPos);AbortProcess("INIT_DLL");}}/* InitApp - initialize the application, this function is called once in the applications WinMain function, but before the main dialog has been created */voidInitApp(HINSTANCEhInstance,wchar_t*lpszCommandLine){WNDCLASSWwc;charlangId[6];InitCommonControlsPtrInitCommonControlsFn=NULL;/* remove current directory from dll search path */SetDllDirectoryFn=(SetDllDirectoryPtr)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"SetDllDirectoryW");SetSearchPathModeFn=(SetSearchPathModePtr)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"SetSearchPathMode");SetDefaultDllDirectoriesFn=(SetDefaultDllDirectoriesPtr)GetProcAddress(GetModuleHandle(L"kernel32.dll"),"SetDefaultDllDirectories");if(SetDllDirectoryFn)SetDllDirectoryFn(L"");if(SetSearchPathModeFn)SetSearchPathModeFn(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE|BASE_SEARCH_PATH_PERMANENT);if(SetDefaultDllDirectoriesFn)SetDefaultDllDirectoriesFn(LOAD_LIBRARY_SEARCH_SYSTEM32);InitOSVersionInfo();VirtualLock(&CmdTokenPin,sizeof(CmdTokenPin));InitGlobalLocks();LoadSystemDll(L"ntmarta.dll",&hntmartadll,TRUE,SRC_POS);LoadSystemDll(L"MPR.DLL",&hmprdll,TRUE,SRC_POS);#ifdef SETUPif(IsOSAtLeast(WIN_7)){LoadSystemDll(L"ProfApi.DLL",&hProfApiDll,TRUE,SRC_POS);LoadSystemDll(L"cryptbase.dll",&hcryptbasedll,TRUE,SRC_POS);LoadSystemDll(L"sspicli.dll",&hsspiclidll,TRUE,SRC_POS);}#endifLoadSystemDll(L"psapi.dll",&hpsapidll,TRUE,SRC_POS);LoadSystemDll(L"secur32.dll",&hsecur32dll,TRUE,SRC_POS);LoadSystemDll(L"msasn1.dll",&hmsasn1dll,TRUE,SRC_POS);LoadSystemDll(L"Usp10.DLL",&hUsp10Dll,TRUE,SRC_POS);if(IsOSAtLeast(WIN_7))LoadSystemDll(L"dwmapi.dll",&hdwmapidll,TRUE,SRC_POS);LoadSystemDll(L"UXTheme.dll",&hUXThemeDll,TRUE,SRC_POS);LoadSystemDll(L"msls31.dll",&hMsls31,TRUE,SRC_POS);LoadSystemDll(L"SETUPAPI.DLL",&hSetupDll,FALSE,SRC_POS);LoadSystemDll(L"SHLWAPI.DLL",&hShlwapiDll,FALSE,SRC_POS);LoadSystemDll(L"userenv.dll",&hUserenvDll,TRUE,SRC_POS);LoadSystemDll(L"rsaenh.dll",&hRsaenhDll,TRUE,SRC_POS);#ifdef SETUPif(nCurrentOS<WIN_7){if(nCurrentOS==WIN_XP){LoadSystemDll(L"imm32.dll",&himm32dll,TRUE,SRC_POS);LoadSystemDll(L"MSCTF.dll",&hMSCTFdll,TRUE,SRC_POS);LoadSystemDll(L"fltlib.dll",&hfltlibdll,TRUE,SRC_POS);LoadSystemDll(L"wbem\\framedyn.dll",&hframedyndll,TRUE,SRC_POS);}if(IsOSAtLeast(WIN_VISTA)){LoadSystemDll(L"netapi32.dll",&hnetapi32dll,TRUE,SRC_POS);LoadSystemDll(L"authz.dll",&hauthzdll,TRUE,SRC_POS);LoadSystemDll(L"xmllite.dll",&hxmllitedll,TRUE,SRC_POS);}}if(IsOSAtLeast(WIN_VISTA)){LoadSystemDll(L"atl.dll",&hsppdll,TRUE,SRC_POS);LoadSystemDll(L"vsstrace.dll",&hvsstracedll,TRUE,SRC_POS);LoadSystemDll(L"vssapi.dll",&vssapidll,TRUE,SRC_POS);LoadSystemDll(L"spp.dll",&hsppdll,TRUE,SRC_POS);if(IsOSAtLeast(WIN_7)){LoadSystemDll(L"CryptSP.dll",&hCryptSpDll,TRUE,SRC_POS);LoadSystemDll(L"cfgmgr32.dll",&hcfgmgr32dll,TRUE,SRC_POS);LoadSystemDll(L"devobj.dll",&hdevobjdll,TRUE,SRC_POS);LoadSystemDll(L"powrprof.dll",&hpowrprofdll,TRUE,SRC_POS);LoadSystemDll(L"crypt32.dll",&hcrypt32dll,TRUE,SRC_POS);LoadSystemDll(L"bcrypt.dll",&hbcryptdll,TRUE,SRC_POS);LoadSystemDll(L"bcryptprimitives.dll",&hbcryptprimitivesdll,TRUE,SRC_POS);}}#elseLoadSystemDll(L"WINSCARD.DLL",&hwinscarddll,TRUE,SRC_POS);#endifLoadSystemDll(L"COMCTL32.DLL",&hComctl32Dll,FALSE,SRC_POS);// call InitCommonControls functionInitCommonControlsFn=(InitCommonControlsPtr)GetProcAddress(hComctl32Dll,"InitCommonControls");ImageList_AddFn=(ImageList_AddPtr)GetProcAddress(hComctl32Dll,"ImageList_Add");ImageList_CreateFn=(ImageList_CreatePtr)GetProcAddress(hComctl32Dll,"ImageList_Create");if(InitCommonControlsFn&&ImageList_AddFn&&ImageList_CreateFn){InitCommonControlsFn();}elseAbortProcess("INIT_DLL");LoadSystemDll(L"Riched20.dll",&hRichEditDll,FALSE,SRC_POS);// Get SetupAPI functions pointersSetupCloseInfFileFn=(SetupCloseInfFilePtr)GetProcAddress(hSetupDll,"SetupCloseInfFile");SetupDiOpenClassRegKeyFn=(SetupDiOpenClassRegKeyPtr)GetProcAddress(hSetupDll,"SetupDiOpenClassRegKey");SetupInstallFromInfSectionWFn=(SetupInstallFromInfSectionWPtr)GetProcAddress(hSetupDll,"SetupInstallFromInfSectionW");SetupOpenInfFileWFn=(SetupOpenInfFileWPtr)GetProcAddress(hSetupDll,"SetupOpenInfFileW");if(!SetupCloseInfFileFn||!SetupDiOpenClassRegKeyFn||!SetupInstallFromInfSectionWFn||!SetupOpenInfFileWFn)AbortProcess("INIT_DLL");// Get SHDeleteKeyW function pointerSHDeleteKeyWFn=(SHDeleteKeyWPtr)GetProcAddress(hShlwapiDll,"SHDeleteKeyW");SHStrDupWFn=(SHStrDupWPtr)GetProcAddress(hShlwapiDll,"SHStrDupW");if(!SHDeleteKeyWFn||!SHStrDupWFn)AbortProcess("INIT_DLL");if(IsOSAtLeast(WIN_VISTA)){/* Get ChangeWindowMessageFilter used to enable some messages bypasss UIPI (User Interface Privilege Isolation) */ChangeWindowMessageFilterFn=(ChangeWindowMessageFilterPtr)GetProcAddress(GetModuleHandle(L"user32.dll"),"ChangeWindowMessageFilter");#ifndef SETUP/* enable drag-n-drop when we are running elevated */AllowMessageInUIPI(WM_DROPFILES);AllowMessageInUIPI(WM_COPYDATA);AllowMessageInUIPI(WM_COPYGLOBALDATA);#endif}/* Save the instance handle for later */hInst=hInstance;SetErrorMode(SetErrorMode(0)|SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);CoInitialize(NULL);#ifndef SETUP// Application IDtypedefHRESULT(WINAPI*SetAppId_t)(PCWSTRappID);SetAppId_tsetAppId=(SetAppId_t)GetProcAddress(GetModuleHandle(L"shell32.dll"),"SetCurrentProcessExplicitAppUserModelID");if(setAppId)setAppId(TC_APPLICATION_ID);#endif// LanguagelangId[0]=0;SetPreferredLangId(ConfigReadString("Language","",langId,sizeof(langId)));if(langId[0]==0){if(IsNonInstallMode()){// only support automatic use of a language file in portable mode// this is achieved by placing a unique language XML file in the same// place as portable VeraCrypt binaries.DialogBoxParamW(hInst,MAKEINTRESOURCEW(IDD_LANGUAGE),NULL,(DLGPROC)LanguageDlgProc,(LPARAM)1);}else{// when installed, force using English as default languageSetPreferredLangId("en");}}LoadLanguageFile();#ifndef SETUP// UAC elevation moniker cannot be used in portable mode.// A new instance of the application must be created with elevated privileges.if(IsNonInstallMode()&&!IsAdmin()&&IsUacSupported()){wchar_tmodPath[MAX_PATH];if(wcsstr(lpszCommandLine,L"/q UAC ")==lpszCommandLine){Error("UAC_INIT_ERROR",NULL);exit(1);}GetModuleFileNameW(NULL,modPath,ARRAYSIZE(modPath));if(LaunchElevatedProcess(NULL,modPath,lpszCommandLine))exit(0);elseexit(1);}#endifSetUnhandledExceptionFilter(ExceptionHandler);_set_invalid_parameter_handler(InvalidParameterHandler);RemoteSession=GetSystemMetrics(SM_REMOTESESSION)!=0;// OS version checkif(CurrentOSMajor<5){MessageBoxW(NULL,GetString("UNSUPPORTED_OS"),lpszTitle,MB_ICONSTOP);exit(1);}else{// Service pack check & warnings about critical MS issuesswitch(nCurrentOS){caseWIN_2000:if(CurrentOSServicePack<3)Warning("LARGE_IDE_WARNING_2K",NULL);else{DWORDval=0,size=sizeof(val);HKEYhkey;if(RegOpenKeyExW(HKEY_LOCAL_MACHINE,L"SYSTEM\\CurrentControlSet\\Services\\Atapi\\Parameters",0,KEY_READ,&hkey)==ERROR_SUCCESS){if(RegQueryValueExW(hkey,L"EnableBigLba",0,0,(LPBYTE)&val,&size)!=ERROR_SUCCESS||val!=1){Warning("LARGE_IDE_WARNING_2K_REGISTRY",NULL);}RegCloseKey(hkey);}}break;caseWIN_XP:if(CurrentOSServicePack<1){HKEYk;// PE environment does not report version of SPif(RegOpenKeyExW(HKEY_LOCAL_MACHINE,L"System\\CurrentControlSet\\Control\\minint",0,KEY_READ,&k)!=ERROR_SUCCESS)Warning("LARGE_IDE_WARNING_XP",NULL);elseRegCloseKey(k);}break;}}/* Get the attributes for the standard dialog class */if((GetClassInfoW(hInst,WINDOWS_DIALOG_CLASS,&wc))==0){handleWin32Error(NULL,SRC_POS);AbortProcess("INIT_REGISTER");}#ifndef SETUPwc.hIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_TRUECRYPT_ICON));#else#include"../setup/resource.h"wc.hIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_SETUP));#endifwc.lpszClassName=TC_DLG_CLASS;wc.lpfnWndProc=&CustomDlgProc;wc.hCursor=LoadCursor(NULL,IDC_ARROW);wc.cbWndExtra=DLGWINDOWEXTRA;hDlgClass=RegisterClassW(&wc);if(hDlgClass==0){handleWin32Error(NULL,SRC_POS);AbortProcess("INIT_REGISTER");}wc.lpszClassName=TC_SPLASH_CLASS;wc.lpfnWndProc=&SplashDlgProc;wc.hCursor=LoadCursor(NULL,IDC_ARROW);wc.cbWndExtra=DLGWINDOWEXTRA;hSplashClass=RegisterClassW(&wc);if(hSplashClass==0){handleWin32Error(NULL,SRC_POS);AbortProcess("INIT_REGISTER");}// DPI and GUI aspect ratioDialogBoxParamW(hInst,MAKEINTRESOURCEW(IDD_AUXILIARY_DLG),NULL,(DLGPROC)AuxiliaryDlgProc,(LPARAM)1);InitHelpFileName();#ifndef SETUPif(!EncryptionThreadPoolStart(ReadEncryptionThreadPoolFreeCpuCountLimit())){handleWin32Error(NULL,SRC_POS);FREE_DLL(hRichEditDll);FREE_DLL(hComctl32Dll);FREE_DLL(hSetupDll);FREE_DLL(hShlwapiDll);FREE_DLL(hProfApiDll);FREE_DLL(hUsp10Dll);FREE_DLL(hCryptSpDll);FREE_DLL(hUXThemeDll);FREE_DLL(hUserenvDll);FREE_DLL(hRsaenhDll);FREE_DLL(himm32dll);FREE_DLL(hMSCTFdll);FREE_DLL(hfltlibdll);FREE_DLL(hframedyndll);FREE_DLL(hpsapidll);FREE_DLL(hsecur32dll);FREE_DLL(hnetapi32dll);FREE_DLL(hauthzdll);FREE_DLL(hxmllitedll);FREE_DLL(hmprdll);FREE_DLL(hsppdll);FREE_DLL(vssapidll);FREE_DLL(hvsstracedll);FREE_DLL(hCryptSpDll);FREE_DLL(hcfgmgr32dll);FREE_DLL(hdevobjdll);FREE_DLL(hpowrprofdll);FREE_DLL(hsspiclidll);FREE_DLL(hcryptbasedll);FREE_DLL(hdwmapidll);FREE_DLL(hmsasn1dll);FREE_DLL(hcrypt32dll);FREE_DLL(hbcryptdll);FREE_DLL(hbcryptprimitivesdll);FREE_DLL(hMsls31);FREE_DLL(hntmartadll);FREE_DLL(hwinscarddll);exit(1);}#endif}voidFinalizeApp(void){FREE_DLL(hRichEditDll);FREE_DLL(hComctl32Dll);FREE_DLL(hSetupDll);FREE_DLL(hShlwapiDll);FREE_DLL(hProfApiDll);FREE_DLL(hUsp10Dll);FREE_DLL(hCryptSpDll);FREE_DLL(hUXThemeDll);FREE_DLL(hUserenvDll);FREE_DLL(hRsaenhDll);FREE_DLL(himm32dll);FREE_DLL(hMSCTFdll);FREE_DLL(hfltlibdll);FREE_DLL(hframedyndll);FREE_DLL(hpsapidll);FREE_DLL(hsecur32dll);FREE_DLL(hnetapi32dll);FREE_DLL(hauthzdll);FREE_DLL(hxmllitedll);FREE_DLL(hmprdll);FREE_DLL(hsppdll);FREE_DLL(vssapidll);FREE_DLL(hvsstracedll);FREE_DLL(hCryptSpDll);FREE_DLL(hcfgmgr32dll);FREE_DLL(hdevobjdll);FREE_DLL(hpowrprofdll);FREE_DLL(hsspiclidll);FREE_DLL(hcryptbasedll);FREE_DLL(hdwmapidll);FREE_DLL(hmsasn1dll);FREE_DLL(hcrypt32dll);FREE_DLL(hbcryptdll);FREE_DLL(hbcryptprimitivesdll);FREE_DLL(hMsls31);FREE_DLL(hntmartadll);FREE_DLL(hwinscarddll);}voidInitHelpFileName(void){wchar_t*lpszTmp;GetModuleFileNameW(NULL,szHelpFile,ARRAYSIZE(szHelpFile));lpszTmp=wcsrchr(szHelpFile,L'\\');if(lpszTmp){wchar_tszTemp[TC_MAX_PATH];++lpszTmp;*lpszTmp=0;// add null terminating character to prepare for append operations// Primary file nameif(strcmp(GetPreferredLangId(),"en")==0||strlen(GetPreferredLangId())==0){StringCbCatW(szHelpFile,sizeof(szHelpFile),L"docs\\VeraCrypt User Guide.chm");}else{StringCbPrintfW(szTemp,sizeof(szTemp),L"docs\\VeraCrypt User Guide.%S.chm",GetPreferredLangId());StringCbCatW(szHelpFile,sizeof(szHelpFile),szTemp);}// Secondary file name (used when localized documentation is not found).GetModuleFileNameW(NULL,szHelpFile2,ARRAYSIZE(szHelpFile2));lpszTmp=wcsrchr(szHelpFile2,L'\\');if(lpszTmp){++lpszTmp;*lpszTmp=0;StringCbCatW(szHelpFile2,sizeof(szHelpFile2),L"docs\\VeraCrypt User Guide.chm");}}}#ifndef SETUPBOOLOpenDevice(constwchar_t*lpszPath,OPEN_TEST_STRUCT*driver,BOOLdetectFilesystem,BOOLcomputeVolumeIDs){DWORDdwResult;BOOLbResult;wchar_twszFileName[TC_MAX_PATH];StringCbCopyW(wszFileName,sizeof(wszFileName),lpszPath);memset(driver,0,sizeof(OPEN_TEST_STRUCT));memcpy(driver->wszFileName,wszFileName,sizeof(wszFileName));driver->bDetectTCBootLoader=FALSE;driver->DetectFilesystem=detectFilesystem;driver->bComputeVolumeIDs=computeVolumeIDs;bResult=DeviceIoControl(hDriver,TC_IOCTL_OPEN_TEST,driver,sizeof(OPEN_TEST_STRUCT),driver,sizeof(OPEN_TEST_STRUCT),&dwResult,NULL);// check variable driverif(bResult&&((driver->bDetectTCBootLoader!=TRUE&&driver->bDetectTCBootLoader!=FALSE)||(driver->TCBootLoaderDetected!=TRUE&&driver->TCBootLoaderDetected!=FALSE)||(driver->DetectFilesystem!=TRUE&&driver->DetectFilesystem!=FALSE)||(driver->FilesystemDetected!=TRUE&&driver->FilesystemDetected!=FALSE)||(wcscmp(wszFileName,driver->wszFileName)))){returnFALSE;}if(bResult==FALSE){dwResult=GetLastError();if(dwResult==ERROR_SHARING_VIOLATION||dwResult==ERROR_NOT_READY){driver->TCBootLoaderDetected=FALSE;driver->FilesystemDetected=FALSE;memset(driver->VolumeIDComputed,0,sizeof(driver->VolumeIDComputed));returnTRUE;}elsereturnFALSE;}returnTRUE;}#endif// Tells the driver that it's running in portable modevoidNotifyDriverOfPortableMode(void){if(hDriver!=INVALID_HANDLE_VALUE){DWORDdwResult;DeviceIoControl(hDriver,TC_IOCTL_SET_PORTABLE_MODE_STATUS,NULL,0,NULL,0,&dwResult,NULL);}}BOOLGetDriveLabel(intdriveNo,wchar_t*label,intlabelSize){DWORDfileSystemFlags;wchar_troot[]={L'A'+(wchar_t)driveNo,L':',L'\\',0};returnGetVolumeInformationW(root,label,labelSize/2,NULL,NULL,&fileSystemFlags,NULL,0);}#ifndef SETUP/* Stores the device path of the system partition in SysPartitionDevicePath and the device path of the system drivein SysDriveDevicePath.IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user selected the system partition/device.After this function completes successfully, the results are cached for the rest of the session and repeatedexecutions complete very fast. Returns TRUE if successful (otherwise FALSE). */BOOLGetSysDevicePaths(HWNDhwndDlg){if(!bCachedSysDevicePathsValid||wcslen(SysPartitionDevicePath)<=1||wcslen(SysDriveDevicePath)<=1){foreach(constHostDevice&device,GetAvailableHostDevices(false,true)){if(device.ContainsSystem)StringCchCopyW(device.IsPartition?SysPartitionDevicePath:SysDriveDevicePath,TC_MAX_PATH,device.Path.c_str());}if(IsOSAtLeast(WIN_7)){// Find extra boot partitionforeach(constHostDevice&drive,GetAvailableHostDevices(false,false)){if(drive.ContainsSystem){foreach(constHostDevice&sysDrivePartition,drive.Partitions){if(sysDrivePartition.Bootable){if(sysDrivePartition.Size<=TC_MAX_EXTRA_BOOT_PARTITION_SIZE)ExtraBootPartitionDevicePath=sysDrivePartition.Path;break;}}break;}}}bCachedSysDevicePathsValid=1;}return(bCachedSysDevicePathsValid&&wcslen(SysPartitionDevicePath)>1&&wcslen(SysDriveDevicePath)>1);}/* Determines whether the device path is the path of the system partition or of the system drive (or neither). If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon. If it's FALSE and the function is called for the first time, execution may take up to one minute but theresults are reliable.IMPORTANT: As the execution may take a very long time if called for the first time with bReliableRequired set to TRUE, it should be called with bReliableRequired set to TRUE only before performing a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never at WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user selected the system partition/device).After this function completes successfully, the results are cached for the rest of the session, bReliableRequiredis ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable. Return codes:1 - it is the system partition path (e.g. \Device\Harddisk0\Partition1)2 - it is the system drive path (e.g. \Device\Harddisk0\Partition0)3 - it is the extra boot partition path0 - it's not the system partition/drive path-1 - the result can't be determined, isn't reliable, or there was an error. */intIsSystemDevicePath(constwchar_t*path,HWNDhwndDlg,BOOLbReliableRequired){if(!bCachedSysDevicePathsValid&&bReliableRequired){if(!GetSysDevicePaths(hwndDlg))return-1;}if(wcslen(SysPartitionDevicePath)<=1||wcslen(SysDriveDevicePath)<=1)return-1;if(!path)return-1;if(wcsncmp(path,SysPartitionDevicePath,max(wcslen(path),wcslen(SysPartitionDevicePath)))==0)return1;elseif(wcsncmp(path,SysDriveDevicePath,max(wcslen(path),wcslen(SysDriveDevicePath)))==0)return2;elseif(ExtraBootPartitionDevicePath==path)return3;return0;}/* Determines whether the path points to a non-system partition on the system drive.IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events. Return codes:0 - it isn't a non-system partition on the system drive 1 - it's a non-system partition on the system drive -1 - the result can't be determined, isn't reliable, or there was an error. */intIsNonSysPartitionOnSysDrive(constwchar_t*path){wchar_ttmpPath[TC_MAX_PATH+1];intpos;if(!GetSysDevicePaths(MainDlg))return-1;if(wcslen(SysPartitionDevicePath)<=1||wcslen(SysDriveDevicePath)<=1)return-1;if(wcsncmp(path,SysPartitionDevicePath,max(wcslen(path),wcslen(SysPartitionDevicePath)))==0||wcsncmp(path,SysDriveDevicePath,max(wcslen(path),wcslen(SysDriveDevicePath)))==0){// It is the system partition/drive path (it isn't a non-system partition)return0;}memset(tmpPath,0,sizeof(tmpPath));wcsncpy(tmpPath,path,ARRAYSIZE(tmpPath)-1);pos=(int)FindString((constchar*)tmpPath,(constchar*)L"Partition",(int)wcslen(tmpPath)*2,(int)wcslen(L"Partition")*2,0);if(pos<0)return-1;pos/=2;pos+=(int)strlen("Partition");if(pos+1>ARRAYSIZE(tmpPath)-1)return-1;tmpPath[pos]=L'0';tmpPath[pos+1]=0;if(wcsncmp(tmpPath,SysDriveDevicePath,max(wcslen(tmpPath),wcslen(SysDriveDevicePath)))==0){// It is a non-system partition on the system drive return1;}else{// The partition is not on the system drive return0;}}#endif //!SETUPwstringGetSysEncryptionPretestInfo2String(void){// This huge string is divided into smaller portions to make it easier for translators to// re-translate it when a minor modification is made to it (the whole huge string will not be// reverted to English, so they will have to translate only a small portion of it).return(wstring(L"\n")+GetString("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_1")+GetString("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_2")+GetString("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_3")+GetString("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_4"));}wstringGetRescueDiskHelpString(void){// This huge string is divided into smaller portions to make it easier for translators to// re-translate it when a minor modification is made to it (the whole huge string will not be// reverted to English, so they will have to translate only a small portion of it).return(wstring(GetString("RESCUE_DISK_HELP_PORTION_1"))+GetString("RESCUE_DISK_HELP_PORTION_2")+GetString("RESCUE_DISK_HELP_PORTION_3")+GetString("RESCUE_DISK_HELP_PORTION_4")+GetString("RESCUE_DISK_HELP_PORTION_5")+GetString("RESCUE_DISK_HELP_PORTION_6")+GetString("RESCUE_DISK_HELP_PORTION_7")+GetString("RESCUE_DISK_HELP_PORTION_8")+GetString("RESCUE_DISK_HELP_PORTION_9"));}wstringGetDecoyOsInstructionsString(void){// This huge string is divided into smaller portions to make it easier for translators to// re-translate it when a minor modification is made to it (the whole huge string will not be// reverted to English, so they will have to translate only a small portion of it).return(wstring(GetString("DECOY_OS_INSTRUCTIONS_PORTION_1"))+GetString("DECOY_OS_INSTRUCTIONS_PORTION_2")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_3")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_4")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_5")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_6")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_7")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_8")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_9")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_10")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_11")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_12")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_13")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_14")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_15")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_16")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_17")+GetString("DECOY_OS_INSTRUCTIONS_PORTION_18"));}struct_TEXT_EDIT_DIALOG_PARAM{BOOLReadOnly;std::string&Text;constWCHAR*Title;_TEXT_EDIT_DIALOG_PARAM(BOOL_readOnly,constWCHAR*title,std::string&_text):Title(title),Text(_text),ReadOnly(_readOnly){}_TEXT_EDIT_DIALOG_PARAM&operator=(const_TEXT_EDIT_DIALOG_PARAM&other){ReadOnly=other.ReadOnly;Text=other.Text;Title=other.Title;return*this;}};typedefstruct_TEXT_EDIT_DIALOG_PARAMTEXT_INFO_DIALOG_PARAM,*TEXT_INFO_DIALOG_PARAM_PTR;INT_PTRTextEditDialogBox(BOOLreadOnly,HWNDparent,constWCHAR*Title,std::string&text){TEXT_INFO_DIALOG_PARAMpm(readOnly,Title,text);returnDialogBoxParamW(hInst,MAKEINTRESOURCEW(IDD_TEXT_EDIT_DLG),parent,(DLGPROC)TextEditDlgProc,(LPARAM)&pm);}BOOLCALLBACKTextEditDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){WORDlw=LOWORD(wParam);staticintnID=0;staticTEXT_INFO_DIALOG_PARAM_PTRprm;switch(msg){caseWM_INITDIALOG:{prm=(TEXT_INFO_DIALOG_PARAM_PTR)lParam;// increase size limit of rich edit controlSendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),EM_EXLIMITTEXT,0,-1);SetWindowTextW(hwndDlg,prm->Title);// Left margin for rich edit text fieldSendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),EM_SETMARGINS,(WPARAM)EC_LEFTMARGIN,(LPARAM)CompensateXDPI(4));if(prm->ReadOnly){// switch rich edit control to ReadOnlySendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),ES_READONLY,TRUE,0);// hide cancel buttonShowWindow(GetDlgItem(hwndDlg,IDCANCEL),SW_HIDE);}SendMessage(hwndDlg,TC_APPMSG_LOAD_TEXT_BOX_CONTENT,0,0);}return0;caseWM_COMMAND:if(lw==IDOK){if(!prm->ReadOnly){prm->Text.resize(GetWindowTextLengthA(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT))+1);GetWindowTextA(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),&(prm->Text)[0],(int)prm->Text.size());}NormalCursor();EndDialog(hwndDlg,IDOK);return1;}if(lw==IDCANCEL){NormalCursor();EndDialog(hwndDlg,IDCANCEL);return1;}return0;caseTC_APPMSG_LOAD_TEXT_BOX_CONTENT:{SetWindowTextA(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),prm->Text.c_str());}return0;caseWM_CLOSE:NormalCursor();EndDialog(hwndDlg,0);return1;}return0;}INT_PTRTextInfoDialogBox(intnID){returnDialogBoxParamW(hInst,MAKEINTRESOURCEW(IDD_TEXT_INFO_DIALOG_BOX_DLG),MainDlg,(DLGPROC)TextInfoDialogBoxDlgProc,(LPARAM)nID);}BOOLCALLBACKTextInfoDialogBoxDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){WORDlw=LOWORD(wParam);staticintnID=0;switch(msg){caseWM_INITDIALOG:{nID=(int)lParam;// increase size limit of rich edit controlSendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),EM_EXLIMITTEXT,0,-1);// Left margin for rich edit text fieldSendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),EM_SETMARGINS,(WPARAM)EC_LEFTMARGIN,(LPARAM)CompensateXDPI(4));ShowWindow(GetDlgItem(hwndDlg,IDC_PRINT),SW_HIDE);switch(nID){caseTC_TBXID_LEGAL_NOTICES:LocalizeDialog(hwndDlg,"LEGAL_NOTICES_DLG_TITLE");break;caseTC_TBXID_SYS_ENCRYPTION_PRETEST:LocalizeDialog(hwndDlg,NULL);ShowWindow(GetDlgItem(hwndDlg,IDC_PRINT),SW_SHOW);break;caseTC_TBXID_SYS_ENC_RESCUE_DISK:LocalizeDialog(hwndDlg,NULL);ShowWindow(GetDlgItem(hwndDlg,IDC_PRINT),SW_SHOW);break;caseTC_TBXID_DECOY_OS_INSTRUCTIONS:LocalizeDialog(hwndDlg,NULL);ShowWindow(GetDlgItem(hwndDlg,IDC_PRINT),SW_SHOW);break;caseTC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS:LocalizeDialog(hwndDlg,NULL);ShowWindow(GetDlgItem(hwndDlg,IDC_PRINT),SW_SHOW);break;}SendMessage(hwndDlg,TC_APPMSG_LOAD_TEXT_BOX_CONTENT,0,0);}return0;caseWM_COMMAND:if(lw==IDOK||lw==IDCANCEL){NormalCursor();EndDialog(hwndDlg,0);return1;}if(lw==IDC_PRINT){switch(nID){caseTC_TBXID_SYS_ENCRYPTION_PRETEST:PrintHardCopyTextUTF16((wchar_t*)GetSysEncryptionPretestInfo2String().c_str(),L"Pre-Boot Troubleshooting",GetSysEncryptionPretestInfo2String().length()*2);break;caseTC_TBXID_SYS_ENC_RESCUE_DISK:PrintHardCopyTextUTF16((wchar_t*)GetRescueDiskHelpString().c_str(),L"VeraCrypt Rescue Disk Help",GetRescueDiskHelpString().length()*2);break;caseTC_TBXID_DECOY_OS_INSTRUCTIONS:PrintHardCopyTextUTF16((wchar_t*)GetDecoyOsInstructionsString().c_str(),L"How to Create Decoy OS",GetDecoyOsInstructionsString().length()*2);break;caseTC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS:PrintHardCopyTextUTF16(GetString("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS"),L"How to Remove Extra Boot Partition",wcslen(GetString("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS"))*2);break;}return1;}return0;caseTC_APPMSG_LOAD_TEXT_BOX_CONTENT:{char*r=NULL;switch(nID){caseTC_TBXID_LEGAL_NOTICES:LocalizeDialog(hwndDlg,"LEGAL_NOTICES_DLG_TITLE");r=GetLegalNotices();if(r!=NULL){SETTEXTEXTextInfo={0};TextInfo.flags=ST_SELECTION;TextInfo.codepage=CP_ACP;SendMessage(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),EM_SETTEXTEX,(WPARAM)&TextInfo,(LPARAM)r);free(r);}break;caseTC_TBXID_SYS_ENCRYPTION_PRETEST:LocalizeDialog(hwndDlg,NULL);SetWindowTextW(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),(wchar_t*)GetSysEncryptionPretestInfo2String().c_str());break;caseTC_TBXID_SYS_ENC_RESCUE_DISK:LocalizeDialog(hwndDlg,NULL);SetWindowTextW(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),(wchar_t*)GetRescueDiskHelpString().c_str());break;caseTC_TBXID_DECOY_OS_INSTRUCTIONS:LocalizeDialog(hwndDlg,NULL);SetWindowTextW(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),(wchar_t*)GetDecoyOsInstructionsString().c_str());break;caseTC_TBXID_EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS:LocalizeDialog(hwndDlg,NULL);SetWindowTextW(GetDlgItem(hwndDlg,IDC_INFO_BOX_TEXT),GetString("EXTRA_BOOT_PARTITION_REMOVAL_INSTRUCTIONS"));break;}}return1;caseWM_CLOSE:NormalCursor();EndDialog(hwndDlg,0);return1;}return0;}char*GetLegalNotices(){staticchar*resource;staticDWORDsize;char*buf=NULL;if(resource==NULL)resource=(char*)MapResource(L"Text",IDR_LICENSE,&size);if(resource!=NULL){buf=(char*)malloc(size+1);if(buf!=NULL){memcpy(buf,resource,size);buf[size]=0;}}returnbuf;}#ifndef SETUPBOOLCALLBACKRawDevicesDlgProc(HWNDhwndDlg,UINTmsg,WPARAMwParam,LPARAMlParam){staticwchar_t*lpszFileName;// This is actually a pointer to a GLOBAL arraystaticvector<HostDevice>devices;staticmap<int,HostDevice>itemToDeviceMap;WORDlw=LOWORD(wParam);switch(msg){caseWM_INITDIALOG:{LVCOLUMNWLvCol;HWNDhList=GetDlgItem(hwndDlg,IDC_DEVICELIST);RawDevicesDlgParam*pDlgParam=(RawDevicesDlgParam*)lParam;LocalizeDialog(hwndDlg,"IDD_RAWDEVICES_DLG");SendMessage(hList,LVM_SETEXTENDEDLISTVIEWSTYLE,0,LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_TWOCLICKACTIVATE|LVS_EX_LABELTIP);memset(&LvCol,0,sizeof(LvCol));LvCol.mask=LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM|LVCF_FMT;LvCol.pszText=GetString("DEVICE");LvCol.cx=CompensateXDPI(186);LvCol.fmt=LVCFMT_LEFT;SendMessage(hList,LVM_INSERTCOLUMNW,0,(LPARAM)&LvCol);LvCol.pszText=GetString("DRIVE");LvCol.cx=CompensateXDPI(38);LvCol.fmt=LVCFMT_LEFT;SendMessage(hList,LVM_INSERTCOLUMNW,1,(LPARAM)&LvCol);LvCol.pszText=GetString("SIZE");LvCol.cx=CompensateXDPI(64);LvCol.fmt=LVCFMT_RIGHT;SendMessage(hList,LVM_INSERTCOLUMNW,2,(LPARAM)&LvCol);LvCol.pszText=GetString("LABEL");LvCol.cx=CompensateXDPI(128);LvCol.fmt=LVCFMT_LEFT;SendMessage(hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol);devices.clear();itemToDeviceMap.clear();if(pDlgParam->devices.empty()){WaitCursor();devices=GetAvailableHostDevices(false,true,false);NormalCursor();}elsedevices=pDlgParam->devices;if(devices.empty()){MessageBoxW(hwndDlg,GetString("RAWDEVICES"),lpszTitle,ICON_HAND);EndDialog(hwndDlg,IDCANCEL);return1;}intline=1;LVITEMitem;memset(&item,0,sizeof(item));item.mask=LVIF_TEXT;foreach(constHostDevice&device,devices){item.iSubItem=1;if(device.ContainsSystem){if(device.IsPartition)StringCbCopyW(SysPartitionDevicePath,sizeof(SysPartitionDevicePath),device.Path.c_str());elseStringCbCopyW(SysDriveDevicePath,sizeof(SysDriveDevicePath),device.Path.c_str());}// Pathif(!device.IsPartition||device.DynamicVolume){if(!device.Floppy&&(device.Size==0)&&(device.IsPartition||device.Partitions.empty()||device.Partitions[0].Size==0))continue;if(line>1){ListItemAdd(hList,item.iItem,L"");item.iItem=line++;}if(device.Floppy||device.DynamicVolume){ListItemAdd(hList,item.iItem,(wchar_t*)device.Path.c_str());}else{wchar_ts[1024];if(device.Removable)StringCbPrintfW(s,sizeof(s),L"%s %d",GetString("REMOVABLE_DISK"),device.SystemNumber);elseStringCbPrintfW(s,sizeof(s),L"%s %d",GetString("HARDDISK"),device.SystemNumber);if(!device.Partitions.empty())StringCbCatW(s,sizeof(s),L":");ListItemAdd(hList,item.iItem,s);}}else{ListItemAdd(hList,item.iItem,(wchar_t*)device.Path.c_str());}itemToDeviceMap[item.iItem]=device;// Sizeif(device.Size!=0){wchar_tsize[100]={0};GetSizeString(device.Size,size,sizeof(size));ListSubItemSet(hList,item.iItem,2,size);}// Mount pointif(!device.MountPoint.empty())ListSubItemSet(hList,item.iItem,1,(wchar_t*)device.MountPoint.c_str());// Labelif(!device.Name.empty())ListSubItemSet(hList,item.iItem,3,(wchar_t*)device.Name.c_str());#ifdef TCMOUNTelse{booluseInExplorer=false;wstringfavoriteLabel=GetFavoriteVolumeLabel(device.Path,useInExplorer);if(!favoriteLabel.empty())ListSubItemSet(hList,item.iItem,3,(wchar_t*)favoriteLabel.c_str());}#endifitem.iItem=line++;}SendMessageW(hList,LVM_SETCOLUMNWIDTH,0,MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER,0));SendMessageW(hList,LVM_SETCOLUMNWIDTH,1,MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER,0));SendMessageW(hList,LVM_SETCOLUMNWIDTH,2,MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER,0));SendMessageW(hList,LVM_SETCOLUMNWIDTH,3,MAKELPARAM(LVSCW_AUTOSIZE_USEHEADER,0));lpszFileName=pDlgParam->pszFileName;#ifdef VOLFORMATEnableWindow(GetDlgItem(hwndDlg,IDOK),FALSE);#endifreturn1;}caseWM_COMMAND:caseWM_NOTIFY:// catch non-device line selectedif(msg==WM_NOTIFY&&((LPNMHDR)lParam)->code==LVN_ITEMCHANGED&&(((LPNMLISTVIEW)lParam)->uNewState&LVIS_FOCUSED)){BOOLbEnableOkButton=FALSE;LVITEMLvItem;memset(&LvItem,0,sizeof(LvItem));LvItem.mask=LVIF_TEXT|LVIF_PARAM;LvItem.iItem=((LPNMLISTVIEW)lParam)->iItem;LvItem.pszText=lpszFileName;LvItem.cchTextMax=TC_MAX_PATH;lpszFileName[0]=0;SendMessage(GetDlgItem(hwndDlg,IDC_DEVICELIST),LVM_GETITEM,LvItem.iItem,(LPARAM)&LvItem);if(lpszFileName[0]!=0&&lpszFileName[0]!=' '){bEnableOkButton=TRUE;#ifdef VOLFORMATif(bInPlaceEncNonSysResumed&&(WizardMode==WIZARD_MODE_NONSYS_DEVICE)&&LvItem.iItem!=-1&&itemToDeviceMap.find(LvItem.iItem)!=itemToDeviceMap.end()){constHostDeviceselectedDevice=itemToDeviceMap[LvItem.iItem];if(selectedDevice.ContainsSystem){bEnableOkButton=FALSE;}}#endif}EnableWindow(GetDlgItem((HWND)hwndDlg,IDOK),bEnableOkButton);return1;}if(msg==WM_COMMAND&&lw==IDOK||msg==WM_NOTIFY&&((NMHDR*)lParam)->code==LVN_ITEMACTIVATE){intselectedItem=ListView_GetSelectionMark(GetDlgItem(hwndDlg,IDC_DEVICELIST));if(selectedItem==-1||itemToDeviceMap.find(selectedItem)==itemToDeviceMap.end())return1;// non-device line selected constHostDeviceselectedDevice=itemToDeviceMap[selectedItem];StringCchCopyW(lpszFileName,TC_MAX_PATH,selectedDevice.Path.c_str());#ifdef VOLFORMATif(selectedDevice.ContainsSystem&&selectedDevice.IsPartition){if(WizardMode!=WIZARD_MODE_SYS_DEVICE){if(bInPlaceEncNonSysResumed&&(WizardMode==WIZARD_MODE_NONSYS_DEVICE)){// disable selectionreturn1;}if(AskYesNo("CONFIRM_SYSTEM_ENCRYPTION_MODE",hwndDlg)==IDNO){EndDialog(hwndDlg,IDCANCEL);return1;}bSysPartitionSelected=TRUE;bSysDriveSelected=FALSE;lpszFileName[0]=0;SwitchWizardToSysEncMode();NormalCursor();EndDialog(hwndDlg,IDOK);return1;}else{// This should never be the case because the Select Device dialog is not available in this wizard modebSysPartitionSelected=TRUE;bSysDriveSelected=FALSE;lpszFileName[0]=0;SwitchWizardToSysEncMode();NormalCursor();EndDialog(hwndDlg,IDCANCEL);return1;}}if(!(selectedDevice.ContainsSystem&&!selectedDevice.IsPartition)){if(bWarnDeviceFormatAdvanced&&!bHiddenVolDirect&&AskWarnNoYes("FORMAT_DEVICE_FOR_ADVANCED_ONLY",hwndDlg)==IDNO){if(AskNoYes("CONFIRM_CHANGE_WIZARD_MODE_TO_FILE_CONTAINER",hwndDlg)==IDYES){SwitchWizardToFileContainerMode();}EndDialog(hwndDlg,IDCANCEL);return1;}if(!bHiddenVolDirect)bWarnDeviceFormatAdvanced=FALSE;}#else // #ifdef VOLFORMATbSysPartitionSelected=(selectedDevice.ContainsSystem&&selectedDevice.IsPartition);bSysDriveSelected=FALSE;#endif // #ifdef VOLFORMATif(!selectedDevice.IsPartition&&!selectedDevice.Floppy){// Whole device selected#ifdef VOLFORMATif(selectedDevice.ContainsSystem&&!selectedDevice.IsPartition){if(WizardMode!=WIZARD_MODE_SYS_DEVICE){if(bInPlaceEncNonSysResumed&&(WizardMode==WIZARD_MODE_NONSYS_DEVICE)){// disable selectionreturn1;}if(AskYesNo("CONFIRM_SYSTEM_ENCRYPTION_MODE",hwndDlg)==IDNO){NormalCursor();EndDialog(hwndDlg,IDCANCEL);return1;}bSysDriveSelected=TRUE;bSysPartitionSelected=FALSE;lpszFileName[0]=0;SwitchWizardToSysEncMode();NormalCursor();EndDialog(hwndDlg,IDOK);return1;}else{// This should never be the case because the Select Device dialog is not available in this wizard modebSysDriveSelected=TRUE;bSysPartitionSelected=FALSE;lpszFileName[0]=0;SwitchWizardToSysEncMode();NormalCursor();EndDialog(hwndDlg,IDCANCEL);return1;}}// Disallow format if the device contains partitions, but not if the partition is virtual or system if(!selectedDevice.IsVirtualPartition&&!bHiddenVolDirect){if(!selectedDevice.Partitions.empty()){EnableWindow(GetDlgItem(hwndDlg,IDOK),FALSE);Error("DEVICE_PARTITIONS_ERR_W_INPLACE_ENC_NOTE",hwndDlg);return1;}if(AskWarnNoYes("WHOLE_NONSYS_DEVICE_ENC_CONFIRM",hwndDlg)==IDNO)return1;}#else // #ifdef VOLFORMATbSysDriveSelected=(selectedDevice.ContainsSystem&&!selectedDevice.IsPartition);bSysPartitionSelected=FALSE;#endif // #ifdef VOLFORMAT}elsebSysDriveSelected=FALSE;#ifdef VOLFORMATbRemovableHostDevice=selectedDevice.Removable;#endifNormalCursor();EndDialog(hwndDlg,IDOK);return1;}if((msg==WM_COMMAND)&&(lw==IDCANCEL)){NormalCursor();EndDialog(hwndDlg,IDCANCEL);return1;}return0;}return0;}#endif //!SETUPBOOLDoDriverInstall(HWNDhwndDlg){#ifdef SETUPif(SystemEncryptionUpdate)returnTRUE;#endifSC_HANDLEhManager,hService=NULL;BOOLbOK=FALSE,bRet;hManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);if(hManager==NULL)gotoerror;#ifdef SETUPStatusMessage(hwndDlg,"INSTALLING_DRIVER");#endifhService=CreateService(hManager,L"veracrypt",L"veracrypt",SERVICE_ALL_ACCESS,SERVICE_KERNEL_DRIVER,SERVICE_SYSTEM_START,SERVICE_ERROR_NORMAL,L"System32\\drivers\\veracrypt.sys",NULL,NULL,NULL,NULL,NULL);if(hService==NULL)gotoerror;elseCloseServiceHandle(hService);hService=OpenService(hManager,L"veracrypt",SERVICE_ALL_ACCESS);if(hService==NULL)gotoerror;#ifdef SETUPStatusMessage(hwndDlg,"STARTING_DRIVER");#endifbRet=StartService(hService,0,NULL);if(bRet==FALSE)gotoerror;bOK=TRUE;error:if(bOK==FALSE&&GetLastError()!=ERROR_SERVICE_ALREADY_RUNNING){handleWin32Error(hwndDlg,SRC_POS);MessageBoxW(hwndDlg,GetString("DRIVER_INSTALL_FAILED"),lpszTitle,MB_ICONHAND);}elsebOK=TRUE;if(hService!=NULL)CloseServiceHandle(hService);if(hManager!=NULL)CloseServiceHandle(hManager);returnbOK;}// Install and start driver service and mark it for removal (non-install mode)staticintDriverLoad(){HANDLEfile;WIN32_FIND_DATAfind;SC_HANDLEhManager,hService=NULL;wchar_tdriverPath[TC_MAX_PATH*2];BOOLres;wchar_t*tmp;DWORDstartType;if(ReadLocalMachineRegistryDword(L"SYSTEM\\CurrentControlSet\\Services\\veracrypt",L"Start",&startType)&&startType==SERVICE_BOOT_START)returnERR_PARAMETER_INCORRECT;GetModuleFileName(NULL,driverPath,ARRAYSIZE(driverPath));tmp=wcsrchr(driverPath,L'\\');if(!tmp){driverPath[0]=L'.';driverPath[1]=0;}else*tmp=0;StringCbCatW(driverPath,sizeof(driverPath),!Is64BitOs()?L"\\veracrypt.sys":L"\\veracrypt-x64.sys");file=FindFirstFile(driverPath,&find);if(file==INVALID_HANDLE_VALUE){MessageBoxW(0,GetString("DRIVER_NOT_FOUND"),lpszTitle,ICON_HAND);returnERR_DONT_REPORT;}FindClose(file);hManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);if(hManager==NULL){if(GetLastError()==ERROR_ACCESS_DENIED){MessageBoxW(0,GetString("ADMIN_PRIVILEGES_DRIVER"),lpszTitle,ICON_HAND);returnERR_DONT_REPORT;}returnERR_OS_ERROR;}hService=OpenService(hManager,L"veracrypt",SERVICE_ALL_ACCESS);if(hService!=NULL){// Remove stale service (driver is not loaded but service exists)DeleteService(hService);CloseServiceHandle(hService);Sleep(500);}hService=CreateService(hManager,L"veracrypt",L"veracrypt",SERVICE_ALL_ACCESS,SERVICE_KERNEL_DRIVER,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,driverPath,NULL,NULL,NULL,NULL,NULL);if(hService==NULL){CloseServiceHandle(hManager);returnERR_OS_ERROR;}res=StartService(hService,0,NULL);DeleteService(hService);CloseServiceHandle(hManager);CloseServiceHandle(hService);return!res?ERR_OS_ERROR:ERROR_SUCCESS;}BOOLDriverUnload(){MOUNT_LIST_STRUCTdriver;intrefCount;intvolumesMounted;DWORDdwResult;BOOLbResult;SC_HANDLEhManager,hService=NULL;BOOLbRet;SERVICE_STATUSstatus;intx;BOOLdriverUnloaded=FALSE;if(hDriver==INVALID_HANDLE_VALUE)returnTRUE;try{if(BootEncryption(NULL).GetStatus().DeviceFilterActive)returnFALSE;}catch(...){}// Test for mounted volumesbResult=DeviceIoControl(hDriver,TC_IOCTL_IS_ANY_VOLUME_MOUNTED,NULL,0,&volumesMounted,sizeof(volumesMounted),&dwResult,NULL);if(!bResult){bResult=DeviceIoControl(hDriver,TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES,NULL,0,&driver,sizeof(driver),&dwResult,NULL);if(bResult)volumesMounted=driver.ulMountedDrives;}if(bResult){if(volumesMounted!=0)returnFALSE;}elsereturnTRUE;// Test for any applications attached to driverrefCount=GetDriverRefCount();if(refCount>1)returnFALSE;CloseHandle(hDriver);hDriver=INVALID_HANDLE_VALUE;// Stop driver servicehManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);if(hManager==NULL)gotoerror;hService=OpenService(hManager,L"veracrypt",SERVICE_ALL_ACCESS);if(hService==NULL)gotoerror;bRet=QueryServiceStatus(hService,&status);if(bRet!=TRUE)gotoerror;if(status.dwCurrentState!=SERVICE_STOPPED){ControlService(hService,SERVICE_CONTROL_STOP,&status);for(x=0;x<10;x++){bRet=QueryServiceStatus(hService,&status);if(bRet!=TRUE)gotoerror;if(status.dwCurrentState==SERVICE_STOPPED){driverUnloaded=TRUE;break;}Sleep(200);}}elsedriverUnloaded=TRUE;error:if(hService!=NULL)CloseServiceHandle(hService);if(hManager!=NULL)CloseServiceHandle(hManager);if(driverUnloaded){hDriver=INVALID_HANDLE_VALUE;returnTRUE;}returnFALSE;}intDriverAttach(void){/* Try to open a handle to the device driver. It will be closed later. */#ifndef SETUPintnLoadRetryCount=0;start:#endifhDriver=CreateFile(WIN32_ROOT_PREFIX,0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);if(hDriver==INVALID_HANDLE_VALUE){#ifndef SETUPLoadSysEncSettings();if(!CreateDriverSetupMutex()){// Another instance is already attempting to install, register or start the driverwhile(!CreateDriverSetupMutex()){Sleep(100);// Wait until the other instance finishes}// Try to open a handle to the driver again (keep the mutex in case the other instance failed)gotostart;}else{// No other instance is currently attempting to install, register or start the driverif(SystemEncryptionStatus!=SYSENC_STATUS_NONE){// This is an inconsistent state. The config file indicates system encryption should be// active, but the driver is not running. This may happen e.g. when the pretest fails and // the user selects "Last Known Good Configuration" from the Windows boot menu.// To fix this, we're going to reinstall the driver, start it, and register it for boot.if(DoDriverInstall(NULL)){Sleep(1000);hDriver=CreateFile(WIN32_ROOT_PREFIX,0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);try{BootEncryptionbootEnc(NULL);bootEnc.RegisterBootDriver(bootEnc.GetHiddenOSCreationPhase()!=TC_HIDDEN_OS_CREATION_PHASE_NONE?true:false);}catch(Exception&e){e.Show(NULL);}}CloseDriverSetupMutex();}else{// Attempt to load the driver (non-install/portable mode)load:BOOLres=DriverLoad();CloseDriverSetupMutex();if(res!=ERROR_SUCCESS)returnres;bPortableModeConfirmed=TRUE;if(hDriver!=INVALID_HANDLE_VALUE)CloseHandle(hDriver);hDriver=CreateFile(WIN32_ROOT_PREFIX,0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);}if(bPortableModeConfirmed)NotifyDriverOfPortableMode();}#endif // #ifndef SETUPif(hDriver==INVALID_HANDLE_VALUE)returnERR_OS_ERROR;}CloseDriverSetupMutex();if(hDriver!=INVALID_HANDLE_VALUE){DWORDdwResult;BOOLbResult=DeviceIoControl(hDriver,TC_IOCTL_GET_DRIVER_VERSION,NULL,0,&DriverVersion,sizeof(DriverVersion),&dwResult,NULL);if(!bResult)bResult=DeviceIoControl(hDriver,TC_IOCTL_LEGACY_GET_DRIVER_VERSION,NULL,0,&DriverVersion,sizeof(DriverVersion),&dwResult,NULL);#ifndef SETUP // Don't check version during setup to allow removal of another versionif(bResult==FALSE){returnERR_OS_ERROR;}elseif(DriverVersion!=VERSION_NUM){// Unload an incompatbile version of the driver loaded in non-install mode and load the required versionif(IsNonInstallMode()&&CreateDriverSetupMutex()&&DriverUnload()&&nLoadRetryCount++<3)gotoload;CloseDriverSetupMutex();CloseHandle(hDriver);hDriver=INVALID_HANDLE_VALUE;returnERR_DRIVER_VERSION;}#elseif(!bResult)DriverVersion=0;#endif}return0;}voidResetCurrentDirectory(){wchar_tp[MAX_PATH];if(!IsNonInstallMode()&&SHGetFolderPath(NULL,CSIDL_PROFILE,NULL,0,p)==ERROR_SUCCESS){SetCurrentDirectory(p);}else{GetModPath(p,ARRAYSIZE(p));SetCurrentDirectory(p);}}BOOLBrowseFiles(HWNDhwndDlg,char*stringId,wchar_t*lpszFileName,BOOLkeepHistory,BOOLsaveMode,wchar_t*browseFilter){returnBrowseFilesInDir(hwndDlg,stringId,NULL,lpszFileName,keepHistory,saveMode,browseFilter);}BOOLBrowseFilesInDir(HWNDhwndDlg,char*stringId,wchar_t*initialDir,wchar_t*lpszFileName,BOOLkeepHistory,BOOLsaveMode,wchar_t*browseFilter,constwchar_t*initialFileName,constwchar_t*defaultExtension){OPENFILENAMEWofn;wchar_tfile[TC_MAX_PATH]={0};wchar_tfilter[1024];BOOLstatus=FALSE;CoInitialize(NULL);ZeroMemory(&ofn,sizeof(ofn));*lpszFileName=0;if(initialDir){ofn.lpstrInitialDir=initialDir;}if(initialFileName)StringCchCopyW(file,array_capacity(file),initialFileName);ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=hwndDlg;StringCbPrintfW(filter,sizeof(filter),L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c",GetString("ALL_FILES"),0,0,GetString("TC_VOLUMES"),0,0,0);ofn.lpstrFilter=browseFilter?browseFilter:filter;ofn.nFilterIndex=1;ofn.lpstrFile=file;ofn.nMaxFile=sizeof(file)/sizeof(file[0]);ofn.lpstrTitle=GetString(stringId);ofn.lpstrDefExt=defaultExtension;ofn.Flags=OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|(keepHistory?0:OFN_DONTADDTORECENT)|(saveMode?OFN_OVERWRITEPROMPT:0);if(!keepHistory)CleanLastVisitedMRU();SystemFileSelectorCallerThreadId=GetCurrentThreadId();SystemFileSelectorCallPending=TRUE;if(!saveMode){if(!GetOpenFileNameW(&ofn))gotoret;}else{if(!GetSaveFileNameW(&ofn))gotoret;}SystemFileSelectorCallPending=FALSE;StringCchCopyW(lpszFileName,MAX_PATH,file);if(!keepHistory)CleanLastVisitedMRU();status=TRUE;ret:SystemFileSelectorCallPending=FALSE;ResetCurrentDirectory();CoUninitialize();returnstatus;}staticwchar_tSelectMultipleFilesPath[131072];staticintSelectMultipleFilesOffset;BOOLSelectMultipleFiles(HWNDhwndDlg,constchar*stringId,wchar_t*lpszFileName,size_tcbFileName,BOOLkeepHistory){OPENFILENAMEWofn;wchar_tfilter[1024];BOOLstatus=FALSE;CoInitialize(NULL);ZeroMemory(&ofn,sizeof(ofn));SelectMultipleFilesPath[0]=0;*lpszFileName=0;ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=hwndDlg;StringCbPrintfW(filter,sizeof(filter),L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c",GetString("ALL_FILES"),0,0,GetString("TC_VOLUMES"),0,0,0);ofn.lpstrFilter=filter;ofn.nFilterIndex=1;ofn.lpstrFile=SelectMultipleFilesPath;ofn.nMaxFile=0xffff*2;// The size must not exceed 0xffff*2 due to a bug in Windows 2000 and XP SP1ofn.lpstrTitle=GetString(stringId);ofn.Flags=OFN_HIDEREADONLY|OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_ALLOWMULTISELECT|(keepHistory?0:OFN_DONTADDTORECENT);if(!keepHistory)CleanLastVisitedMRU();SystemFileSelectorCallerThreadId=GetCurrentThreadId();SystemFileSelectorCallPending=TRUE;if(!GetOpenFileNameW(&ofn))gotoret;SystemFileSelectorCallPending=FALSE;if(SelectMultipleFilesPath[ofn.nFileOffset-1]!=0){// Single file selectedStringCbCopyW(lpszFileName,cbFileName,SelectMultipleFilesPath);SelectMultipleFilesOffset=0;SecureZeroMemory(SelectMultipleFilesPath,sizeof(SelectMultipleFilesPath));}else{// Multiple files selectedSelectMultipleFilesOffset=ofn.nFileOffset;SelectMultipleFilesNext(lpszFileName,cbFileName);}if(!keepHistory)CleanLastVisitedMRU();status=TRUE;ret:SystemFileSelectorCallPending=FALSE;ResetCurrentDirectory();CoUninitialize();returnstatus;}BOOLSelectMultipleFilesNext(wchar_t*lpszFileName,size_tcbFileName){if(SelectMultipleFilesOffset==0)returnFALSE;StringCbCopyW(lpszFileName,cbFileName,SelectMultipleFilesPath);lpszFileName[TC_MAX_PATH-1]=0;if(lpszFileName[wcslen(lpszFileName)-1]!=L'\\')StringCbCatW(lpszFileName,cbFileName,L"\\");StringCbCatW(lpszFileName,cbFileName,SelectMultipleFilesPath+SelectMultipleFilesOffset);SelectMultipleFilesOffset+=(int)wcslen(SelectMultipleFilesPath+SelectMultipleFilesOffset)+1;if(SelectMultipleFilesPath[SelectMultipleFilesOffset]==0){SelectMultipleFilesOffset=0;SecureZeroMemory(SelectMultipleFilesPath,sizeof(SelectMultipleFilesPath));}returnTRUE;}staticintCALLBACKBrowseCallbackProc(HWNDhwnd,UINTuMsg,LPARAMlp,LPARAMpData){switch(uMsg){caseBFFM_INITIALIZED:{/* WParam is TRUE since we are passing a path. It would be FALSE if we were passing a pidl. */SendMessageW(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData);break;}caseBFFM_SELCHANGED:{wchar_tszDir[TC_MAX_PATH];/* Set the status window to the currently selected path. */if(SHGetPathFromIDList((LPITEMIDLIST)lp,szDir)){SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,(LPARAM)szDir);}break;}default:break;}return0;}BOOLBrowseDirectories(HWNDhwndDlg,char*lpszTitle,wchar_t*dirName){BROWSEINFOWbi;LPITEMIDLISTpidl;LPMALLOCpMalloc;BOOLbOK=FALSE;CoInitialize(NULL);if(SUCCEEDED(SHGetMalloc(&pMalloc))){ZeroMemory(&bi,sizeof(bi));bi.hwndOwner=hwndDlg;bi.pszDisplayName=0;bi.lpszTitle=GetString(lpszTitle);bi.pidlRoot=0;bi.ulFlags=BIF_RETURNONLYFSDIRS|BIF_STATUSTEXT;bi.lpfn=BrowseCallbackProc;bi.lParam=(LPARAM)dirName;pidl=SHBrowseForFolderW(&bi);if(pidl!=NULL){if(SHGetPathFromIDList(pidl,dirName)){bOK=TRUE;}pMalloc->Free(pidl);pMalloc->Release();}}CoUninitialize();returnbOK;}std::wstringGetWrongPasswordErrorMessage(HWNDhwndDlg){WCHARszTmp[8192];StringCbPrintfW(szTmp,sizeof(szTmp),GetString(KeyFilesEnable?