VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Common/Dlgcode.c590
-rw-r--r--src/Common/Dlgcode.h24
2 files changed, 340 insertions, 274 deletions
diff --git a/src/Common/Dlgcode.c b/src/Common/Dlgcode.c
index de400e7a..071ed8e2 100644
--- a/src/Common/Dlgcode.c
+++ b/src/Common/Dlgcode.c
@@ -44,40 +44,42 @@
#include "SecurityToken.h"
#include "Tests.h"
#include "Volumes.h"
#include "Wipe.h"
#include "Xml.h"
#include "Xts.h"
#include "Boot/Windows/BootCommon.h"
#ifdef TCMOUNT
#include "Mount/Mount.h"
#endif
#ifdef VOLFORMAT
#include "Format/Tcformat.h"
#endif
#ifdef SETUP
#include "Setup/Setup.h"
#endif
+#include <strsafe.h>
+
using namespace VeraCrypt;
LONG DriverVersion;
char *LastDialogId;
char szHelpFile[TC_MAX_PATH];
char szHelpFile2[TC_MAX_PATH];
char SecurityTokenLibraryPath[TC_MAX_PATH];
HFONT hFixedDigitFont = NULL;
HFONT hBoldFont = NULL;
HFONT hTitleFont = NULL;
HFONT hFixedFont = NULL;
HFONT hUserFont = NULL;
HFONT hUserUnderlineFont = NULL;
HFONT hUserBoldFont = NULL;
HFONT hUserUnderlineBoldFont = NULL;
HFONT WindowTitleBarFont;
@@ -303,104 +305,109 @@ void cleanup ()
}
catch (...) { }
EncryptionThreadPoolStop();
#endif
}
void LowerCaseCopy (char *lpszDest, const char *lpszSource)
{
int i = strlen (lpszSource);
lpszDest[i] = 0;
while (--i >= 0)
{
lpszDest[i] = (char) tolower (lpszSource[i]);
}
}
-void UpperCaseCopy (char *lpszDest, const char *lpszSource)
+void UpperCaseCopy (char *lpszDest, size_t cbDest, const char *lpszSource)
{
- int i = strlen (lpszSource);
-
- lpszDest[i] = 0;
- while (--i >= 0)
+ if (lpszDest && cbDest)
{
- lpszDest[i] = (char) toupper (lpszSource[i]);
+ int i = strlen (lpszSource);
+ if (i >= (int) cbDest)
+ i = cbDest - 1;
+
+ lpszDest[i] = 0;
+ while (--i >= 0)
+ {
+ lpszDest[i] = (char) toupper (lpszSource[i]);
+ }
}
}
std::string ToUpperCase (const std::string &str)
{
string u;
foreach (char c, str)
{
u += (char) toupper (c);
}
return u;
}
BOOL IsVolumeDeviceHosted (const char *lpszDiskFile)
{
return strstr (lpszDiskFile, "\\Device\\") == lpszDiskFile
|| strstr (lpszDiskFile, "\\DEVICE\\") == lpszDiskFile;
}
-void CreateFullVolumePath (char *lpszDiskFile, const char *lpszFileName, BOOL * bDevice)
+void CreateFullVolumePath (char *lpszDiskFile, size_t cbDiskFile, const char *lpszFileName, BOOL * bDevice)
{
- UpperCaseCopy (lpszDiskFile, lpszFileName);
+ UpperCaseCopy (lpszDiskFile, cbDiskFile, lpszFileName);
*bDevice = FALSE;
if (memcmp (lpszDiskFile, "\\DEVICE", sizeof (char) * 7) == 0)
{
*bDevice = TRUE;
}
- strcpy (lpszDiskFile, lpszFileName);
+ StringCbCopyA (lpszDiskFile, cbDiskFile, lpszFileName);
#if _DEBUG
OutputDebugString ("CreateFullVolumePath: ");
OutputDebugString (lpszDiskFile);
OutputDebugString ("\n");
#endif
}
-int FakeDosNameForDevice (const char *lpszDiskFile, char *lpszDosDevice, char *lpszCFDevice, BOOL bNameOnly)
+int FakeDosNameForDevice (const char *lpszDiskFile , char *lpszDosDevice , size_t cbDosDevice, char *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly)
{
BOOL bDosLinkCreated = TRUE;
- sprintf (lpszDosDevice, "veracrypt%lu", GetCurrentProcessId ());
+ StringCbPrintfA (lpszDosDevice, cbDosDevice,"veracrypt%lu", GetCurrentProcessId ());
if (bNameOnly == FALSE)
bDosLinkCreated = DefineDosDevice (DDD_RAW_TARGET_PATH, lpszDosDevice, lpszDiskFile);
if (bDosLinkCreated == FALSE)
return ERR_OS_ERROR;
else
- sprintf (lpszCFDevice, "\\\\.\\%s", lpszDosDevice);
+ StringCbPrintfA (lpszCFDevice, cbCFDevice,"\\\\.\\%s", lpszDosDevice);
return 0;
}
int RemoveFakeDosName (char *lpszDiskFile, char *lpszDosDevice)
{
BOOL bDosLinkRemoved = DefineDosDevice (DDD_RAW_TARGET_PATH | DDD_EXACT_MATCH_ON_REMOVE |
DDD_REMOVE_DEFINITION, lpszDosDevice, lpszDiskFile);
if (bDosLinkRemoved == FALSE)
{
return ERR_OS_ERROR;
}
return 0;
}
void AbortProcess (char *stringId)
{
// Note that this function also causes localcleanup() to be called (see atexit())
@@ -792,42 +799,45 @@ void ToBootPwdField (HWND hwndDlg, UINT ctrlId)
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
SetWindowLongPtr (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtr (hwndCtrl, GWLP_WNDPROC));
SetWindowLongPtr (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.
BOOL CALLBACK AuxiliaryDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_INITDIALOG:
{
HDC hDC = GetDC (hwndDlg);
- ScreenDPI = GetDeviceCaps (hDC, LOGPIXELSY);
- ReleaseDC (hwndDlg, hDC);
+ 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.
RECT trec;
trec.right = 0;
trec.bottom = 0;
GetClientRect (GetDlgItem (hwndDlg, IDC_ASPECT_RATIO_CALIBRATION_BOX), &trec);
if (trec.right != 0 && trec.bottom != 0)
@@ -873,43 +883,43 @@ BOOL CALLBACK AboutDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam
SetWindowText (GetDlgItem (hwndDlg, IDC_HOMEPAGE), "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);
}
// Version
SendMessage (GetDlgItem (hwndDlg, IDT_ABOUT_VERSION), WM_SETFONT, (WPARAM) hUserBoldFont, 0);
- sprintf (szTmp, "VeraCrypt %s", VERSION_STRING);
+ StringCbPrintfA (szTmp, sizeof(szTmp), "VeraCrypt %s", VERSION_STRING);
#if (defined(_DEBUG) || defined(DEBUG))
- strcat (szTmp, " (debug)");
+ StringCbCatA (szTmp, sizeof(szTmp), " (debug)");
#endif
SetDlgItemText (hwndDlg, IDT_ABOUT_VERSION, szTmp);
SetDlgItemText (hwndDlg, IDT_ABOUT_RELEASE, TC_STR_RELEASED_BY);
// Credits
SendMessage (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS), WM_SETFONT, (WPARAM) hUserFont, (LPARAM) 0);
SendMessage (hwndDlg, WM_APP, 0, 0);
return 1;
}
case WM_APP:
SetWindowText (GetDlgItem (hwndDlg, IDC_ABOUT_CREDITS),
"Based on TrueCrypt, freely available at http://www.truecrypt.org/ .\r\n\r\n"
"Portions of this software:\r\n"
"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\r\n"
"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\r\n"
"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\r\n"
"Copyright \xA9 2002-2004 Mark Adler. All Rights Reserved.\r\n\r\n"
@@ -1033,215 +1043,218 @@ void CheckButton (HWND hButton)
void LeftPadString (char *szTmp, int len, int targetLen, char filler)
{
int i;
if (targetLen <= len)
return;
for (i = targetLen-1; i >= (targetLen-len); i--)
szTmp [i] = szTmp [i-(targetLen-len)];
memset (szTmp, filler, targetLen-len);
szTmp [targetLen] = 0;
}
/*****************************************************************************
ToSBCS: converts a unicode string to Single Byte Character String (SBCS).
***************************************************************************/
-void ToSBCS (LPWSTR lpszText)
+void ToSBCS (LPWSTR lpszText, size_t cbSize)
{
- int j = wcslen (lpszText);
- if (j == 0)
- {
- strcpy ((char *) lpszText, "");
- return;
- }
- else
+ if (lpszText)
{
- char *lpszNewText = (char *) err_malloc (j + 1);
- j = WideCharToMultiByte (CP_ACP, 0L, lpszText, -1, lpszNewText, j + 1, NULL, NULL);
- if (j > 0)
- strcpy ((char *) lpszText, lpszNewText);
+ int j = wcslen (lpszText);
+ if (j == 0)
+ {
+ *((char *) lpszText) = 0;
+ return;
+ }
else
- strcpy ((char *) lpszText, "");
- free (lpszNewText);
+ {
+ char *lpszNewText = (char *) err_malloc (j + 1);
+ j = WideCharToMultiByte (CP_ACP, 0L, lpszText, -1, lpszNewText, j + 1, NULL, NULL);
+ if (j > 0)
+ StringCbCopyA ((char *) lpszText, cbSize, lpszNewText);
+ else
+ *((char *) lpszText) = 0;
+ free (lpszNewText);
+ }
}
}
/*****************************************************************************
ToUNICODE: converts a SBCS string to a UNICODE string.
***************************************************************************/
-void ToUNICODE (char *lpszText)
+void ToUNICODE (char *lpszText, size_t cbSize)
{
- int j = strlen (lpszText);
+ int j = (int) strlen (lpszText);
if (j == 0)
{
- wcscpy ((LPWSTR) lpszText, (LPWSTR) WIDE (""));
+ StringCbCopyW ((LPWSTR) lpszText, cbSize, (LPWSTR) WIDE (""));
return;
}
else
{
LPWSTR lpszNewText = (LPWSTR) err_malloc ((j + 1) * 2);
j = MultiByteToWideChar (CP_ACP, 0L, lpszText, -1, lpszNewText, j + 1);
if (j > 0)
- wcscpy ((LPWSTR) lpszText, lpszNewText);
+ StringCbCopyW ((LPWSTR) lpszText, cbSize, lpszNewText);
else
- wcscpy ((LPWSTR) lpszText, (LPWSTR) WIDE (""));
+ StringCbCopyW ((LPWSTR) lpszText, cbSize, (LPWSTR) WIDE (""));
free (lpszNewText);
}
}
/* InitDialog - initialize the applications main dialog, this function should
be called only once in the dialogs WM_INITDIALOG message handler */
void InitDialog (HWND hwndDlg)
{
NONCLIENTMETRICSW metric;
static BOOL aboutMenuAppended = FALSE;
int nHeight;
LOGFONTW lf;
HMENU hMenu;
Font *font;
/* Fonts */
memset (&lf, 0, sizeof(lf));
// Normal
font = 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)
{
- wcsncpy ((WCHAR *)metric.lfMessageFont.lfFaceName, font->FaceName, sizeof (metric.lfMessageFont.lfFaceName)/2);
+ StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), font->FaceName);
}
else if (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.
- wcsncpy ((WCHAR *)metric.lfMessageFont.lfFaceName, L"Tahoma", sizeof (metric.lfMessageFont.lfFaceName)/2);
+ 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;
- wcscpy (lf.lfFaceName, L"Courier New");
+ StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), L"Courier New");
hFixedDigitFont = CreateFontIndirectW (&lf);
if (hFixedDigitFont == NULL)
{
handleWin32Error (hwndDlg);
AbortProcess ("NOFONT");
}
// Bold
font = GetFont ("font_bold");
nHeight = CompensateDPIFont (!font ? -13 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_BLACK;
- wcsncpy (lf.lfFaceName, !font ? L"Arial" : font->FaceName, sizeof (lf.lfFaceName)/2);
+ StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), !font ? L"Arial" : font->FaceName);
hBoldFont = CreateFontIndirectW (&lf);
if (hBoldFont == NULL)
{
handleWin32Error (hwndDlg);
AbortProcess ("NOFONT");
}
// Title
font = GetFont ("font_title");
nHeight = CompensateDPIFont (!font ? -21 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_REGULAR;
- wcsncpy (lf.lfFaceName, !font ? L"Times New Roman" : font->FaceName, sizeof (lf.lfFaceName)/2);
+ StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Times New Roman" : font->FaceName);
hTitleFont = CreateFontIndirectW (&lf);
if (hTitleFont == NULL)
{
handleWin32Error (hwndDlg);
AbortProcess ("NOFONT");
}
// Fixed-size
font = 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;
- wcsncpy (lf.lfFaceName, !font ? L"Lucida Console" : font->FaceName, sizeof (lf.lfFaceName)/2);
+ StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Lucida Console" : font->FaceName);
hFixedFont = CreateFontIndirectW (&lf);
if (hFixedFont == NULL)
{
handleWin32Error (hwndDlg);
AbortProcess ("NOFONT");
}
if (!aboutMenuAppended)
{
hMenu = GetSystemMenu (hwndDlg, FALSE);
- AppendMenu (hMenu, MF_SEPARATOR, 0, NULL);
+ AppendMenu (hMenu, MF_SEPARATOR, 0, "");
AppendMenuW (hMenu, MF_ENABLED | MF_STRING, IDC_ABOUT, GetString ("ABOUTBOX"));
aboutMenuAppended = TRUE;
}
}
// The parameter maxMessagesToProcess prevents endless processing of paint messages
void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess)
{
MSG paintMsg;
int msgCounter = maxMessagesToProcess;
while (PeekMessage (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0)
{
DispatchMessage (&paintMsg);
}
}
@@ -1263,120 +1276,127 @@ HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, char *resource)
return dcMem;
}
/* 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 are
retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the
same 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 in
both 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 be
deleted 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. */
HBITMAP RenderBitmap (char *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio)
{
LRESULT lResult = 0;
HDC hdcSrc = CreateMemBitmap (hInst, hwndDest, resource);
+ if (!hdcSrc)
+ return NULL;
HGDIOBJ picture = GetCurrentObject (hdcSrc, OBJ_BITMAP);
- HBITMAP hbmpRescaled;
+ HBITMAP hbmpRescaled = NULL;
BITMAP bitmap;
HDC hdcRescaled;
if (!bDirectRender && nWidth == 0 && nHeight == 0)
{
RECT rec;
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);
-
- hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight);
-
- SelectObject (hdcRescaled, hbmpRescaled);
+ hdcRescaled = CreateCompatibleDC (hdcSrc);
- /* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000.
- TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */
- SetStretchBltMode (hdcRescaled, HALFTONE);
+ if (hdcRescaled)
+ {
+ hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight);
- StretchBlt (hdcRescaled,
- 0,
- 0,
- nWidth,
- nHeight,
- hdcSrc,
- 0,
- 0,
- bitmap.bmWidth,
- bitmap.bmHeight,
- SRCCOPY);
+ SelectObject (hdcRescaled, hbmpRescaled);
- DeleteDC (hdcSrc);
+ /* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000.
+ TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */
+ SetStretchBltMode (hdcRescaled, HALFTONE);
- if (bDirectRender)
- {
- HDC hdcDest = GetDC (hwndDest);
+ StretchBlt (hdcRescaled,
+ 0,
+ 0,
+ nWidth,
+ nHeight,
+ hdcSrc,
+ 0,
+ 0,
+ bitmap.bmWidth,
+ bitmap.bmHeight,
+ SRCCOPY);
- 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);
- }
+ DeleteDC (hdcSrc);
- if ((HGDIOBJ) lResult != NULL && (HGDIOBJ) lResult != (HGDIOBJ) hbmpRescaled)
- DeleteObject ((HGDIOBJ) lResult);
+ if (bDirectRender)
+ {
+ HDC hdcDest = 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);
+ DeleteDC (hdcRescaled);
+ }
return hbmpRescaled;
}
LRESULT CALLBACK
RedTick (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{
}
else if (uMsg == WM_DESTROY)
{
}
else if (uMsg == WM_TIMER)
{
}
else if (uMsg == WM_PAINT)
{
PAINTSTRUCT tmp;
@@ -2322,42 +2342,42 @@ void InitApp (HINSTANCE hInstance, char *lpszCommandLine)
memset (&wcex, 0, sizeof (wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.lpfnWndProc = (WNDPROC) NonInstallUacWndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = "VeraCrypt";
RegisterClassEx (&wcex);
// A small transparent window is necessary to bring the new instance to foreground
hWnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_LAYERED,
"VeraCrypt", "VeraCrypt", 0,
GetSystemMetrics (SM_CXSCREEN)/2,
GetSystemMetrics (SM_CYSCREEN)/2,
1, 1, NULL, NULL, hInstance, NULL);
SetLayeredWindowAttributes (hWnd, 0, 0, LWA_ALPHA);
ShowWindow (hWnd, SW_SHOWNORMAL);
GetModuleFileName (NULL, modPath, sizeof (modPath));
- strcpy (newCmdLine, "/q UAC ");
- strcat_s (newCmdLine, sizeof (newCmdLine), lpszCommandLine);
+ StringCbCopyA (newCmdLine, sizeof(newCmdLine), "/q UAC ");
+ StringCbCatA (newCmdLine, sizeof (newCmdLine), lpszCommandLine);
if ((int)ShellExecute (hWnd, "runas", modPath, newCmdLine, NULL, SW_SHOWNORMAL) <= 32)
exit (1);
Sleep (2000);
exit (0);
}
#endif
SetUnhandledExceptionFilter (ExceptionHandler);
_set_invalid_parameter_handler (InvalidParameterHandler);
RemoteSession = GetSystemMetrics (SM_REMOTESESSION) != 0;
// OS version check
if (CurrentOSMajor < 5)
{
MessageBoxW (NULL, GetString ("UNSUPPORTED_OS"), lpszTitle, MB_ICONSTOP);
exit (1);
}
@@ -2427,105 +2447,110 @@ void InitApp (HINSTANCE hInstance, char *lpszCommandLine)
hDlgClass = RegisterClass (&wc);
if (hDlgClass == 0)
{
handleWin32Error (NULL);
AbortProcess ("INIT_REGISTER");
}
wc.lpszClassName = TC_SPLASH_CLASS;
wc.lpfnWndProc = &SplashDlgProc;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.cbWndExtra = DLGWINDOWEXTRA;
hSplashClass = RegisterClass (&wc);
if (hSplashClass == 0)
{
handleWin32Error (NULL);
AbortProcess ("INIT_REGISTER");
}
if (GetSystemDirectory(dllPath, MAX_PATH))
- strcat(dllPath, "\\Riched20.dll");
+ StringCbCatA(dllPath, sizeof(dllPath), "\\Riched20.dll");
else
- strcpy(dllPath, "c:\\Windows\\System32\\Riched20.dll");
+ StringCbCopyA(dllPath, sizeof(dllPath), "c:\\Windows\\System32\\Riched20.dll");
// Required for RichEdit text fields to work
if (LoadLibrary(dllPath) == NULL)
{
// This error is fatal e.g. because legal notices could not be displayed
handleWin32Error (NULL);
AbortProcess ("INIT_RICHEDIT");
}
// DPI and GUI aspect ratio
DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_AUXILIARY_DLG), NULL,
(DLGPROC) AuxiliaryDlgProc, (LPARAM) 1);
InitHelpFileName ();
#ifndef SETUP
if (!EncryptionThreadPoolStart (ReadEncryptionThreadPoolFreeCpuCountLimit()))
{
handleWin32Error (NULL);
exit (1);
}
#endif
}
void InitHelpFileName (void)
{
char *lpszTmp;
GetModuleFileName (NULL, szHelpFile, sizeof (szHelpFile));
lpszTmp = strrchr (szHelpFile, '\\');
if (lpszTmp)
{
char szTemp[TC_MAX_PATH];
+ ++lpszTmp;
+ *lpszTmp = 0; // add null terminating character to prepare for append operations
+
// Primary file name
if (strcmp (GetPreferredLangId(), "en") == 0
|| GetPreferredLangId() == NULL)
{
- strcpy (++lpszTmp, "VeraCrypt User Guide.pdf");
+ StringCbCatA (szHelpFile, sizeof(szHelpFile), "VeraCrypt User Guide.pdf");
}
else
{
- sprintf (szTemp, "VeraCrypt User Guide.%s.pdf", GetPreferredLangId());
- strcpy (++lpszTmp, szTemp);
+ StringCbPrintfA (szTemp, sizeof(szTemp), "VeraCrypt User Guide.%s.pdf", GetPreferredLangId());
+ StringCbCatA (szHelpFile, sizeof(szHelpFile), szTemp);
}
// Secondary file name (used when localized documentation is not found).
GetModuleFileName (NULL, szHelpFile2, sizeof (szHelpFile2));
lpszTmp = strrchr (szHelpFile2, '\\');
if (lpszTmp)
{
- strcpy (++lpszTmp, "VeraCrypt User Guide.pdf");
+ ++lpszTmp;
+ *lpszTmp = 0;
+ StringCbCopyA (szHelpFile2, sizeof(szHelpFile2), "VeraCrypt User Guide.pdf");
}
}
}
BOOL OpenDevice (const char *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem)
{
DWORD dwResult;
BOOL bResult;
- strcpy ((char *) &driver->wszFileName[0], lpszPath);
- ToUNICODE ((char *) &driver->wszFileName[0]);
+ StringCbCopyA ((char *) &driver->wszFileName[0], sizeof(driver->wszFileName), lpszPath);
+ ToUNICODE ((char *) &driver->wszFileName[0], sizeof(driver->wszFileName));
driver->bDetectTCBootLoader = FALSE;
driver->DetectFilesystem = detectFilesystem;
bResult = DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST,
driver, sizeof (OPEN_TEST_STRUCT),
driver, sizeof (OPEN_TEST_STRUCT),
&dwResult, NULL);
if (bResult == FALSE)
{
dwResult = GetLastError ();
if (dwResult == ERROR_SHARING_VIOLATION || dwResult == ERROR_NOT_READY)
{
driver->TCBootLoaderDetected = FALSE;
driver->FilesystemDetected = FALSE;
return TRUE;
}
else
@@ -2610,52 +2635,55 @@ BOOL GetSysDevicePaths (HWND hwndDlg)
/* 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 the
results 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, bReliableRequired
is 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 path
0 - it's not the system partition/drive path
-1 - the result can't be determined, isn't reliable, or there was an error. */
-int IsSystemDevicePath (char *path, HWND hwndDlg, BOOL bReliableRequired)
+int IsSystemDevicePath (const char *path, HWND hwndDlg, BOOL bReliableRequired)
{
if (!bCachedSysDevicePathsValid
&& bReliableRequired)
{
if (!GetSysDevicePaths (hwndDlg))
return -1;
}
if (strlen (SysPartitionDevicePath) <= 1 || strlen (SysDriveDevicePath) <= 1)
return -1;
+ if (!path)
+ return -1;
+
if (strncmp (path, SysPartitionDevicePath, max (strlen(path), strlen(SysPartitionDevicePath))) == 0)
return 1;
else if (strncmp (path, SysDriveDevicePath, max (strlen(path), strlen(SysDriveDevicePath))) == 0)
return 2;
else if (ExtraBootPartitionDevicePath == path)
return 3;
return 0;
}
wstring GetSysEncryptionPretestInfo2String (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")
@@ -2942,62 +2970,62 @@ BOOL CALLBACK RawDevicesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM l
// Path
if (!device.IsPartition || device.DynamicVolume)
{
if (!device.Floppy && device.Size == 0)
continue;
if (line > 1)
{
ListItemAdd (hList, item.iItem, "");
item.iItem = line++;
}
if (device.Floppy || device.DynamicVolume)
{
ListItemAdd (hList, item.iItem, (char *) device.Path.c_str());
}
else
{
wchar_t s[1024];
if (device.Removable)
- wsprintfW (s, L"%s %d", GetString ("REMOVABLE_DISK"), device.SystemNumber);
+ StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("REMOVABLE_DISK"), device.SystemNumber);
else
- wsprintfW (s, L"%s %d", GetString ("HARDDISK"), device.SystemNumber);
+ StringCbPrintfW (s, sizeof(s), L"%s %d", GetString ("HARDDISK"), device.SystemNumber);
if (!device.Partitions.empty())
- wcscat (s, L":");
+ StringCbCatW (s, sizeof(s), L":");
ListItemAddW (hList, item.iItem, s);
}
}
else
{
ListItemAdd (hList, item.iItem, (char *) device.Path.c_str());
}
itemToDeviceMap[item.iItem] = device;
// Size
if (device.Size != 0)
{
wchar_t size[100] = { 0 };
- GetSizeString (device.Size, size);
+ GetSizeString (device.Size, size, sizeof(size));
ListSubItemSetW (hList, item.iItem, 2, size);
}
// Mount point
if (!device.MountPoint.empty())
ListSubItemSet (hList, item.iItem, 1, (char *) device.MountPoint.c_str());
// Label
if (!device.Name.empty())
ListSubItemSetW (hList, item.iItem, 3, (wchar_t *) device.Name.c_str());
#ifdef TCMOUNT
else
{
wstring favoriteLabel = GetFavoriteVolumeLabel (device.Path);
if (!favoriteLabel.empty())
ListSubItemSetW (hList, item.iItem, 3, (wchar_t *) favoriteLabel.c_str());
}
#endif
item.iItem = line++;
@@ -3241,45 +3269,47 @@ error:
// Install and start driver service and mark it for removal (non-install mode)
static int DriverLoad ()
{
HANDLE file;
WIN32_FIND_DATA find;
SC_HANDLE hManager, hService = NULL;
char driverPath[TC_MAX_PATH*2];
BOOL res;
char *tmp;
DWORD startType;
if (ReadLocalMachineRegistryDword ("SYSTEM\\CurrentControlSet\\Services\\veracrypt", "Start", &startType) && startType == SERVICE_BOOT_START)
return ERR_PARAMETER_INCORRECT;
GetModuleFileName (NULL, driverPath, sizeof (driverPath));
tmp = strrchr (driverPath, '\\');
if (!tmp)
{
- strcpy (driverPath, ".");
- tmp = driverPath + 1;
+ driverPath[0] = '.';
+ driverPath[1] = 0;
}
+ else
+ *tmp = 0;
- strcpy (tmp, !Is64BitOs () ? "\\veracrypt.sys" : "\\veracrypt-x64.sys");
+ StringCbCatA (driverPath, sizeof(driverPath), !Is64BitOs () ? "\\veracrypt.sys" : "\\veracrypt-x64.sys");
file = FindFirstFile (driverPath, &find);
if (file == INVALID_HANDLE_VALUE)
{
MessageBoxW (0, GetString ("DRIVER_NOT_FOUND"), lpszTitle, ICON_HAND);
return ERR_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);
return ERR_DONT_REPORT;
}
@@ -3573,41 +3603,41 @@ BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, char *initialDir, char *lps
wchar_t filter[1024];
BOOL status = FALSE;
CoInitialize (NULL);
ZeroMemory (&ofn, sizeof (ofn));
*lpszFileName = 0;
if (initialDir)
{
swprintf_s (wInitialDir, sizeof (wInitialDir) / 2, L"%hs", initialDir);
ofn.lpstrInitialDir = wInitialDir;
}
if (initialFileName)
wcscpy_s (file, array_capacity (file), initialFileName);
ofn.lStructSize = sizeof (ofn);
ofn.hwndOwner = hwndDlg;
- wsprintfW (filter, L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c",
+ 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)
{
@@ -3624,55 +3654,55 @@ BOOL BrowseFilesInDir (HWND hwndDlg, char *stringId, char *initialDir, char *lps
WideCharToMultiByte (CP_ACP, 0, file, -1, lpszFileName, MAX_PATH, NULL, NULL);
if (!keepHistory)
CleanLastVisitedMRU ();
status = TRUE;
ret:
SystemFileSelectorCallPending = FALSE;
ResetCurrentDirectory();
CoUninitialize();
return status;
}
static char SelectMultipleFilesPath[131072];
static int SelectMultipleFilesOffset;
-BOOL SelectMultipleFiles (HWND hwndDlg, char *stringId, char *lpszFileName, BOOL keepHistory)
+BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, char *lpszFileName, size_t cbFileName,BOOL keepHistory)
{
OPENFILENAMEW ofn;
wchar_t file[0xffff * 2] = { 0 }; // The size must not exceed 0xffff*2 due to a bug in Windows 2000 and XP SP1
wchar_t filter[1024];
BOOL status = FALSE;
CoInitialize (NULL);
ZeroMemory (&ofn, sizeof (ofn));
*lpszFileName = 0;
ofn.lStructSize = sizeof (ofn);
ofn.hwndOwner = hwndDlg;
- wsprintfW (filter, L"%ls (*.*)%c*.*%c%ls (*.hc)%c*.hc%c%c",
+ 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 = file;
ofn.nMaxFile = sizeof (file) / sizeof (file[0]);
ofn.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))
goto ret;
@@ -3681,69 +3711,69 @@ BOOL SelectMultipleFiles (HWND hwndDlg, char *stringId, char *lpszFileName, BOOL
if (file[ofn.nFileOffset - 1] != 0)
{
// Single file selected
WideCharToMultiByte (CP_ACP, 0, file, -1, lpszFileName, MAX_PATH, NULL, NULL);
SelectMultipleFilesOffset = 0;
}
else
{
// Multiple files selected
int n;
wchar_t *f = file;
char *s = SelectMultipleFilesPath;
while ((n = WideCharToMultiByte (CP_ACP, 0, f, -1, s, MAX_PATH, NULL, NULL)) > 1)
{
f += n;
s += n;
}
SelectMultipleFilesOffset = ofn.nFileOffset;
- SelectMultipleFilesNext (lpszFileName);
+ SelectMultipleFilesNext (lpszFileName, cbFileName);
}
if (!keepHistory)
CleanLastVisitedMRU ();
status = TRUE;
ret:
SystemFileSelectorCallPending = FALSE;
ResetCurrentDirectory();
CoUninitialize();
return status;
}
-BOOL SelectMultipleFilesNext (char *lpszFileName)
+BOOL SelectMultipleFilesNext (char *lpszFileName, size_t cbFileName)
{
if (SelectMultipleFilesOffset == 0)
return FALSE;
- strncpy (lpszFileName, SelectMultipleFilesPath, TC_MAX_PATH);
+ StringCbCopyA (lpszFileName, cbFileName,SelectMultipleFilesPath);
lpszFileName[TC_MAX_PATH - 1] = 0;
if (lpszFileName[strlen (lpszFileName) - 1] != '\\')
- strcat (lpszFileName, "\\");
+ StringCbCatA (lpszFileName, cbFileName,"\\");
- strcat (lpszFileName, SelectMultipleFilesPath + SelectMultipleFilesOffset);
+ StringCbCatA (lpszFileName, cbFileName,SelectMultipleFilesPath + SelectMultipleFilesOffset);
SelectMultipleFilesOffset += strlen (SelectMultipleFilesPath + SelectMultipleFilesOffset) + 1;
if (SelectMultipleFilesPath[SelectMultipleFilesOffset] == 0)
SelectMultipleFilesOffset = 0;
return TRUE;
}
static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData)
{
switch(uMsg) {
case BFFM_INITIALIZED:
{
/* WParam is TRUE since we are passing a path.
It would be FALSE if we were passing a pidl. */
SendMessage (hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData);
break;
}
@@ -3793,53 +3823,53 @@ BOOL BrowseDirectories (HWND hwndDlg, char *lpszTitle, char *dirName)
if (SHGetPathFromIDList(pidl, dirName))
{
bOK = TRUE;
}
pMalloc->Free (pidl);
pMalloc->Release();
}
}
CoUninitialize();
return bOK;
}
std::wstring GetWrongPasswordErrorMessage (HWND hwndDlg)
{
WCHAR szTmp[8192];
- swprintf (szTmp, GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_WRONG" : "PASSWORD_WRONG"));
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_WRONG" : "PASSWORD_WRONG"));
if (CheckCapsLock (hwndDlg, TRUE))
- wcscat (szTmp, GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
#ifdef TCMOUNT
if (TCBootLoaderOnInactiveSysEncDrive ())
{
- swprintf (szTmp, GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_OR_MODE_WRONG" : "PASSWORD_OR_MODE_WRONG"));
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString (KeyFilesEnable ? "PASSWORD_OR_KEYFILE_OR_MODE_WRONG" : "PASSWORD_OR_MODE_WRONG"));
if (CheckCapsLock (hwndDlg, TRUE))
- wcscat (szTmp, GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("PASSWORD_WRONG_CAPSLOCK_ON"));
- wcscat (szTmp, GetString ("SYSENC_MOUNT_WITHOUT_PBA_NOTE"));
+ StringCbCatW (szTmp, sizeof(szTmp), GetString ("SYSENC_MOUNT_WITHOUT_PBA_NOTE"));
}
#endif
wstring msg = szTmp;
#ifdef TCMOUNT
if (KeyFilesEnable && HiddenFilesPresentInKeyfilePath)
{
msg += GetString ("HIDDEN_FILES_PRESENT_IN_KEYFILE_PATH");
HiddenFilesPresentInKeyfilePath = FALSE;
}
#endif
return msg;
}
void handleError (HWND hwndDlg, int code)
{
WCHAR szTmp[4096];
@@ -3923,52 +3953,52 @@ void handleError (HWND hwndDlg, int code)
break;
case ERR_NONSYS_INPLACE_ENC_INCOMPLETE:
Error ("ERR_NONSYS_INPLACE_ENC_INCOMPLETE");
break;
case ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG:
Error ("ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG");
break;
case ERR_PARAMETER_INCORRECT:
Error ("ERR_PARAMETER_INCORRECT");
break;
case ERR_USER_ABORT:
case ERR_DONT_REPORT:
// A non-error
break;
default:
- wsprintfW (szTmp, GetString ("ERR_UNKNOWN"), code);
+ StringCbPrintfW (szTmp, sizeof(szTmp), GetString ("ERR_UNKNOWN"), code);
MessageBoxW (hwndDlg, szTmp, lpszTitle, ICON_HAND);
}
}
BOOL CheckFileStreamWriteErrors (FILE *file, const char *fileName)
{
if (ferror (file))
{
wchar_t s[TC_MAX_PATH];
- swprintf_s (s, ARRAYSIZE (s), GetString ("CANNOT_WRITE_FILE_X"), fileName);
+ StringCbPrintfW (s, sizeof (s), GetString ("CANNOT_WRITE_FILE_X"), fileName);
ErrorDirect (s);
return FALSE;
}
return TRUE;
}
static BOOL CALLBACK LocalizeDialogEnum( HWND hwnd, LPARAM font)
{
// Localization of controls
if (LocalizationActive)
{
int ctrlId = GetDlgCtrlID (hwnd);
if (ctrlId != 0)
{
char name[10] = { 0 };
GetClassName (hwnd, name, sizeof (name));
@@ -3991,192 +4021,192 @@ static BOOL CALLBACK LocalizeDialogEnum( HWND hwnd, LPARAM font)
void LocalizeDialog (HWND hwnd, char *stringId)
{
LastDialogId = stringId;
SetWindowLongPtr (hwnd, GWLP_USERDATA, (LONG_PTR) 'VERA');
SendMessage (hwnd, WM_SETFONT, (WPARAM) hUserFont, 0);
if (stringId == NULL)
SetWindowText (hwnd, "VeraCrypt");
else
SetWindowTextW (hwnd, GetString (stringId));
if (hUserFont != 0)
EnumChildWindows (hwnd, LocalizeDialogEnum, (LPARAM) hUserFont);
}
void OpenVolumeExplorerWindow (int driveNo)
{
char dosName[5];
SHFILEINFO fInfo;
- sprintf (dosName, "%c:\\", (char) driveNo + 'A');
+ StringCbPrintfA (dosName, sizeof(dosName), "%c:\\", (char) driveNo + 'A');
// Force explorer to discover the drive
SHGetFileInfo (dosName, 0, &fInfo, sizeof (fInfo), 0);
ShellExecute (NULL, "open", dosName, NULL, NULL, SW_SHOWNORMAL);
}
static BOOL explorerCloseSent;
static HWND explorerTopLevelWindow;
static BOOL CALLBACK CloseVolumeExplorerWindowsChildEnum (HWND hwnd, LPARAM driveStr)
{
char s[MAX_PATH];
SendMessage (hwnd, WM_GETTEXT, sizeof (s), (LPARAM) s);
if (strstr (s, (char *) driveStr) != NULL)
{
PostMessage (explorerTopLevelWindow, WM_CLOSE, 0, 0);
explorerCloseSent = TRUE;
return FALSE;
}
return TRUE;
}
static BOOL CALLBACK CloseVolumeExplorerWindowsEnum (HWND hwnd, LPARAM driveNo)
{
char driveStr[10];
char s[MAX_PATH];
- sprintf (driveStr, "%c:\\", driveNo + 'A');
+ StringCbPrintfA (driveStr, sizeof(driveStr), "%c:\\", driveNo + 'A');
GetClassName (hwnd, s, sizeof s);
if (strcmp (s, "CabinetWClass") == 0)
{
GetWindowText (hwnd, s, sizeof s);
if (strstr (s, driveStr) != NULL)
{
PostMessage (hwnd, WM_CLOSE, 0, 0);
explorerCloseSent = TRUE;
return TRUE;
}
explorerTopLevelWindow = hwnd;
EnumChildWindows (hwnd, CloseVolumeExplorerWindowsChildEnum, (LPARAM) driveStr);
}
return TRUE;
}
BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo)
{
if (driveNo >= 0)
{
explorerCloseSent = FALSE;
EnumWindows (CloseVolumeExplorerWindowsEnum, (LPARAM) driveNo);
}
return explorerCloseSent;
}
string GetUserFriendlyVersionString (int version)
{
char szTmp [64];
- sprintf (szTmp, "%x", version);
+ StringCbPrintfA (szTmp, sizeof(szTmp), "%x", version);
string versionString (szTmp);
versionString.insert (version > 0xfff ? 2 : 1,".");
if (versionString[versionString.length()-1] == '0')
versionString.erase (versionString.length()-1, 1);
return (versionString);
}
-void GetSizeString (unsigned __int64 size, wchar_t *str)
+void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr)
{
static wchar_t *b, *kb, *mb, *gb, *tb, *pb;
static int serNo;
if (b == NULL || serNo != LocalizationSerialNo)
{
serNo = LocalizationSerialNo;
kb = GetString ("KB");
mb = GetString ("MB");
gb = GetString ("GB");
tb = GetString ("TB");
pb = GetString ("PB");
b = GetString ("BYTE");
}
if (size > 1024I64*1024*1024*1024*1024*99)
- swprintf (str, L"%I64d %s", size/1024/1024/1024/1024/1024, pb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024/1024/1024/1024, pb);
else if (size > 1024I64*1024*1024*1024*1024)
- swprintf (str, L"%.1f %s",(double)(size/1024.0/1024/1024/1024/1024), pb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024/1024), pb);
else if (size > 1024I64*1024*1024*1024*99)
- swprintf (str, L"%I64d %s",size/1024/1024/1024/1024, tb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024/1024, tb);
else if (size > 1024I64*1024*1024*1024)
- swprintf (str, L"%.1f %s",(double)(size/1024.0/1024/1024/1024), tb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024/1024), tb);
else if (size > 1024I64*1024*1024*99)
- swprintf (str, L"%I64d %s",size/1024/1024/1024, gb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s",size/1024/1024/1024, gb);
else if (size > 1024I64*1024*1024)
- swprintf (str, L"%.1f %s",(double)(size/1024.0/1024/1024), gb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024/1024), gb);
else if (size > 1024I64*1024*99)
- swprintf (str, L"%I64d %s", size/1024/1024, mb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024/1024, mb);
else if (size > 1024I64*1024)
- swprintf (str, L"%.1f %s",(double)(size/1024.0/1024), mb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(size/1024.0/1024), mb);
else if (size >= 1024I64)
- swprintf (str, L"%I64d %s", size/1024, kb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", size/1024, kb);
else
- swprintf (str, L"%I64d %s", size, b);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", size, b);
}
#ifndef SETUP
-void GetSpeedString (unsigned __int64 speed, wchar_t *str)
+void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr)
{
static wchar_t *b, *kb, *mb, *gb, *tb, *pb;
static int serNo;
if (b == NULL || serNo != LocalizationSerialNo)
{
serNo = LocalizationSerialNo;
kb = GetString ("KB_PER_SEC");
mb = GetString ("MB_PER_SEC");
gb = GetString ("GB_PER_SEC");
tb = GetString ("TB_PER_SEC");
pb = GetString ("PB_PER_SEC");
b = GetString ("B_PER_SEC");
}
if (speed > 1024I64*1024*1024*1024*1024*99)
- swprintf (str, L"%I64d %s", speed/1024/1024/1024/1024/1024, pb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024/1024/1024/1024, pb);
else if (speed > 1024I64*1024*1024*1024*1024)
- swprintf (str, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024/1024), pb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024/1024), pb);
else if (speed > 1024I64*1024*1024*1024*99)
- swprintf (str, L"%I64d %s",speed/1024/1024/1024/1024, tb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024/1024, tb);
else if (speed > 1024I64*1024*1024*1024)
- swprintf (str, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024), tb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024/1024), tb);
else if (speed > 1024I64*1024*1024*99)
- swprintf (str, L"%I64d %s",speed/1024/1024/1024, gb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s",speed/1024/1024/1024, gb);
else if (speed > 1024I64*1024*1024)
- swprintf (str, L"%.1f %s",(double)(speed/1024.0/1024/1024), gb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024/1024), gb);
else if (speed > 1024I64*1024*99)
- swprintf (str, L"%I64d %s", speed/1024/1024, mb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024/1024, mb);
else if (speed > 1024I64*1024)
- swprintf (str, L"%.1f %s",(double)(speed/1024.0/1024), mb);
+ StringCbPrintfW (str, cbStr, L"%.1f %s",(double)(speed/1024.0/1024), mb);
else if (speed > 1024I64)
- swprintf (str, L"%I64d %s", speed/1024, kb);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", speed/1024, kb);
else
- swprintf (str, L"%I64d %s", speed, b);
+ StringCbPrintfW (str, cbStr, L"%I64d %s", speed, b);
}
static void DisplayBenchmarkResults (HWND hwndDlg)
{
wchar_t item1[100]={0};
LVITEMW LvItem;
HWND hList = GetDlgItem (hwndDlg, IDC_RESULTS);
int ea, i;
BOOL unsorted = TRUE;
BENCHMARK_REC tmp_line;
/* Sort the list */
switch (benchmarkSortMethod)
{
case BENCHMARK_SORT_BY_SPEED:
while (unsorted)
{
unsorted = FALSE;
@@ -4213,61 +4243,61 @@ static void DisplayBenchmarkResults (HWND hwndDlg)
}
/* Render the results */
SendMessage (hList,LVM_DELETEALLITEMS,0,(LPARAM)&LvItem);
for (i = 0; i < benchmarkTotalItems; i++)
{
ea = benchmarkTable[i].id;
memset (&LvItem,0,sizeof(LvItem));
LvItem.mask = LVIF_TEXT;
LvItem.iItem = i;
LvItem.iSubItem = 0;
LvItem.pszText = (LPWSTR) benchmarkTable[i].name;
SendMessageW (hList, LVM_INSERTITEM, 0, (LPARAM)&LvItem);
#if PKCS5_BENCHMARKS
wcscpy (item1, L"-");
#else
- GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].encSpeed / benchmarkPerformanceFrequency.QuadPart)), item1);
+ GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].encSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1));
#endif
LvItem.iSubItem = 1;
LvItem.pszText = item1;
SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem);
#if PKCS5_BENCHMARKS
wcscpy (item1, L"-");
#else
- GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].decSpeed / benchmarkPerformanceFrequency.QuadPart)), item1);
+ GetSpeedString ((unsigned __int64) (benchmarkLastBufferSize / ((float) benchmarkTable[i].decSpeed / benchmarkPerformanceFrequency.QuadPart)), item1, sizeof(item1));
#endif
LvItem.iSubItem = 2;
LvItem.pszText = item1;
SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem);
#if PKCS5_BENCHMARKS
swprintf (item1, L"%d t", benchmarkTable[i].encSpeed);
#else
- GetSpeedString (benchmarkTable[i].meanBytesPerSec, item1);
+ GetSpeedString (benchmarkTable[i].meanBytesPerSec, item1, sizeof(item1));
#endif
LvItem.iSubItem = 3;
LvItem.pszText = item1;
SendMessageW (hList, LVM_SETITEMW, 0, (LPARAM)&LvItem);
}
}
static BOOL PerformBenchmark(HWND hwndDlg)
{
LARGE_INTEGER performanceCountStart, performanceCountEnd;
BYTE *lpTestBuffer;
PCRYPTO_INFO ci = NULL;
UINT64_STRUCT startDataUnitNo;
startDataUnitNo.Value = 0;
#if !(PKCS5_BENCHMARKS || HASH_FNC_BENCHMARKS)
ci = crypto_open ();
if (!ci)
@@ -4350,41 +4380,41 @@ static BOOL PerformBenchmark(HWND hwndDlg)
RMD160Init(&rctx);
RMD160Update(&rctx, lpTestBuffer, benchmarkBufferSize);
RMD160Final((unsigned char *) digest, &rctx);
break;
case WHIRLPOOL:
WHIRLPOOL_init (&wctx);
WHIRLPOOL_add (lpTestBuffer, benchmarkBufferSize * 8, &wctx);
WHIRLPOOL_finalize (&wctx, (unsigned char *) digest);
break;
}
if (QueryPerformanceCounter (&performanceCountEnd) == 0)
goto counter_error;
benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
benchmarkTable[benchmarkTotalItems].decSpeed = benchmarkTable[benchmarkTotalItems].encSpeed;
benchmarkTable[benchmarkTotalItems].id = hid;
benchmarkTable[benchmarkTotalItems].meanBytesPerSec = ((unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].encSpeed / benchmarkPerformanceFrequency.QuadPart)) + (unsigned __int64) (benchmarkBufferSize / ((float) benchmarkTable[benchmarkTotalItems].decSpeed / benchmarkPerformanceFrequency.QuadPart))) / 2;
- sprintf (benchmarkTable[benchmarkTotalItems].name, "%s", HashGetName(hid));
+ StringCbPrintfA (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTotalItems].name),"%s", HashGetName(hid));
benchmarkTotalItems++;
}
}
#elif PKCS5_BENCHMARKS // #if HASH_FNC_BENCHMARKS
/* Measures the time that it takes for the PKCS-5 routine to derive a header key using
each of the implemented PRF algorithms.
The PKCS-5 benchmarks are included here for development purposes only. Do not enable
them when building a public release (the benchmark GUI strings wouldn't make sense). */
{
int thid, i;
char dk[MASTER_KEYDATA_SIZE];
char *tmp_salt = {"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF\x01\x23\x45\x67\x89\xAB\xCD\xEF\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xAA\xBB\xCC\xDD\xEE\xFF"};
for (thid = FIRST_PRF_ID; thid <= LAST_PRF_ID; thid++)
{
if (QueryPerformanceCounter (&performanceCountStart) == 0)
@@ -4404,41 +4434,41 @@ static BOOL PerformBenchmark(HWND hwndDlg)
derive_key_sha512 ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, FALSE), dk, MASTER_KEYDATA_SIZE);
break;
case RIPEMD160:
/* PKCS-5 test with HMAC-RIPEMD-160 used as the PRF */
derive_key_ripemd160 (FALSE, "passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, FALSE), dk, MASTER_KEYDATA_SIZE);
break;
case WHIRLPOOL:
/* PKCS-5 test with HMAC-Whirlpool used as the PRF */
derive_key_whirlpool ("passphrase-1234567890", 21, tmp_salt, 64, get_pkcs5_iteration_count(thid, FALSE), dk, MASTER_KEYDATA_SIZE);
break;
}
}
if (QueryPerformanceCounter (&performanceCountEnd) == 0)
goto counter_error;
benchmarkTable[benchmarkTotalItems].encSpeed = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
benchmarkTable[benchmarkTotalItems].id = thid;
- sprintf (benchmarkTable[benchmarkTotalItems].name, "%s", get_pkcs5_prf_name (thid));
+ StringCbPrintfA (benchmarkTable[benchmarkTotalItems].name, sizeof(benchmarkTable[benchmarkTable[benchmarkTotalItems].name),"%s", get_pkcs5_prf_name (thid));
benchmarkTotalItems++;
}
}
#else // #elif PKCS5_BENCHMARKS
/* Encryption algorithm benchmarks */
for (ci->ea = EAGetFirst(); ci->ea != 0; ci->ea = EAGetNext(ci->ea))
{
if (!EAIsFormatEnabled (ci->ea))
continue;
EAInit (ci->ea, ci->master_keydata, ci->ks);
ci->mode = FIRST_MODE_OF_OPERATION_ID;
EAInitMode (ci);
if (QueryPerformanceCounter (&performanceCountStart) == 0)
@@ -4552,111 +4582,111 @@ BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lP
SendMessageW (hList,LVM_INSERTCOLUMNW,3,(LPARAM)&LvCol);
/* Combo boxes */
// Sort method
SendMessage (hCboxSortMethod, CB_RESETCONTENT, 0, 0);
nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("ALPHABETICAL_CATEGORIZED"));
SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0);
nIndex = SendMessageW (hCboxSortMethod, CB_ADDSTRING, 0, (LPARAM) GetString ("MEAN_SPEED"));
SendMessage (hCboxSortMethod, CB_SETITEMDATA, nIndex, (LPARAM) 0);
SendMessage (hCboxSortMethod, CB_SETCURSEL, 1, 0); // Default sort method
// Buffer size
SendMessage (hCboxBufferSize, CB_RESETCONTENT, 0, 0);
- swprintf (s, L"100 %s", GetString ("KB"));
+ StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("KB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_KB);
- swprintf (s, L"500 %s", GetString ("KB"));
+ StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("KB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_KB);
- swprintf (s, L"1 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_MB);
- swprintf (s, L"5 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"5 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 5 * BYTES_PER_MB);
- swprintf (s, L"10 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"10 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 10 * BYTES_PER_MB);
- swprintf (s, L"50 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"50 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 50 * BYTES_PER_MB);
- swprintf (s, L"100 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"100 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 100 * BYTES_PER_MB);
- swprintf (s, L"200 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"200 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 200 * BYTES_PER_MB);
- swprintf (s, L"500 %s", GetString ("MB"));
+ StringCbPrintfW (s, sizeof(s), L"500 %s", GetString ("MB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 500 * BYTES_PER_MB);
- swprintf (s, L"1 %s", GetString ("GB"));
+ StringCbPrintfW (s, sizeof(s), L"1 %s", GetString ("GB"));
nIndex = SendMessageW (hCboxBufferSize, CB_ADDSTRING, 0, (LPARAM) s);
SendMessage (hCboxBufferSize, CB_SETITEMDATA, nIndex, (LPARAM) 1 * BYTES_PER_GB);
SendMessage (hCboxBufferSize, CB_SETCURSEL, 5, 0); // Default buffer size
uint32 driverConfig = ReadDriverConfigurationFlags();
SetDlgItemTextW (hwndDlg, IDC_HW_AES, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? ((driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? "UISTR_DISABLED" : "UISTR_YES") : "NOT_APPLICABLE_OR_NOT_AVAILABLE"))).c_str());
ToHyperlink (hwndDlg, IDC_HW_AES_LABEL_LINK);
if (is_aes_hw_cpu_supported() && (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION))
{
Warning ("DISABLED_HW_AES_AFFECTS_PERFORMANCE");
}
SYSTEM_INFO sysInfo;
GetSystemInfo (&sysInfo);
size_t nbrThreads = GetEncryptionThreadCount();
wchar_t nbrThreadsStr [300];
if (sysInfo.dwNumberOfProcessors < 2)
{
- wcscpy (nbrThreadsStr, GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
+ StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NOT_APPLICABLE_OR_NOT_AVAILABLE"));
}
else if (nbrThreads < 2)
{
- wcscpy (nbrThreadsStr, GetString ("UISTR_DISABLED"));
+ StringCbCopyW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("UISTR_DISABLED"));
}
else
{
- wsprintfW (nbrThreadsStr, GetString ("NUMBER_OF_THREADS"), nbrThreads);
+ StringCbPrintfW (nbrThreadsStr, sizeof(nbrThreadsStr), GetString ("NUMBER_OF_THREADS"), nbrThreads);
}
SetDlgItemTextW (hwndDlg, IDC_PARALLELIZATION, (wstring (L" ") + nbrThreadsStr).c_str());
ToHyperlink (hwndDlg, IDC_PARALLELIZATION_LABEL_LINK);
if (nbrThreads < min (sysInfo.dwNumberOfProcessors, GetMaxEncryptionThreadCount())
&& sysInfo.dwNumberOfProcessors > 1)
{
Warning ("LIMITED_THREAD_COUNT_AFFECTS_PERFORMANCE");
}
return 1;
}
break;
case WM_COMMAND:
case WM_NOTIFY:
switch (lw)
@@ -4755,44 +4785,44 @@ static BOOL CALLBACK RandomPoolEnrichementDlgProc (HWND hwndDlg, UINT msg, WPARA
case WM_TIMER:
{
char tmp[4];
unsigned char tmpByte;
int col, row;
if (bDisplayPoolContents)
{
RandpeekBytes (randPool, sizeof (randPool));
if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0)
{
outputDispBuffer[0] = 0;
for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++)
{
for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++)
{
tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col];
- sprintf (tmp, bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
- strcat (outputDispBuffer, tmp);
+ StringCbPrintfA (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
+ StringCbCatA (outputDispBuffer, sizeof(outputDispBuffer), tmp);
}
- strcat (outputDispBuffer, "\n");
+ StringCbCatA (outputDispBuffer, sizeof(outputDispBuffer), "\n");
}
SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer);
memcpy (lastRandPool, randPool, sizeof(lastRandPool));
}
}
return 1;
}
case WM_COMMAND:
if (lw == IDC_CONTINUE)
lw = IDOK;
if (lw == IDOK || lw == IDCLOSE || lw == IDCANCEL)
{
goto exit;
}
if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE)
{
@@ -4909,44 +4939,44 @@ BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP
case WM_TIMER:
{
char tmp[4];
unsigned char tmpByte;
int col, row;
if (bDisplayPoolContents)
{
RandpeekBytes (randPool, sizeof (randPool));
if (memcmp (lastRandPool, randPool, sizeof(lastRandPool)) != 0)
{
outputDispBuffer[0] = 0;
for (row = 0; row < RANDPOOL_DISPLAY_ROWS; row++)
{
for (col = 0; col < RANDPOOL_DISPLAY_COLUMNS; col++)
{
tmpByte = randPool[row * RANDPOOL_DISPLAY_COLUMNS + col];
- sprintf (tmp, bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
- strcat (outputDispBuffer, tmp);
+ StringCbPrintfA (tmp, sizeof(tmp), bRandPoolDispAscii ? ((tmpByte >= 32 && tmpByte < 255 && tmpByte != '&') ? " %c " : " . ") : "%02X ", tmpByte);
+ StringCbCatA (outputDispBuffer, sizeof(outputDispBuffer), tmp);
}
- strcat (outputDispBuffer, "\n");
+ StringCbCatA (outputDispBuffer, sizeof(outputDispBuffer), "\n");
}
SetWindowText (GetDlgItem (hwndDlg, IDC_POOL_CONTENTS), outputDispBuffer);
memcpy (lastRandPool, randPool, sizeof(lastRandPool));
}
}
return 1;
}
case WM_COMMAND:
if (lw == IDCLOSE || lw == IDCANCEL)
{
goto exit;
}
if (lw == IDC_PRF_ID && hw == CBN_SELCHANGE)
{
hid = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETCURSEL, 0, 0);
hash_algo = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PRF_ID), CB_GETITEMDATA, hid, 0);
@@ -5353,42 +5383,42 @@ CipherTestDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
EncipherBlock(idTestCipher, tmp, ks_tmp);
}
else
{
DecipherBlock(idTestCipher, tmp, ks_tmp);
}
if (idTestCipher == BLOWFISH)
{
/* Deprecated/legacy */
/* Convert back to big-endian */
LongReverse((unsigned int *) tmp, pt);
}
}
*szTmp = 0;
for (n = 0; n < pt; n ++)
{
char szTmp2[3];
- sprintf(szTmp2, "%02x", (int)((unsigned char)tmp[n]));
- strcat(szTmp, szTmp2);
+ StringCbPrintfA(szTmp2, sizeof(szTmp2), "%02x", (int)((unsigned char)tmp[n]));
+ StringCbCatA(szTmp, sizeof(szTmp), szTmp2);
}
if (bEncrypt)
SetWindowText(GetDlgItem(hwndDlg,IDC_CIPHERTEXT), szTmp);
else
SetWindowText(GetDlgItem(hwndDlg,IDC_PLAINTEXT), szTmp);
}
return 1;
}
if (lw == IDCLOSE || lw == IDCANCEL)
{
idTestCipher = -1;
EndDialog (hwndDlg, 0);
return 1;
}
break;
case WM_CLOSE:
@@ -5407,41 +5437,41 @@ ResetCipherTest(HWND hwndDlg, int idTestCipher)
ShowWindow(GetDlgItem(hwndDlg, IDC_TESTS_MESSAGE), SW_HIDE);
ShowWindow(GetDlgItem(hwndDlg, IDC_REDTICK), SW_HIDE);
EnableWindow(GetDlgItem(hwndDlg,IDC_KEY_SIZE), FALSE);
/* Setup the keysize and plaintext sizes for the selected cipher */
SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_RESETCONTENT, 0,0);
SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_RESETCONTENT, 0,0);
SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_RESETCONTENT, 0,0);
ndx = SendMessage (GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_ADDSTRING, 0,(LPARAM) "64");
SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 8);
SendMessage(GetDlgItem(hwndDlg, IDC_PLAINTEXT_SIZE), CB_SETCURSEL, ndx,0);
for (ndx = 0; ndx < BLOCKS_PER_XTS_DATA_UNIT; ndx++)
{
char tmpStr [16];
- sprintf (tmpStr, "%d", ndx);
+ StringCbPrintfA (tmpStr, sizeof(tmpStr), "%d", ndx);
ndx = SendMessage (GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_ADDSTRING, 0,(LPARAM) tmpStr);
SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETITEMDATA, ndx,(LPARAM) ndx);
}
SendMessage(GetDlgItem(hwndDlg, IDC_TEST_BLOCK_NUMBER), CB_SETCURSEL, 0, 0);
SetWindowText(GetDlgItem(hwndDlg, IDC_SECONDARY_KEY), "0000000000000000000000000000000000000000000000000000000000000000");
SetWindowText(GetDlgItem(hwndDlg, IDC_TEST_DATA_UNIT_NUMBER), "0");
if (idTestCipher == BLOWFISH)
{
/* Deprecated/legacy */
ndx = SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_ADDSTRING, 0,(LPARAM) "448");
SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 56);
ndx = SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_ADDSTRING, 0,(LPARAM) "256");
SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 32);
ndx = SendMessage (GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_ADDSTRING, 0,(LPARAM) "128");
SendMessage(GetDlgItem(hwndDlg, IDC_KEY_SIZE), CB_SETITEMDATA, ndx,(LPARAM) 16);
@@ -5854,41 +5884,41 @@ int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced)
unmount.ignoreOpenFiles = forced;
bResult = DeviceIoControl (hDriver, TC_IOCTL_DISMOUNT_VOLUME, &unmount,
sizeof (unmount), &unmount, sizeof (unmount), &dwResult, NULL);
if (bResult == FALSE)
{
handleWin32Error (hwndDlg);
return 1;
}
#ifdef TCMOUNT
if (unmount.nReturnCode == ERR_SUCCESS
&& unmount.HiddenVolumeProtectionTriggered
&& !VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo])
{
wchar_t msg[4096];
VolumeNotificationsList.bHidVolDamagePrevReported [nDosDriveNo] = TRUE;
- swprintf (msg, GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), nDosDriveNo + 'A');
+ StringCbPrintfW (msg, sizeof(msg), GetString ("DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"), nDosDriveNo + 'A');
SetForegroundWindow (hwndDlg);
MessageBoxW (hwndDlg, msg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
#endif // #ifdef TCMOUNT
return unmount.nReturnCode;
}
void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap)
{
DEV_BROADCAST_VOLUME dbv;
DWORD_PTR dwResult;
LONG eventId = 0;
int i;
if (DeviceChangeBroadcastDisabled)
return;
@@ -5897,41 +5927,41 @@ void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap)
else if (message == DBT_DEVICEREMOVECOMPLETE)
eventId = SHCNE_DRIVEREMOVED;
else if (IsOSAtLeast (WIN_7) && message == DBT_DEVICEREMOVEPENDING) // Explorer on Windows 7 holds open handles of all drives when 'Computer' is expanded in navigation pane. SHCNE_DRIVEREMOVED must be used as DBT_DEVICEREMOVEPENDING is ignored.
eventId = SHCNE_DRIVEREMOVED;
if (driveMap == 0)
driveMap = (1 << nDosDriveNo);
if (eventId != 0)
{
for (i = 0; i < 26; i++)
{
if (driveMap & (1 << i))
{
char root[] = { (char) i + 'A', ':', '\\', 0 };
SHChangeNotify (eventId, SHCNF_PATH, root, NULL);
if (nCurrentOS == WIN_2000 && RemoteSession)
{
char target[32];
- wsprintf (target, "%ls%c", TC_MOUNT_PREFIX, i + 'A');
+ StringCbPrintfA (target, sizeof(target), "%ls%c", TC_MOUNT_PREFIX, i + 'A');
root[2] = 0;
if (message == DBT_DEVICEARRIVAL)
DefineDosDevice (DDD_RAW_TARGET_PATH, root, target);
else if (message == DBT_DEVICEREMOVECOMPLETE)
DefineDosDevice (DDD_RAW_TARGET_PATH| DDD_REMOVE_DEFINITION
| DDD_EXACT_MATCH_ON_REMOVE, root, target);
}
}
}
}
dbv.dbcv_size = sizeof (dbv);
dbv.dbcv_devicetype = DBT_DEVTYP_VOLUME;
dbv.dbcv_reserved = 0;
dbv.dbcv_unitmask = driveMap;
dbv.dbcv_flags = 0;
UINT timeOut = 1000;
@@ -6038,63 +6068,63 @@ retry:
// Windows 2000 mount manager causes problems with remounted volumes
if (CurrentOSMajor == 5 && CurrentOSMinor == 0)
mount.bMountManager = FALSE;
string path = volumePath;
if (path.find ("\\\\?\\") == 0)
{
// Remove \\?\ prefix
path = path.substr (4);
strcpy_s (volumePath, TC_MAX_PATH, path.c_str());
}
if (path.find ("Volume{") == 0 && path.rfind ("}\\") == path.size() - 2)
{
string resolvedPath = VolumeGuidPathToDevicePath (path);
if (!resolvedPath.empty())
strcpy_s (volumePath, TC_MAX_PATH, resolvedPath.c_str());
}
- CreateFullVolumePath ((char *) mount.wszVolume, volumePath, &bDevice);
+ CreateFullVolumePath ((char *) mount.wszVolume, sizeof(mount.wszVolume), volumePath, &bDevice);
if (!bDevice)
{
// UNC path
if (path.find ("\\\\") == 0)
{
strcpy_s ((char *)mount.wszVolume, array_capacity (mount.wszVolume), ("UNC" + path.substr (1)).c_str());
}
if (GetVolumePathName (volumePath, root, sizeof (root) - 1))
{
DWORD bps, flags, d;
if (GetDiskFreeSpace (root, &d, &bps, &d, &d))
mount.BytesPerSector = bps;
// Read-only host filesystem
if (!mount.bMountReadOnly && GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0))
mount.bMountReadOnly = (flags & FILE_READ_ONLY_VOLUME) != 0;
}
}
- ToUNICODE ((char *) mount.wszVolume);
+ ToUNICODE ((char *) mount.wszVolume, sizeof(mount.wszVolume));
if (mountOptions->PartitionInInactiveSysEncScope)
{
if (mount.wszVolume == NULL || swscanf_s ((const wchar_t *) mount.wszVolume,
WIDE("\\Device\\Harddisk%d\\Partition"),
&mount.nPartitionInInactiveSysEncScopeDriveNo,
sizeof(mount.nPartitionInInactiveSysEncScopeDriveNo)) != 1)
{
return -1;
}
mount.bPartitionInInactiveSysEncScope = TRUE;
}
bResult = DeviceIoControl (hDriver, TC_IOCTL_MOUNT_VOLUME, &mount,
sizeof (mount), &mount, sizeof (mount), &dwResult, NULL);
burn (&mount.VolumePassword, sizeof (mount.VolumePassword));
burn (&mount.ProtectedHidVolPassword, sizeof (mount.ProtectedHidVolPassword));
@@ -6151,114 +6181,114 @@ retry:
IncreaseWrongPwdRetryCount (1); // We increase the count here only if bReportWrongPassword is TRUE, because "Auto-Mount All Devices" and other callers do it separately
if (WrongPwdRetryCountOverLimit ()
&& !mount.UseBackupHeader)
{
// Retry using embedded header backup (if any)
mount.UseBackupHeader = TRUE;
goto retry;
}
if (bDevice && mount.bProtectHiddenVolume)
{
int driveNo;
if (sscanf (volumePath, "\\Device\\Harddisk%d\\Partition", &driveNo) == 1)
{
OPEN_TEST_STRUCT openTestStruct;
memset (&openTestStruct, 0, sizeof (openTestStruct));
openTestStruct.bDetectTCBootLoader = TRUE;
- _snwprintf ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", driveNo);
+ StringCchPrintfW ((wchar_t *) openTestStruct.wszFileName, array_capacity (openTestStruct.wszFileName), L"\\Device\\Harddisk%d\\Partition0", driveNo);
DWORD dwResult;
if (DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST, &openTestStruct, sizeof (OPEN_TEST_STRUCT), &openTestStruct, sizeof (OPEN_TEST_STRUCT), &dwResult, NULL) && openTestStruct.TCBootLoaderDetected)
WarningDirect ((GetWrongPasswordErrorMessage (hwndDlg) + L"\n\n" + GetString ("HIDDEN_VOL_PROT_PASSWORD_US_KEYB_LAYOUT")).c_str());
else
handleError (hwndDlg, mount.nReturnCode);
}
}
else
handleError (hwndDlg, mount.nReturnCode);
}
return 0;
}
if (!quiet)
handleError (hwndDlg, mount.nReturnCode);
return 0;
}
// Mount successful
if (mount.UseBackupHeader != mountOptions->UseBackupHeader
&& mount.UseBackupHeader)
{
if (bReportWrongPassword && !Silent)
Warning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
}
LastMountedVolumeDirty = mount.FilesystemDirty;
if (mount.FilesystemDirty)
{
wchar_t msg[1024];
wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 };
- wsprintfW (msg, GetString ("MOUNTED_VOLUME_DIRTY"), mountPoint);
+ StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_VOLUME_DIRTY"), mountPoint);
if (AskWarnYesNoStringTopmost (msg) == IDYES)
CheckFilesystem (driveNo, TRUE);
}
if (mount.VolumeMountedReadOnlyAfterAccessDenied
&& !Silent
&& !bDevice
&& !FileHasReadOnlyAttribute (volumePath)
&& !IsFileOnReadOnlyFilesystem (volumePath))
{
wchar_t msg[1024];
wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 };
- wsprintfW (msg, GetString ("MOUNTED_CONTAINER_FORCED_READ_ONLY"), mountPoint);
+ StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_CONTAINER_FORCED_READ_ONLY"), mountPoint);
WarningDirect (msg);
}
if (mount.VolumeMountedReadOnlyAfterAccessDenied
&& !Silent
&& bDevice)
{
wchar_t msg[1024];
wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 };
- wsprintfW (msg, GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY"), mountPoint);
+ StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY"), mountPoint);
WarningDirect (msg);
}
if (mount.VolumeMountedReadOnlyAfterDeviceWriteProtected
&& !Silent
&& strstr (volumePath, "\\Device\\Harddisk") == volumePath)
{
wchar_t msg[1024];
wchar_t mountPoint[] = { L'A' + (wchar_t) driveNo, L':', 0 };
- wsprintfW (msg, GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY_WRITE_PROTECTION"), mountPoint);
+ StringCbPrintfW (msg, sizeof(msg), GetString ("MOUNTED_DEVICE_FORCED_READ_ONLY_WRITE_PROTECTION"), mountPoint);
WarningDirect (msg);
if (CurrentOSMajor >= 6
&& strstr (volumePath, "\\Device\\HarddiskVolume") != volumePath
&& AskNoYes ("ASK_REMOVE_DEVICE_WRITE_PROTECTION") == IDYES)
{
RemoveDeviceWriteProtection (hwndDlg, volumePath);
}
}
ResetWrongPwdRetryCount ();
BroadcastDeviceChange (DBT_DEVICEARRIVAL, driveNo, 0);
if (mount.bExclusiveAccess == FALSE)
return 2;
return 1;
}
@@ -6312,84 +6342,84 @@ retry:
BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, nDosDriveNo, 0);
return TRUE;
}
BOOL IsPasswordCacheEmpty (void)
{
DWORD dw;
return !DeviceIoControl (hDriver, TC_IOCTL_GET_PASSWORD_CACHE_STATUS, 0, 0, 0, 0, &dw, 0);
}
BOOL IsMountedVolume (const char *volname)
{
MOUNT_LIST_STRUCT mlist;
DWORD dwResult;
int i;
char volume[TC_MAX_PATH*2+16];
- strcpy (volume, volname);
+ StringCbCopyA (volume, sizeof(volume), volname);
if (strstr (volname, "\\Device\\") != volname)
- sprintf(volume, "\\??\\%s", volname);
+ StringCbPrintfA(volume, sizeof(volume), "\\??\\%s", volname);
string resolvedPath = VolumeGuidPathToDevicePath (volname);
if (!resolvedPath.empty())
- strcpy_s (volume, sizeof (volume), resolvedPath.c_str());
+ StringCbCopyA (volume, sizeof (volume), resolvedPath.c_str());
- ToUNICODE (volume);
+ ToUNICODE (volume, sizeof(volume));
memset (&mlist, 0, sizeof (mlist));
DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist,
sizeof (mlist), &mlist, sizeof (mlist), &dwResult,
NULL);
for (i=0 ; i<26; i++)
if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], (WCHAR *)volume))
return TRUE;
return FALSE;
}
int GetMountedVolumeDriveNo (char *volname)
{
MOUNT_LIST_STRUCT mlist;
DWORD dwResult;
int i;
char volume[TC_MAX_PATH*2+16];
if (volname == NULL)
return -1;
- strcpy (volume, volname);
+ StringCbCopyA (volume, sizeof(volume), volname);
if (strstr (volname, "\\Device\\") != volname)
- sprintf(volume, "\\??\\%s", volname);
+ StringCbPrintfA (volume, sizeof(volume), "\\??\\%s", volname);
string resolvedPath = VolumeGuidPathToDevicePath (volname);
if (!resolvedPath.empty())
- strcpy_s (volume, sizeof (volume), resolvedPath.c_str());
+ StringCbCopyA (volume, sizeof (volume), resolvedPath.c_str());
- ToUNICODE (volume);
+ ToUNICODE (volume, sizeof(volume));
memset (&mlist, 0, sizeof (mlist));
DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, &mlist,
sizeof (mlist), &mlist, sizeof (mlist), &dwResult,
NULL);
for (i=0 ; i<26; i++)
if (0 == _wcsicmp ((wchar_t *) mlist.wszVolume[i], (WCHAR *)volume))
return i;
return -1;
}
BOOL IsAdmin (void)
{
return IsUserAnAdmin ();
}
@@ -6422,123 +6452,123 @@ BOOL IsBuiltInAdmin ()
BOOL IsUacSupported ()
{
HKEY hkey;
DWORD value = 1, size = sizeof (DWORD);
if (!IsOSAtLeast (WIN_VISTA))
return FALSE;
if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_READ, &hkey) == ERROR_SUCCESS)
{
if (RegQueryValueEx (hkey, "EnableLUA", 0, 0, (LPBYTE) &value, &size) != ERROR_SUCCESS)
value = 1;
RegCloseKey (hkey);
}
return value != 0;
}
-BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName)
+BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName)
{
BOOL bResult;
DWORD dwResult;
RESOLVE_SYMLINK_STRUCT resolve;
memset (&resolve, 0, sizeof(resolve));
- wcscpy ((PWSTR) &resolve.symLinkName, symLinkName);
+ StringCbCopyW (resolve.symLinkName, sizeof(resolve.symLinkName), symLinkName);
bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_RESOLVED_SYMLINK, &resolve,
sizeof (resolve), &resolve, sizeof (resolve), &dwResult,
NULL);
- wcscpy (targetName, (PWSTR) &resolve.targetName);
+ StringCbCopyW (targetName, cbTargetName, resolve.targetName);
return bResult;
}
BOOL GetPartitionInfo (const char *deviceName, PPARTITION_INFORMATION rpartInfo)
{
BOOL bResult;
DWORD dwResult;
DISK_PARTITION_INFO_STRUCT dpi;
memset (&dpi, 0, sizeof(dpi));
- wsprintfW ((PWSTR) &dpi.deviceName, L"%hs", deviceName);
+ StringCbPrintfW ((PWSTR) &dpi.deviceName, sizeof(dpi.deviceName), L"%hs", deviceName);
bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, &dpi,
sizeof (dpi), &dpi, sizeof (dpi), &dwResult, NULL);
memcpy (rpartInfo, &dpi.partInfo, sizeof (PARTITION_INFORMATION));
return bResult;
}
BOOL GetDeviceInfo (const char *deviceName, DISK_PARTITION_INFO_STRUCT *info)
{
DWORD dwResult;
memset (info, 0, sizeof(*info));
- wsprintfW ((PWSTR) &info->deviceName, L"%hs", deviceName);
+ StringCbPrintfW ((PWSTR) &info->deviceName, sizeof(info->deviceName), L"%hs", deviceName);
return DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_PARTITION_INFO, info, sizeof (*info), info, sizeof (*info), &dwResult, NULL);
}
BOOL GetDriveGeometry (const char *deviceName, PDISK_GEOMETRY diskGeometry)
{
BOOL bResult;
DWORD dwResult;
DISK_GEOMETRY_STRUCT dg;
memset (&dg, 0, sizeof(dg));
- wsprintfW ((PWSTR) &dg.deviceName, L"%hs", deviceName);
+ StringCbPrintfW ((PWSTR) &dg.deviceName, sizeof(dg.deviceName), L"%hs", deviceName);
bResult = DeviceIoControl (hDriver, TC_IOCTL_GET_DRIVE_GEOMETRY, &dg,
sizeof (dg), &dg, sizeof (dg), &dwResult, NULL);
memcpy (diskGeometry, &dg.diskGeometry, sizeof (DISK_GEOMETRY));
return bResult;
}
// Returns drive letter number assigned to device (-1 if none)
int GetDiskDeviceDriveLetter (PWSTR deviceName)
{
int i;
WCHAR link[MAX_PATH];
WCHAR target[MAX_PATH];
WCHAR device[MAX_PATH];
- if (!ResolveSymbolicLink (deviceName, device))
- wcscpy (device, deviceName);
+ if (!ResolveSymbolicLink (deviceName, device, sizeof(device)))
+ StringCchCopyW (device, MAX_PATH, deviceName);
for (i = 0; i < 26; i++)
{
WCHAR drive[] = { (WCHAR) i + 'A', ':', 0 };
- wcscpy (link, L"\\DosDevices\\");
- wcscat (link, drive);
+ StringCchCopyW (link, MAX_PATH, L"\\DosDevices\\");
+ StringCchCatW (link, MAX_PATH, drive);
- ResolveSymbolicLink (link, target);
+ ResolveSymbolicLink (link, target, sizeof(target));
if (wcscmp (device, target) == 0)
return i;
}
return -1;
}
// WARNING: This function does NOT provide 100% reliable results -- do NOT use it for critical/dangerous operations!
// Return values: 0 - filesystem does not appear empty, 1 - filesystem appears empty, -1 - an error occurred
int FileSystemAppearsEmpty (const char *devicePath)
{
float percentFreeSpace = 0.0;
__int64 occupiedBytes = 0;
if (GetStatsFreeSpaceOnPartition (devicePath, &percentFreeSpace, &occupiedBytes, TRUE) != -1)
{
if (occupiedBytes > BYTES_PER_GB && percentFreeSpace < 99.99 // "percentFreeSpace < 99.99" is needed because an NTFS filesystem larger than several terabytes can have more than 1GB of data in use, even if there are no files stored on it.
|| percentFreeSpace < 88) // A 24-MB NTFS filesystem has 11.5% of space in use even if there are no files stored on it.
@@ -6549,42 +6579,42 @@ int FileSystemAppearsEmpty (const char *devicePath)
return 1;
}
else
return -1;
}
// Returns the free space on the specified partition (volume) in bytes. If the 'occupiedBytes' pointer
// is not NULL, size of occupied space (in bytes) is written to the pointed location. In addition, if the
// 'percent' pointer is not NULL, % of free space is stored in the pointed location. If there's an error,
// returns -1.
__int64 GetStatsFreeSpaceOnPartition (const char *devicePath, float *percentFree, __int64 *occupiedBytes, BOOL silent)
{
WCHAR devPath [MAX_PATH];
int driveLetterNo = -1;
char szRootPath[4] = {0, ':', '\\', 0};
ULARGE_INTEGER freeSpaceSize;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
- strcpy ((char *) devPath, devicePath);
- ToUNICODE ((char *) devPath);
+ StringCbCopyA ((char *) devPath, sizeof(devPath), devicePath);
+ ToUNICODE ((char *) devPath, sizeof(devPath));
driveLetterNo = GetDiskDeviceDriveLetter (devPath);
szRootPath[0] = (char) driveLetterNo + 'A';
if (!GetDiskFreeSpaceEx (szRootPath, &freeSpaceSize, &totalNumberOfBytes, &totalNumberOfFreeBytes))
{
if (!silent)
{
handleWin32Error (MainDlg);
Error ("CANNOT_CALC_SPACE");
}
return -1;
}
if (percentFree != NULL || occupiedBytes != NULL)
{
// Determine occupied space and % of free space
@@ -6616,42 +6646,42 @@ __int64 GetStatsFreeSpaceOnPartition (const char *devicePath, float *percentFree
__int64 GetDeviceSize (const char *devicePath)
{
PARTITION_INFORMATION partitionInfo;
if (!GetPartitionInfo (devicePath, &partitionInfo))
return -1;
return partitionInfo.PartitionLength.QuadPart;
}
HANDLE DismountDrive (char *devName, char *devicePath)
{
DWORD dwResult;
HANDLE hVolume;
BOOL bResult = FALSE;
int attempt = UNMOUNT_MAX_AUTO_RETRIES;
int driveLetterNo = -1;
WCHAR devPath [MAX_PATH];
- strcpy ((char *) devPath, devicePath);
- ToUNICODE ((char *) devPath);
+ StringCbCopyA ((char *) devPath, sizeof(devPath), devicePath);
+ ToUNICODE ((char *) devPath, sizeof(devPath));
driveLetterNo = GetDiskDeviceDriveLetter (devPath);
hVolume = CreateFile (devName, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hVolume == INVALID_HANDLE_VALUE)
return INVALID_HANDLE_VALUE;
// Try to lock the volume first so that dismount is not forced.
// If we fail, we will dismount anyway even if it needs to be forced.
CloseVolumeExplorerWindows (MainDlg, driveLetterNo);
while (!(bResult = DeviceIoControl (hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
&& attempt > 0)
{
Sleep (UNMOUNT_AUTO_RETRY_DELAY);
attempt--;
@@ -6685,50 +6715,50 @@ int64 FindString (const char *buf, const char *str, int64 bufLen, size_t strLen,
|| strLen > bufLen
|| bufLen < 1
|| strLen < 1
|| startOffset > bufLen - strLen)
{
return -1;
}
for (int64 i = startOffset; i <= bufLen - strLen; i++)
{
if (memcmp (buf + i, str, strLen) == 0)
return i;
}
return -1;
}
// Returns TRUE if the file or directory exists (both may be enclosed in quotation marks).
BOOL FileExists (const char *filePathPtr)
{
- char filePath [TC_MAX_PATH];
+ char filePath [TC_MAX_PATH * 2 + 1];
// Strip quotation marks (if any)
if (filePathPtr [0] == '"')
{
- strcpy (filePath, filePathPtr + 1);
+ StringCbCopyA (filePath, sizeof(filePath), filePathPtr + 1);
}
else
{
- strcpy (filePath, filePathPtr);
+ StringCbCopyA (filePath, sizeof(filePath), filePathPtr);
}
// Strip quotation marks (if any)
if (filePath [strlen (filePath) - 1] == '"')
filePath [strlen (filePath) - 1] = 0;
return (_access (filePath, 0) != -1);
}
// Searches the file from its end for the LAST occurrence of the string str.
// The string may contain zeroes, which do NOT terminate the string.
// If the string is found, its offset from the start of the file is returned.
// If the string isn't found or if any error occurs, -1 is returned.
__int64 FindStringInFile (const char *filePath, const char* str, int strLen)
{
int bufSize = 64 * BYTES_PER_KB;
char *buffer = (char *) err_malloc (bufSize);
HANDLE src = NULL;
DWORD bytesRead;
BOOL readRetVal;
@@ -6911,83 +6941,83 @@ BOOL TCFlushFile (FILE *f)
HANDLE hf = (HANDLE) _get_osfhandle (_fileno (f));
fflush (f);
if (hf == INVALID_HANDLE_VALUE)
return FALSE;
return FlushFileBuffers (hf) != 0;
}
// Prints a UTF-16 text (note that this involves a real printer, not a screen).
// textByteLen - length of the text in bytes
// title - printed as part of the page header and used as the filename for a temporary file
BOOL PrintHardCopyTextUTF16 (wchar_t *text, char *title, int textByteLen)
{
char cl [MAX_PATH*3] = {"/p \""};
char path [MAX_PATH * 2] = { 0 };
char filename [MAX_PATH + 1] = { 0 };
- strcpy (filename, title);
+ StringCbCopyA (filename, sizeof(filename), title);
//strcat (filename, ".txt");
GetTempPath (sizeof (path), path);
if (!FileExists (path))
{
- strcpy (path, GetConfigPath (filename));
+ StringCbCopyA (path, sizeof(path), GetConfigPath (filename));
if (strlen(path) < 2)
return FALSE;
}
else
{
- strcat (path, filename);
+ StringCbCatA (path, sizeof(path), filename);
}
// Write the Unicode signature
if (!SaveBufferToFile ("\xFF\xFE", path, 2, FALSE))
{
remove (path);
return FALSE;
}
// Write the actual text
if (!SaveBufferToFile ((char *) text, path, textByteLen, TRUE))
{
remove (path);
return FALSE;
}
- strcat (cl, path);
- strcat (cl, "\"");
+ StringCbCatA (cl, sizeof(cl), path);
+ StringCbCatA (cl, sizeof(cl), "\"");
// Get the absolute path for notepad
if (GetWindowsDirectory(filename, MAX_PATH))
{
if (filename[strlen (filename) - 1] != '\\')
- strcat (filename, "\\");
- strcat(filename, PRINT_TOOL);
+ StringCbCatA (filename, sizeof(filename), "\\");
+ StringCbCatA(filename, sizeof(filename), PRINT_TOOL);
}
else
- strcpy(filename, "C:\\Windows\\" PRINT_TOOL);
+ StringCbCopyA(filename, sizeof(filename), "C:\\Windows\\" PRINT_TOOL);
WaitCursor ();
ShellExecute (NULL, "open", PRINT_TOOL, cl, NULL, SW_HIDE);
Sleep (6000);
NormalCursor();
remove (path);
return TRUE;
}
BOOL IsNonInstallMode ()
{
HKEY hkey;
DWORD dw;
if (bPortableModeConfirmed)
return TRUE;
@@ -7003,42 +7033,42 @@ BOOL IsNonInstallMode ()
{
// This is also returned if we fail to determine the status (it does not mean that portable mode is disproved).
return FALSE;
}
}
else
{
// The tests in this block are necessary because this function is in some cases called before DriverAttach().
HANDLE hDriverTmp = CreateFile (WIN32_ROOT_PREFIX, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDriverTmp == INVALID_HANDLE_VALUE)
{
// The driver was not found in the system path
char path[MAX_PATH * 2] = { 0 };
// We can't use GetConfigPath() here because it would call us back (indirect recursion)
if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA, NULL, 0, path)))
{
- strcat (path, "\\VeraCrypt\\");
- strcat (path, TC_APPD_FILENAME_SYSTEM_ENCRYPTION);
+ StringCbCatA (path, MAX_PATH * 2, "\\VeraCrypt\\");
+ StringCbCatA (path, MAX_PATH * 2, TC_APPD_FILENAME_SYSTEM_ENCRYPTION);
if (FileExists (path))
{
// To maintain consistency and safety, if the system encryption config file exits, we cannot
// allow portable mode. (This happens e.g. when the pretest fails and the user selects
// "Last Known Good Configuration" from the Windows boot menu.)
// However, if UAC elevation is needed, we have to confirm portable mode first (after we are elevated, we won't).
if (!IsAdmin () && IsUacSupported ())
return TRUE;
return FALSE;
}
}
// As the driver was not found in the system path, we can predict that we will run in portable mode
return TRUE;
}
else
CloseHandle (hDriverTmp);
@@ -7071,123 +7101,134 @@ BOOL GetCheckBox (HWND hwndDlg, int dlgItem)
// Scroll the listview vertically so that the item with index of topMostVisibleItem is the topmost visible item.
void SetListScrollHPos (HWND hList, int topMostVisibleItem)
{
int testedPos = 0;
do
{
SendMessage (hList, LVM_SCROLL, 0, testedPos);
} while (ListView_GetTopIndex (hList) < topMostVisibleItem && ++testedPos < 10000);
}
// Adds or removes TrueCrypt.exe to/from the system startup sequence (with appropriate command line arguments)
void ManageStartupSeq (void)
{
if (!IsNonInstallMode ())
{
char regk [64];
- GetStartupRegKeyName (regk);
+ GetStartupRegKeyName (regk, sizeof(regk));
if (bStartOnLogon || bMountDevicesOnLogon || bMountFavoritesOnLogon)
{
char exe[MAX_PATH * 2] = { '"' };
GetModuleFileName (NULL, exe + 1, sizeof (exe) - 1);
#ifdef VOLFORMAT
{
char *tmp = NULL;
if (tmp = strrchr (exe, '\\'))
- strcpy (++tmp, "VeraCrypt.exe");
+ {
+ *tmp = 0;
+ StringCbCatA (exe, MAX_PATH * 2, "\\VeraCrypt.exe");
+ }
}
#endif
- strcat (exe, "\" /q preferences /a logon");
+ StringCbCatA (exe, MAX_PATH * 2, "\" /q preferences /a logon");
- if (bMountDevicesOnLogon) strcat (exe, " /a devices");
- if (bMountFavoritesOnLogon) strcat (exe, " /a favorites");
+ if (bMountDevicesOnLogon) StringCbCatA (exe, MAX_PATH * 2, " /a devices");
+ if (bMountFavoritesOnLogon) StringCbCatA (exe, MAX_PATH * 2, " /a favorites");
WriteRegistryString (regk, "VeraCrypt", exe);
}
else
DeleteRegistryValue (regk, "VeraCrypt");
}
}
-// Adds or removes the TrueCrypt Volume Creation Wizard to/from the system startup sequence
+// Adds or removes the VeraCrypt Volume Creation Wizard to/from the system startup sequence
void ManageStartupSeqWiz (BOOL bRemove, const char *arg)
{
char regk [64];
- GetStartupRegKeyName (regk);
+ GetStartupRegKeyName (regk, sizeof(regk));
if (!bRemove)
{
- char exe[MAX_PATH * 2] = { '"' };
- GetModuleFileName (NULL, exe + 1, sizeof (exe) - 1);
+ size_t exeSize = (MAX_PATH * 2) + 3 + 20 + strlen (arg); // enough room for all concatenation operations
+ char* exe = (char*) calloc(1, exeSize);
+ exe[0] = '"';
+ GetModuleFileName (NULL, exe + 1, (DWORD) (exeSize - 1));
#ifndef VOLFORMAT
{
char *tmp = NULL;
if (tmp = strrchr (exe, '\\'))
- strcpy (++tmp, "VeraCrypt Format.exe");
+ {
+ *tmp = 0;
+
+ StringCbCatA (exe, exeSize, "\\VeraCrypt Format.exe");
+ }
}
#endif
if (strlen (arg) > 0)
{
- strcat (exe, "\" ");
- strcat (exe, arg);
+ StringCbCatA (exe, exeSize, "\" ");
+ StringCbCatA (exe, exeSize, arg);
}
WriteRegistryString (regk, "VeraCrypt Format", exe);
+
+ free(exe);
}
else
DeleteRegistryValue (regk, "VeraCrypt Format");
}
// Delete the last used Windows file selector path for TrueCrypt from the registry
void CleanLastVisitedMRU (void)
{
WCHAR exeFilename[MAX_PATH];
WCHAR *strToMatch;
WCHAR strTmp[4096];
char regPath[128];
char key[64];
int id, len;
GetModuleFileNameW (NULL, exeFilename, sizeof (exeFilename) / sizeof(exeFilename[0]));
strToMatch = wcsrchr (exeFilename, '\\') + 1;
- sprintf (regPath, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisited%sMRU", IsOSAtLeast (WIN_VISTA) ? "Pidl" : "");
+ StringCbPrintfA (regPath, sizeof(regPath), "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisited%sMRU", IsOSAtLeast (WIN_VISTA) ? "Pidl" : "");
for (id = (IsOSAtLeast (WIN_VISTA) ? 0 : 'a'); id <= (IsOSAtLeast (WIN_VISTA) ? 1000 : 'z'); id++)
{
*strTmp = 0;
- sprintf (key, (IsOSAtLeast (WIN_VISTA) ? "%d" : "%c"), id);
+ StringCbPrintfA (key, sizeof(key), (IsOSAtLeast (WIN_VISTA) ? "%d" : "%c"), id);
if ((len = ReadRegistryBytes (regPath, key, (char *) strTmp, sizeof (strTmp))) > 0)
{
if (_wcsicmp (strTmp, strToMatch) == 0)
{
char buf[65536], bufout[sizeof (buf)];
// Overwrite the entry with zeroes while keeping its original size
memset (strTmp, 0, len);
if (!WriteRegistryBytes (regPath, key, (char *) strTmp, len))
MessageBoxW (NULL, GetString ("CLEAN_WINMRU_FAILED"), lpszTitle, ICON_HAND);
DeleteRegistryValue (regPath, key);
// Remove ID from MRUList
if (IsOSAtLeast (WIN_VISTA))
{
int *p = (int *)buf;
int *pout = (int *)bufout;
int l;
@@ -7496,79 +7537,81 @@ __int64 GetFileSize64 (const char *path)
LARGE_INTEGER size;
__int64 retSize = -1;
if (h)
{
if (GetFileSizeEx (h, &size))
{
retSize = size.QuadPart;
}
CloseHandle (h);
}
return retSize;
}
char *GetModPath (char *path, int maxSize)
{
GetModuleFileName (NULL, path, maxSize);
- strrchr (path, '\\')[1] = 0;
+ char* ptr = strrchr (path, '\\');
+ if (ptr)
+ ptr[1] = 0;
return path;
}
char *GetConfigPath (char *fileName)
{
static char path[MAX_PATH * 2] = { 0 };
if (IsNonInstallMode ())
{
GetModPath (path, sizeof (path));
- strcat (path, fileName);
+ StringCbCatA (path, (MAX_PATH * 2), fileName);
return path;
}
if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path)))
{
- strcat (path, "\\VeraCrypt\\");
+ StringCbCatA (path, (MAX_PATH * 2), "\\VeraCrypt\\");
CreateDirectory (path, NULL);
- strcat (path, fileName);
+ StringCbCatA (path, (MAX_PATH * 2), fileName);
}
else
path[0] = 0;
return path;
}
char *GetProgramConfigPath (char *fileName)
{
static char path[MAX_PATH * 2] = { 0 };
if (SUCCEEDED (SHGetFolderPath (NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path)))
{
- strcat (path, "\\VeraCrypt\\");
+ StringCbCatA (path, (MAX_PATH * 2), "\\VeraCrypt\\");
CreateDirectory (path, NULL);
- strcat (path, fileName);
+ StringCbCatA (path, (MAX_PATH * 2), fileName);
}
else
path[0] = 0;
return path;
}
std::string GetServiceConfigPath (const char *fileName)
{
char sysPath[TC_MAX_PATH];
if (Is64BitOs())
{
typedef UINT (WINAPI *GetSystemWow64Directory_t) (LPTSTR lpBuffer, UINT uSize);
GetSystemWow64Directory_t getSystemWow64Directory = (GetSystemWow64Directory_t) GetProcAddress (GetModuleHandle ("kernel32"), "GetSystemWow64DirectoryA");
getSystemWow64Directory (sysPath, sizeof (sysPath));
}
else
@@ -7596,42 +7639,42 @@ void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *te
{
MessageBoxW (MainDlg, text, headline, warning ? MB_ICONWARNING : MB_ICONINFORMATION);
return;
}
NOTIFYICONDATAW tnid;
ZeroMemory (&tnid, sizeof (tnid));
tnid.cbSize = sizeof (tnid);
tnid.hWnd = hwnd;
tnid.uID = IDI_TRUECRYPT_ICON;
//tnid.uVersion = (IsOSAtLeast (WIN_VISTA) ? NOTIFYICON_VERSION_4 : NOTIFYICON_VERSION);
//Shell_NotifyIconW (NIM_SETVERSION, &tnid);
tnid.uFlags = NIF_INFO;
tnid.dwInfoFlags = (warning ? NIIF_WARNING : NIIF_INFO);
tnid.uTimeout = (IsOSAtLeast (WIN_VISTA) ? 1000 : 5000); // in ms
- wcsncpy (tnid.szInfoTitle, headline, ARRAYSIZE (tnid.szInfoTitle) - 1);
- wcsncpy (tnid.szInfo, text, ARRAYSIZE (tnid.szInfo) - 1);
+ StringCbCopyW (tnid.szInfoTitle, sizeof(tnid.szInfoTitle), headline);
+ StringCbCopyW (tnid.szInfo, sizeof(tnid.szInfo),text);
// Display the balloon tooltip quickly twice in a row to avoid the slow and unwanted "fade-in" phase
Shell_NotifyIconW (NIM_MODIFY, &tnid);
Shell_NotifyIconW (NIM_MODIFY, &tnid);
}
// Either of the pointers may be NULL
void InfoBalloon (char *headingStringId, char *textStringId)
{
if (Silent)
return;
TaskBarIconDisplayBalloonTooltip (MainDlg,
headingStringId == NULL ? L"VeraCrypt" : GetString (headingStringId),
textStringId == NULL ? L" " : GetString (textStringId),
FALSE);
}
@@ -7936,41 +7979,41 @@ BOOL ConfigWriteString (char *configKey, char *configValue)
if (ConfigFileHandle == NULL)
return FALSE;
// Mark previous config value as updated
if (ConfigBuffer != NULL)
{
c = XmlFindElementByAttributeValue (ConfigBuffer, "config", "key", configKey);
if (c != NULL)
c[1] = '!';
}
return 0 != fprintf (
ConfigFileHandle, "\n\t\t<config key=\"%s\">%s</config>",
configKey, configValue);
}
BOOL ConfigWriteInt (char *configKey, int configValue)
{
char val[32];
- sprintf (val, "%d", configValue);
+ StringCbPrintfA (val, sizeof(val), "%d", configValue);
return ConfigWriteString (configKey, val);
}
static BOOL ConfigRead (char *configKey, char *configValue, int maxValueSize)
{
DWORD size;
char *xml;
if (ConfigBuffer == NULL)
ConfigBuffer = LoadFile (GetConfigPath (TC_APPD_FILENAME_CONFIGURATION), &size);
xml = ConfigBuffer;
if (xml != NULL)
{
xml = XmlFindElementByAttributeValue (xml, "config", "key", configKey);
if (xml != NULL)
{
XmlGetNodeText (xml, configValue, maxValueSize);
return TRUE;
@@ -8045,78 +8088,87 @@ void RestoreDefaultKeyFilesParam (void)
KeyFilesEnable = FALSE;
}
BOOL LoadDefaultKeyFilesParam (void)
{
BOOL status = TRUE;
DWORD size;
char *defaultKeyfilesFile = LoadFile (GetConfigPath (TC_APPD_FILENAME_DEFAULT_KEYFILES), &size);
char *xml = defaultKeyfilesFile;
KeyFile *kf;
if (xml == NULL)
return FALSE;
KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile);
while (xml = XmlFindElement (xml, "keyfile"))
{
kf = (KeyFile *) malloc (sizeof (KeyFile));
-
- if (XmlGetNodeText (xml, kf->FileName, sizeof (kf->FileName)) != NULL)
- defaultKeyFilesParam.FirstKeyFile = KeyFileAdd (defaultKeyFilesParam.FirstKeyFile, kf);
+ if (kf)
+ {
+ if (XmlGetNodeText (xml, kf->FileName, sizeof (kf->FileName)) != NULL)
+ defaultKeyFilesParam.FirstKeyFile = KeyFileAdd (defaultKeyFilesParam.FirstKeyFile, kf);
+ else
+ free (kf);
+ }
else
- free (kf);
+ {
+ KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile);
+ status = FALSE;
+ break;
+ }
xml++;
}
free (defaultKeyfilesFile);
- KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles;
+ if (status)
+ KeyFilesEnable = defaultKeyFilesParam.EnableKeyFiles;
return status;
}
#endif /* #ifndef SETUP */
void Debug (char *format, ...)
{
char buf[1024];
va_list val;
va_start(val, format);
- _vsnprintf (buf, sizeof (buf), format, val);
+ StringCbVPrintfA (buf, sizeof (buf), format, val);
va_end(val);
OutputDebugString (buf);
}
void DebugMsgBox (char *format, ...)
{
char buf[1024];
va_list val;
va_start(val, format);
- _vsnprintf (buf, sizeof (buf), format, val);
+ StringCbVPrintfA (buf, sizeof (buf), format, val);
va_end(val);
MessageBox (MainDlg, buf, "VeraCrypt debug", 0);
}
BOOL IsOSAtLeast (OSVersionEnum reqMinOS)
{
return IsOSVersionAtLeast (reqMinOS, 0);
}
// Returns TRUE if the operating system is at least reqMinOS and service pack at least reqMinServicePack.
// Example 1: IsOSVersionAtLeast (WIN_VISTA, 1) called under Windows 2008, returns TRUE.
// Example 2: IsOSVersionAtLeast (WIN_XP, 3) called under Windows XP SP1, returns FALSE.
// Example 3: IsOSVersionAtLeast (WIN_XP, 3) called under Windows Vista SP1, returns TRUE.
BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack)
{
/* When updating this function, update IsOSAtLeast() in Ntdriver.c too. */
@@ -8335,62 +8387,73 @@ std::string GetWindowsEdition ()
osname += "-x64";
if (CurrentOSServicePack > 0)
{
stringstream s;
s << "-sp" << CurrentOSServicePack;
osname += s.str();
}
return osname;
}
void Applink (char *dest, BOOL bSendOS, char *extraOutput)
{
char url [MAX_URL_LENGTH];
ArrowWaitCursor ();
// sprintf_s (url, sizeof (url), TC_APPLINK "%s%s&dest=%s", bSendOS ? ("&os=" + GetWindowsEdition()).c_str() : "", extraOutput, dest);
- sprintf_s (url, sizeof (url),"%s", "https://sourceforge.net/projects/veracrypt/");
+ if (strcmp(dest, "donate") == 0)
+ {
+ StringCbPrintfA (url, sizeof (url),"%s", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=PWT5LHZWANHY6");
+ }
+ else if (strcmp(dest,"localizations") == 0)
+ {
+ StringCbPrintfA (url, sizeof (url),"http://sourceforge.net/projects/veracrypt/files/VeraCrypt%%20%s/VeraCrypt_%s_Language_Files.zip/download", VERSION_STRING, VERSION_STRING);
+ }
+ else
+ {
+ StringCbPrintfA (url, sizeof (url),"%s", "https://sourceforge.net/projects/veracrypt/");
+ }
ShellExecute (NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
Sleep (200);
NormalCursor ();
}
char *RelativePath2Absolute (char *szFileName)
{
if (szFileName[0] != '\\'
&& strchr (szFileName, ':') == 0
&& strstr (szFileName, "Volume{") != szFileName)
{
char path[MAX_PATH*2];
GetCurrentDirectory (MAX_PATH, path);
if (path[strlen (path) - 1] != '\\')
- strcat (path, "\\");
+ StringCbCatA (path, (MAX_PATH * 2), "\\");
- strcat (path, szFileName);
- strncpy (szFileName, path, MAX_PATH-1);
+ StringCbCatA (path, (MAX_PATH * 2), szFileName);
+ StringCbCopyA (szFileName, MAX_PATH + 1, path); // szFileName size is always at least (MAX_PATH + 1)
}
return szFileName;
}
void HandleDriveNotReadyError ()
{
HKEY hkey = 0;
DWORD value = 0, size = sizeof (DWORD);
if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\MountMgr",
0, KEY_READ, &hkey) != ERROR_SUCCESS)
return;
if (RegQueryValueEx (hkey, "NoAutoMount", 0, 0, (LPBYTE) &value, &size) == ERROR_SUCCESS
&& value != 0)
{
Warning ("SYS_AUTOMOUNT_DISABLED");
}
@@ -8446,90 +8509,90 @@ BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam)
BYTE *MapResource (char *resourceType, int resourceId, PDWORD size)
{
HGLOBAL hResL;
HRSRC hRes;
hRes = FindResource (NULL, MAKEINTRESOURCE(resourceId), resourceType);
hResL = LoadResource (NULL, hRes);
if (size != NULL)
*size = SizeofResource (NULL, hRes);
return (BYTE *) LockResource (hResL);
}
void InconsistencyResolved (char *techInfo)
{
wchar_t finalMsg[8024];
- wsprintfW (finalMsg, GetString ("INCONSISTENCY_RESOLVED"), techInfo);
+ StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("INCONSISTENCY_RESOLVED"), techInfo);
MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
}
void ReportUnexpectedState (char *techInfo)
{
wchar_t finalMsg[8024];
- wsprintfW (finalMsg, GetString ("UNEXPECTED_STATE"), techInfo);
+ StringCbPrintfW (finalMsg, sizeof(finalMsg), GetString ("UNEXPECTED_STATE"), techInfo);
MessageBoxW (MainDlg, finalMsg, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST);
}
#ifndef SETUP
int OpenVolume (OpenVolumeContext *context, const char *volumePath, Password *password, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader)
{
int status = ERR_PARAMETER_INCORRECT;
int volumeType;
char szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH];
char szDosDevice[TC_MAX_PATH];
char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE];
LARGE_INTEGER headerOffset;
DWORD dwResult;
DISK_GEOMETRY deviceGeometry;
context->VolumeIsOpen = FALSE;
context->CryptoInfo = NULL;
context->HostFileHandle = INVALID_HANDLE_VALUE;
context->TimestampsValid = FALSE;
- CreateFullVolumePath (szDiskFile, volumePath, &context->IsDevice);
+ CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), volumePath, &context->IsDevice);
if (context->IsDevice)
{
- status = FakeDosNameForDevice (szDiskFile, szDosDevice, szCFDevice, FALSE);
+ status = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE);
if (status != 0)
return status;
preserveTimestamps = FALSE;
if (!GetDriveGeometry (volumePath, &deviceGeometry))
{
status = ERR_OS_ERROR;
goto error;
}
}
else
- strcpy (szCFDevice, szDiskFile);
+ StringCbCopyA (szCFDevice, sizeof(szCFDevice), szDiskFile);
if (preserveTimestamps)
write = TRUE;
context->HostFileHandle = CreateFile (szCFDevice, GENERIC_READ | (write ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (context->HostFileHandle == INVALID_HANDLE_VALUE)
{
status = ERR_OS_ERROR;
goto error;
}
if (context->IsDevice)
{
// Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise,
// the NTFS driver guards hidden sectors and prevents e.g. header backup restore after the user
// accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS, etc.)
DeviceIoControl (context->HostFileHandle, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwResult, NULL);
}
@@ -8871,41 +8934,41 @@ std::string StringToUpperCase (const std::string &str)
_strupr ((char *) upperCase.c_str());
return upperCase;
}
#ifndef SETUP
BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
WORD lw = LOWORD (wParam);
static string *password;
switch (msg)
{
case WM_INITDIALOG:
{
password = (string *) lParam;
LocalizeDialog (hwndDlg, "IDD_TOKEN_PASSWORD");
wchar_t s[1024];
- wsprintfW (s, GetString ("ENTER_TOKEN_PASSWORD"), Utf8StringToWide (password->c_str()).c_str());
+ StringCbPrintfW (s, sizeof(s), GetString ("ENTER_TOKEN_PASSWORD"), Utf8StringToWide (password->c_str()).c_str());
SetWindowTextW (GetDlgItem (hwndDlg, IDT_TOKEN_PASSWORD_INFO), s);
SendMessage (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), EM_LIMITTEXT, SecurityToken::MaxPasswordLength, 0);
SetForegroundWindow (hwndDlg);
SetFocus (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD));
}
return 0;
case WM_COMMAND:
if (lw == IDCANCEL || lw == IDOK)
{
if (lw == IDOK)
{
wchar_t passwordWide[SecurityToken::MaxPasswordLength + 1];
if (GetWindowTextW (GetDlgItem (hwndDlg, IDC_TOKEN_PASSWORD), passwordWide, SecurityToken::MaxPasswordLength + 1) == 0)
{
handleWin32Error (hwndDlg);
break;
@@ -9520,49 +9583,49 @@ BOOL IsFileOnReadOnlyFilesystem (const char *path)
char root[MAX_PATH];
if (!GetVolumePathName (path, root, sizeof (root)))
return FALSE;
DWORD flags, d;
if (!GetVolumeInformation (root, NULL, 0, NULL, &d, &flags, NULL, 0))
return FALSE;
return (flags & FILE_READ_ONLY_VOLUME) ? TRUE : FALSE;
}
void CheckFilesystem (int driveNo, BOOL fixErrors)
{
wchar_t msg[1024], param[1024], cmdPath[MAX_PATH];
char driveRoot[] = { 'A' + (char) driveNo, ':', 0 };
if (fixErrors && AskWarnYesNo ("FILESYS_REPAIR_CONFIRM_BACKUP") == IDNO)
return;
- wsprintfW (msg, GetString (fixErrors ? "REPAIRING_FS" : "CHECKING_FS"), driveRoot);
- wsprintfW (param, fixErrors ? L"/C echo %s & chkdsk %hs /F /X & pause" : L"/C echo %s & chkdsk %hs & pause", msg, driveRoot);
+ StringCbPrintfW (msg, sizeof(msg), GetString (fixErrors ? "REPAIRING_FS" : "CHECKING_FS"), driveRoot);
+ StringCbPrintfW (param, sizeof(param), fixErrors ? L"/C echo %s & chkdsk %hs /F /X & pause" : L"/C echo %s & chkdsk %hs & pause", msg, driveRoot);
if (GetSystemDirectoryW(cmdPath, MAX_PATH))
{
- lstrcatW(cmdPath, L"\\cmd.exe");
+ StringCbCatW(cmdPath, sizeof(cmdPath), L"\\cmd.exe");
}
else
- lstrcpyW(cmdPath, L"C:\\Windows\\System32\\cmd.exe");
+ StringCbCopyW(cmdPath, sizeof(cmdPath), L"C:\\Windows\\System32\\cmd.exe");
ShellExecuteW (NULL, (!IsAdmin() && IsUacSupported()) ? L"runas" : L"open", cmdPath, param, NULL, SW_SHOW);
}
BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str)
{
size_t strLen = strlen (str);
if (bufferSize < strLen)
return FALSE;
bufferSize -= strLen;
for (size_t i = 0; i < bufferSize; ++i)
{
if (memcmp (buffer + i, str, strLen) == 0)
return TRUE;
}
@@ -9595,42 +9658,42 @@ int AskNonSysInPlaceEncryptionResume ()
}
#endif // !SETUP
BOOL RemoveDeviceWriteProtection (HWND hwndDlg, char *devicePath)
{
int driveNumber;
int partitionNumber;
char temp[MAX_PATH*2];
char cmdBatch[MAX_PATH*2];
char diskpartScript[MAX_PATH*2];
if (sscanf (devicePath, "\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
return FALSE;
if (GetTempPath (sizeof (temp), temp) == 0)
return FALSE;
- _snprintf (cmdBatch, sizeof (cmdBatch), "%s\\VeraCrypt_Write_Protection_Removal.cmd", temp);
- _snprintf (diskpartScript, sizeof (diskpartScript), "%s\\VeraCrypt_Write_Protection_Removal.diskpart", temp);
+ StringCbPrintfA (cmdBatch, sizeof (cmdBatch), "%s\\VeraCrypt_Write_Protection_Removal.cmd", temp);
+ StringCbPrintfA (diskpartScript, sizeof (diskpartScript), "%s\\VeraCrypt_Write_Protection_Removal.diskpart", temp);
FILE *f = fopen (cmdBatch, "w");
if (!f)
{
handleWin32Error (hwndDlg);
return FALSE;
}
fprintf (f, "@diskpart /s \"%s\"\n@pause\n@del \"%s\" \"%s\"", diskpartScript, diskpartScript, cmdBatch);
CheckFileStreamWriteErrors (f, cmdBatch);
fclose (f);
f = fopen (diskpartScript, "w");
if (!f)
{
handleWin32Error (hwndDlg);
DeleteFile (cmdBatch);
return FALSE;
}
@@ -9657,116 +9720,119 @@ static LRESULT CALLBACK EnableElevatedCursorChangeWndProc (HWND hWnd, UINT messa
}
void EnableElevatedCursorChange (HWND parent)
{
// Create a transparent window to work around a UAC issue preventing change of the cursor
if (UacElevated)
{
const char *className = "VeraCryptEnableElevatedCursorChange";
WNDCLASSEX winClass;
HWND hWnd;
memset (&winClass, 0, sizeof (winClass));
winClass.cbSize = sizeof (WNDCLASSEX);
winClass.lpfnWndProc = (WNDPROC) EnableElevatedCursorChangeWndProc;
winClass.hInstance = hInst;
winClass.lpszClassName = className;
RegisterClassEx (&winClass);
hWnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_LAYERED, className, "VeraCrypt UAC", 0, 0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), parent, NULL, hInst, NULL);
- SetLayeredWindowAttributes (hWnd, 0, 1, LWA_ALPHA);
- ShowWindow (hWnd, SW_SHOWNORMAL);
+ if (hWnd)
+ {
+ SetLayeredWindowAttributes (hWnd, 0, 1, LWA_ALPHA);
+ ShowWindow (hWnd, SW_SHOWNORMAL);
- DestroyWindow (hWnd);
+ DestroyWindow (hWnd);
+ }
UnregisterClass (className, hInst);
}
}
BOOL DisableFileCompression (HANDLE file)
{
USHORT format;
DWORD bytesOut;
if (!DeviceIoControl (file, FSCTL_GET_COMPRESSION, NULL, 0, &format, sizeof (format), &bytesOut, NULL))
return FALSE;
if (format == COMPRESSION_FORMAT_NONE)
return TRUE;
format = COMPRESSION_FORMAT_NONE;
return DeviceIoControl (file, FSCTL_SET_COMPRESSION, &format, sizeof (format), NULL, 0, &bytesOut, NULL);
}
-BOOL VolumePathExists (char *volumePath)
+BOOL VolumePathExists (const char *volumePath)
{
OPEN_TEST_STRUCT openTest;
- char upperCasePath[TC_MAX_PATH];
+ char upperCasePath[TC_MAX_PATH + 1];
- UpperCaseCopy (upperCasePath, volumePath);
+ UpperCaseCopy (upperCasePath, sizeof(upperCasePath), volumePath);
if (strstr (upperCasePath, "\\DEVICE\\") == upperCasePath)
return OpenDevice (volumePath, &openTest, FALSE);
string path = volumePath;
if (path.find ("\\\\?\\Volume{") == 0 && path.rfind ("}\\") == path.size() - 2)
{
char devicePath[TC_MAX_PATH];
if (QueryDosDevice (path.substr (4, path.size() - 5).c_str(), devicePath, TC_MAX_PATH) != 0)
return TRUE;
}
return _access (volumePath, 0) == 0;
}
BOOL IsWindowsIsoBurnerAvailable ()
{
char path[MAX_PATH*2] = { 0 };
if (!IsOSAtLeast (WIN_7))
{
return FALSE;
}
if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path)))
{
- strcat (path, "\\" ISO_BURNER_TOOL);
+ StringCbCatA (path, MAX_PATH*2, "\\" ISO_BURNER_TOOL);
return (FileExists (path));
}
return FALSE;
}
BOOL LaunchWindowsIsoBurner (HWND hwnd, const char *isoPath)
{
char path[MAX_PATH*2] = { 0 };
int r;
if (SUCCEEDED(SHGetFolderPath (NULL, CSIDL_SYSTEM, NULL, 0, path)))
- strcat (path, "\\" ISO_BURNER_TOOL);
+ StringCbCatA (path, MAX_PATH*2, "\\" ISO_BURNER_TOOL);
else
- strcpy (path, "C:\\Windows\\System32\\" ISO_BURNER_TOOL);
+ StringCbCopyA (path, MAX_PATH*2, "C:\\Windows\\System32\\" ISO_BURNER_TOOL);
r = (int) ShellExecute (hwnd, "open", path, (string ("\"") + isoPath + "\"").c_str(), NULL, SW_SHOWNORMAL);
if (r <= 32)
{
SetLastError (r);
handleWin32Error (hwnd);
return FALSE;
}
return TRUE;
}
std::string VolumeGuidPathToDevicePath (std::string volumeGuidPath)
{
if (volumeGuidPath.find ("\\\\?\\") == 0)
volumeGuidPath = volumeGuidPath.substr (4);
@@ -9778,41 +9844,41 @@ std::string VolumeGuidPathToDevicePath (std::string volumeGuidPath)
return string();
string partitionPath = HarddiskVolumePathToPartitionPath (volDevPath);
return partitionPath.empty() ? volDevPath : partitionPath;
}
std::string HarddiskVolumePathToPartitionPath (const std::string &harddiskVolumePath)
{
wstring volPath = SingleStringToWide (harddiskVolumePath);
for (int driveNumber = 0; driveNumber < MAX_HOST_DRIVE_NUMBER; driveNumber++)
{
for (int partNumber = 0; partNumber < MAX_HOST_PARTITION_NUMBER; partNumber++)
{
wchar_t partitionPath[TC_MAX_PATH];
swprintf_s (partitionPath, ARRAYSIZE (partitionPath), L"\\Device\\Harddisk%d\\Partition%d", driveNumber, partNumber);
wchar_t resolvedPath[TC_MAX_PATH];
- if (ResolveSymbolicLink (partitionPath, resolvedPath))
+ if (ResolveSymbolicLink (partitionPath, resolvedPath, sizeof(resolvedPath)))
{
if (volPath == resolvedPath)
return WideToSingleString (partitionPath);
}
else if (partNumber == 0)
break;
}
}
return string();
}
BOOL IsApplicationInstalled (const char *appName)
{
const char *uninstallRegName = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
BOOL installed = FALSE;
HKEY unistallKey;
LONG res = RegOpenKeyEx (HKEY_LOCAL_MACHINE, uninstallRegName, 0, KEY_READ | KEY_WOW64_64KEY, &unistallKey);
if (res != ERROR_SUCCESS)
diff --git a/src/Common/Dlgcode.h b/src/Common/Dlgcode.h
index 588fea41..11686f89 100644
--- a/src/Common/Dlgcode.h
+++ b/src/Common/Dlgcode.h
@@ -205,62 +205,62 @@ typedef struct
uint64 HostSize;
BOOL TimestampsValid;
FILETIME CreationTime;
FILETIME LastWriteTime;
FILETIME LastAccessTime;
} OpenVolumeContext;
#define DEFAULT_VOL_CREATION_WIZARD_MODE WIZARD_MODE_FILE_CONTAINER
#define ICON_HAND MB_ICONHAND
#define YES_NO MB_YESNO
#define ISO_BURNER_TOOL "isoburn.exe"
#define PRINT_TOOL "notepad.exe"
void cleanup ( void );
void LowerCaseCopy ( char *lpszDest , const char *lpszSource );
-void UpperCaseCopy ( char *lpszDest , const char *lpszSource );
-void CreateFullVolumePath ( char *lpszDiskFile , const char *lpszFileName , BOOL *bDevice );
-int FakeDosNameForDevice ( const char *lpszDiskFile , char *lpszDosDevice , char *lpszCFDevice , BOOL bNameOnly );
+void UpperCaseCopy ( char *lpszDest , size_t cbDest, const char *lpszSource );
+void CreateFullVolumePath ( char *lpszDiskFile , size_t cbDiskFile, const char *lpszFileName , BOOL *bDevice );
+int FakeDosNameForDevice ( const char *lpszDiskFile , char *lpszDosDevice , size_t cbDosDevice, char *lpszCFDevice , size_t cbCFDevice, BOOL bNameOnly );
int RemoveFakeDosName ( char *lpszDiskFile , char *lpszDosDevice );
void AbortProcess ( char *stringId );
void AbortProcessSilent ( void );
void *err_malloc ( size_t size );
char *err_strdup ( char *lpszText );
DWORD handleWin32Error ( HWND hwndDlg );
BOOL IsDiskReadError (DWORD error);
BOOL IsDiskWriteError (DWORD error);
BOOL IsDiskError (DWORD error);
BOOL translateWin32Error ( wchar_t *lpszMsgBuf , int nWSizeOfBuf );
BOOL CALLBACK AboutDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam );
static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
void DisplayStaticModelessWaitDlg (HWND parent);
void CloseStaticModelessWaitDlg (void);
BOOL IsButtonChecked ( HWND hButton );
void CheckButton ( HWND hButton );
void LeftPadString (char *szTmp, int len, int targetLen, char filler);
-void ToSBCS ( LPWSTR lpszText );
-void ToUNICODE ( char *lpszText );
+void ToSBCS ( LPWSTR lpszText, size_t cbSize );
+void ToUNICODE ( char *lpszText , size_t cbSize);
void InitDialog ( HWND hwndDlg );
void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess);
HDC CreateMemBitmap ( HINSTANCE hInstance , HWND hwnd , char *resource );
HBITMAP RenderBitmap ( char *resource , HWND hwndDest , int x , int y , int nWidth , int nHeight , BOOL bDirectRender , BOOL bKeepAspectRatio);
LRESULT CALLBACK RedTick ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam );
BOOL RegisterRedTick ( HINSTANCE hInstance );
BOOL UnregisterRedTick ( HINSTANCE hInstance );
LRESULT CALLBACK SplashDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam );
void WaitCursor ( void );
void NormalCursor ( void );
void ArrowWaitCursor ( void );
void HandCursor ();
void AddComboPair (HWND hComboBox, const char *lpszItem, int value);
void AddComboPairW (HWND hComboBox, const wchar_t *lpszItem, int value);
void SelectAlgo ( HWND hComboBox , int *nCipher );
void PopulateWipeModeCombo (HWND hComboBox, BOOL bNA, BOOL bInPlaceEncryption);
wchar_t *GetWipeModeName (WipeAlgorithmId modeId);
wchar_t *GetPathType (const char *path, BOOL bUpperCase, BOOL *bIsPartition);
LRESULT CALLBACK CustomDlgProc ( HWND hwnd , UINT uMsg , WPARAM wParam , LPARAM lParam );
BOOL TCCreateMutex (volatile HANDLE *hMutex, char *name);
@@ -276,110 +276,110 @@ BOOL NonSysInplaceEncInProgressElsewhere (void);
BOOL CreateDriverSetupMutex (void);
void CloseDriverSetupMutex (void);
BOOL CreateAppSetupMutex (void);
BOOL InstanceHasAppSetupMutex (void);
void CloseAppSetupMutex (void);
BOOL IsTrueCryptInstallerRunning (void);
uint32 ReadDriverConfigurationFlags ();
uint32 ReadEncryptionThreadPoolFreeCpuCountLimit ();
BOOL LoadSysEncSettings (HWND hwndDlg);
int LoadNonSysInPlaceEncSettings (WipeAlgorithmId *wipeAlgorithm);
void RemoveNonSysInPlaceEncNotifications (void);
void SavePostInstallTasksSettings (int command);
void DoPostInstallTasks (void);
void InitOSVersionInfo ();
void InitApp ( HINSTANCE hInstance, char *lpszCommandLine );
void InitHelpFileName (void);
BOOL OpenDevice (const char *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem);
void NotifyDriverOfPortableMode (void);
int GetAvailableFixedDisks ( HWND hComboBox , char *lpszRootPath );
int GetAvailableRemovables ( HWND hComboBox , char *lpszRootPath );
-int IsSystemDevicePath (char *path, HWND hwndDlg, BOOL bReliableRequired);
+int IsSystemDevicePath (const char *path, HWND hwndDlg, BOOL bReliableRequired);
BOOL CALLBACK RawDevicesDlgProc ( HWND hwndDlg , UINT msg , WPARAM wParam , LPARAM lParam );
BOOL TextInfoDialogBox (int nID);
BOOL CALLBACK TextInfoDialogBoxDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
char * GetLegalNotices ();
BOOL CALLBACK BenchmarkDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
void UserEnrichRandomPool (HWND hwndDlg);
BOOL CALLBACK KeyfileGeneratorDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
BOOL CALLBACK MultiChoiceDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
int DriverAttach ( void );
BOOL CALLBACK CipherTestDialogProc ( HWND hwndDlg , UINT uMsg , WPARAM wParam , LPARAM lParam );
void ResetCipherTest ( HWND hwndDlg , int idTestCipher );
void ResetCurrentDirectory ();
BOOL BrowseFiles (HWND hwndDlg, char *stringId, char *lpszFileName, BOOL keepHistory, BOOL saveMode, wchar_t *browseFilter);
BOOL BrowseDirectories (HWND hWnd, char *lpszTitle, char *dirName);
void handleError ( HWND hwndDlg , int code );
BOOL CheckFileStreamWriteErrors (FILE *file, const char *fileName);
void LocalizeDialog ( HWND hwnd, char *stringId );
void OpenVolumeExplorerWindow (int driveNo);
static BOOL CALLBACK CloseVolumeExplorerWindowsEnum( HWND hwnd, LPARAM driveNo);
BOOL CloseVolumeExplorerWindows (HWND hwnd, int driveNo);
BOOL CheckCapsLock (HWND hwnd, BOOL quiet);
BOOL CheckFileExtension (char *fileName);
void IncreaseWrongPwdRetryCount (int count);
void ResetWrongPwdRetryCount (void);
BOOL WrongPwdRetryCountOverLimit (void);
int GetFirstAvailableDrive ();
int GetLastAvailableDrive ();
BOOL IsDriveAvailable (int driveNo);
BOOL IsDeviceMounted (char *deviceName);
int DriverUnmountVolume (HWND hwndDlg, int nDosDriveNo, BOOL forced);
void BroadcastDeviceChange (WPARAM message, int nDosDriveNo, DWORD driveMap);
int MountVolume (HWND hwndDlg, int driveNo, char *volumePath, Password *password, BOOL cachePassword, BOOL sharedAccess, const MountOptions* const mountOptions, BOOL quiet, BOOL bReportWrongPassword);
BOOL UnmountVolume (HWND hwndDlg , int nDosDriveNo, BOOL forceUnmount);
BOOL IsPasswordCacheEmpty (void);
BOOL IsMountedVolume (const char *volname);
int GetMountedVolumeDriveNo (char *volname);
BOOL IsAdmin (void);
BOOL IsBuiltInAdmin ();
BOOL IsUacSupported ();
-BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName);
+BOOL ResolveSymbolicLink (const wchar_t *symLinkName, PWSTR targetName, size_t cbTargetName);
int GetDiskDeviceDriveLetter (PWSTR deviceName);
int FileSystemAppearsEmpty (const char *devicePath);
__int64 GetStatsFreeSpaceOnPartition (const char *devicePath, float *percent, __int64 *occupiedBytes, BOOL silent);
__int64 GetDeviceSize (const char *devicePath);
HANDLE DismountDrive (char *devName, char *devicePath);
int64 FindString (const char *buf, const char *str, int64 bufLen, size_t strLen, int64 startOffset);
BOOL FileExists (const char *filePathPtr);
__int64 FindStringInFile (const char *filePath, const char *str, int strLen);
BOOL TCCopyFile (char *sourceFileName, char *destinationFile);
BOOL SaveBufferToFile (const char *inputBuffer, const char *destinationFile, DWORD inputLength, BOOL bAppend);
BOOL TCFlushFile (FILE *f);
BOOL PrintHardCopyTextUTF16 (wchar_t *text, char *title, int byteLen);
-void GetSpeedString (unsigned __int64 speed, wchar_t *str);
+void GetSpeedString (unsigned __int64 speed, wchar_t *str, size_t cbStr);
BOOL IsNonInstallMode ();
BOOL DriverUnload ();
LRESULT SetCheckBox (HWND hwndDlg, int dlgItem, BOOL state);
BOOL GetCheckBox (HWND hwndDlg, int dlgItem);
void SetListScrollHPos (HWND hList, int topMostVisibleItem);
void ManageStartupSeq (void);
void ManageStartupSeqWiz (BOOL bRemove, const char *arg);
void CleanLastVisitedMRU (void);
void ClearHistory (HWND hwndDlgItem);
LRESULT ListItemAdd (HWND list, int index, char *string);
LRESULT ListItemAddW (HWND list, int index, wchar_t *string);
LRESULT ListSubItemSet (HWND list, int index, int subIndex, char *string);
LRESULT ListSubItemSetW (HWND list, int index, int subIndex, wchar_t *string);
BOOL GetMountList (MOUNT_LIST_STRUCT *list);
int GetDriverRefCount ();
-void GetSizeString (unsigned __int64 size, wchar_t *str);
+void GetSizeString (unsigned __int64 size, wchar_t *str, size_t cbStr);
__int64 GetFileSize64 (const char *path);
BOOL LoadInt16 (char *filePath, int *result, __int64 fileOffset);
BOOL LoadInt32 (char *filePath, unsigned __int32 *result, __int64 fileOffset);
char *LoadFile (const char *fileName, DWORD *size);
char *LoadFileBlock (char *fileName, __int64 fileOffset, size_t count);
char *GetModPath (char *path, int maxSize);
char *GetConfigPath (char *fileName);
char *GetProgramConfigPath (char *fileName);
char GetSystemDriveLetter (void);
void OpenPageHelp (HWND hwndDlg, int nPage);
void TaskBarIconDisplayBalloonTooltip (HWND hwnd, wchar_t *headline, wchar_t *text, BOOL warning);
void InfoBalloon (char *headingStringId, char *textStringId);
void InfoBalloonDirect (wchar_t *headingString, wchar_t *textString);
void WarningBalloon (char *headingStringId, char *textStringId);
void WarningBalloonDirect (wchar_t *headingString, wchar_t *textString);
int Info (char *stringId);
int InfoTopMost (char *stringId);
int InfoDirect (const wchar_t *msg);
int Warning (char *stringId);
int WarningTopMost (char *stringId);
@@ -412,76 +412,76 @@ int ConfigReadInt (char *configKey, int defaultValue);
char *ConfigReadString (char *configKey, char *defaultValue, char *str, int maxLen);
void RestoreDefaultKeyFilesParam (void);
BOOL LoadDefaultKeyFilesParam (void);
void Debug (char *format, ...);
void DebugMsgBox (char *format, ...);
BOOL IsOSAtLeast (OSVersionEnum reqMinOS);
BOOL IsOSVersionAtLeast (OSVersionEnum reqMinOS, int reqMinServicePack);
BOOL Is64BitOs ();
BOOL IsServerOS ();
BOOL IsHiddenOSRunning (void);
BOOL EnableWow64FsRedirection (BOOL enable);
BOOL RestartComputer (void);
void Applink (char *dest, BOOL bSendOS, char *extraOutput);
char *RelativePath2Absolute (char *szFileName);
void HandleDriveNotReadyError ();
BOOL CALLBACK CloseTCWindowsEnum( HWND hwnd, LPARAM lParam);
BOOL CALLBACK FindTCWindowEnum (HWND hwnd, LPARAM lParam);
BYTE *MapResource (char *resourceType, int resourceId, PDWORD size);
void InconsistencyResolved (char *msg);
void ReportUnexpectedState (char *techInfo);
-BOOL SelectMultipleFiles (HWND hwndDlg, char *stringId, char *lpszFileName, BOOL keepHistory);
-BOOL SelectMultipleFilesNext (char *lpszFileName);
+BOOL SelectMultipleFiles (HWND hwndDlg, const char *stringId, char *lpszFileName, size_t cbFileName, BOOL keepHistory);
+BOOL SelectMultipleFilesNext (char *lpszFileName, size_t cbFileName);
void OpenOnlineHelp ();
BOOL GetPartitionInfo (const char *deviceName, PPARTITION_INFORMATION rpartInfo);
BOOL GetDeviceInfo (const char *deviceName, DISK_PARTITION_INFO_STRUCT *info);
BOOL GetDriveGeometry (const char *deviceName, PDISK_GEOMETRY diskGeometry);
BOOL IsVolumeDeviceHosted (const char *lpszDiskFile);
int CompensateXDPI (int val);
int CompensateYDPI (int val);
int CompensateDPIFont (int val);
int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont);
int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont);
BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId);
BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont);
void ToBootPwdField (HWND hwndDlg, UINT ctrlId);
void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont);
BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize);
BOOL DoDriverInstall (HWND hwndDlg);
int OpenVolume (OpenVolumeContext *context, const char *volumePath, Password *password, BOOL write, BOOL preserveTimestamps, BOOL useBackupHeader);
void CloseVolume (OpenVolumeContext *context);
int ReEncryptVolumeHeader (char *buffer, BOOL bBoot, CRYPTO_INFO *cryptoInfo, Password *password, BOOL wipeMode);
BOOL IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly);
BOOL IsPagingFileWildcardActive ();
BOOL DisablePagingFile ();
BOOL CALLBACK SecurityTokenPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
BOOL CALLBACK SecurityTokenKeyfileDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
BOOL InitSecurityTokenLibrary ();
BOOL FileHasReadOnlyAttribute (const char *path);
BOOL IsFileOnReadOnlyFilesystem (const char *path);
void CheckFilesystem (int driveNo, BOOL fixErrors);
BOOL BufferContainsString (const byte *buffer, size_t bufferSize, const char *str);
int AskNonSysInPlaceEncryptionResume ();
BOOL RemoveDeviceWriteProtection (HWND hwndDlg, char *devicePath);
void EnableElevatedCursorChange (HWND parent);
BOOL DisableFileCompression (HANDLE file);
-BOOL VolumePathExists (char *volumePath);
+BOOL VolumePathExists (const char *volumePath);
BOOL IsWindowsIsoBurnerAvailable ();
BOOL LaunchWindowsIsoBurner (HWND hwnd, const char *isoPath);
BOOL IsApplicationInstalled (const char *appName);
#ifdef __cplusplus
}
#include <vector>
#include <string>
struct HostDevice
{
HostDevice ()
:
Bootable (false),
ContainsSystem (false),
DynamicVolume (false),
Floppy (false),
IsPartition (false),
IsVirtualPartition (false),