/* Derived from source code of TrueCrypt 7.1a, which is Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed by the TrueCrypt License 3.0. Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2013-2017 IDRIX and are governed by the Apache License 2.0 the full text of which is contained in the file License.txt included in VeraCrypt binary and source code distribution packages. */ #include "System.h" #include #include #include #include #include "Crypto/cpu.h" #include "Platform/PlatformTest.h" #include "Common/PCSCException.h" #ifdef TC_UNIX #include #include "Platform/Unix/Process.h" #endif #include "Platform/SystemInfo.h" #include "Platform/SystemException.h" #include "Common/SecurityToken.h" #include "Volume/EncryptionTest.h" #include "Application.h" #include "FavoriteVolume.h" #include "UserInterface.h" namespace VeraCrypt { UserInterface::UserInterface () { } UserInterface::~UserInterface () { Core->WarningEvent.Disconnect (this); Core->VolumeMountedEvent.Disconnect (this); try { if (SecurityToken::IsInitialized()) SecurityToken::CloseLibrary(); } catch (...) { } } void UserInterface::CheckRequirementsForMountingVolume () const { #ifdef TC_LINUX if (!Preferences.NonInteractive) { if (!SystemInfo::IsVersionAtLeast (2, 6, 24)) ShowWarning (LangString["LINUX_KERNEL_OLD"]); } #endif // TC_LINUX } void UserInterface::CloseExplorerWindows (shared_ptr mountedVolume) const { #ifdef TC_WINDOWS struct Args { HWND ExplorerWindow; string DriveRootPath; }; struct Enumerator { static BOOL CALLBACK ChildWindows (HWND hwnd, LPARAM argsLP) { Args *args = reinterpret_cast (argsLP); char s[4096]; SendMessageA (hwnd, WM_GETTEXT, sizeof (s), (LPARAM) s); if (strstr (s, args->DriveRootPath.c_str()) != NULL) { PostMessage (args->ExplorerWindow, WM_CLOSE, 0, 0); return FALSE; } return TRUE; } static BOOL CALLBACK TopLevelWindows (HWND hwnd, LPARAM argsLP) { Args *args = reinterpret_cast (argsLP); char s[4096]; GetClassNameA (hwnd, s, sizeof s); if (strcmp (s, "CabinetWClass") == 0) { GetWindowTextA (hwnd, s, sizeof s); if (strstr (s, args->DriveRootPath.c_str()) != NULL) { PostMessage (hwnd, WM_CLOSE, 0, 0); return TRUE; } args->ExplorerWindow = hwnd; EnumChildWindows (hwnd, ChildWindows, argsLP); } return TRUE; } }; Args args; string mountPoint = mountedVolume->MountPoint; if (mountPoint.size() < 2 || mountPoint[1] != ':') return; args.DriveRootPath = string() + mountPoint[0] + string (":\\"); EnumWindows (Enumerator::TopLevelWindows, (LPARAM) &args); #endif } void UserInterface::DismountAllVolumes (bool ignoreOpenFiles, bool interactive) const { try { VolumeInfoList mountedVolumes = Core->GetMountedVolumes(); if (mountedVolumes.size() < 1) ShowInfo (LangString["NO_VOLUMES_MOUNTED"]); BusyScope busy (this); DismountVolumes (mountedVolumes, ignoreOpenFiles, interactive); } catch (exception &e) { ShowError (e); } } void UserInterface::DismountVolume (shared_ptr volume, bool ignoreOpenFiles, bool interactive) const { VolumeInfoList volumes; volumes.push_back (volume); DismountVolumes (volumes, ignoreOpenFiles, interactive); } void UserInterface::DismountVolumes (VolumeInfoList volumes, bool ignoreOpenFiles, bool interactive) const { BusyScope busy (this); volumes.sort (VolumeInfo::FirstVolumeMountedAfterSecond); wxString message; bool twoPassMode = volumes.size() > 1; bool volumesInUse = false; bool firstPass = true; #ifdef TC_WINDOWS if (Preferences.CloseExplorerWindowsOnDismount) { foreach (shared_ptr volume, volumes) CloseExplorerWindows (volume); } #endif while (!volumes.empty()) { VolumeInfoList volumesLeft; foreach (shared_ptr volume, volumes) { try { BusyScope busy (this); volume = Core->DismountVolume (volume, ignoreOpenFiles); } catch (MountedVolumeInUse&) { if (!firstPass) throw; if (twoPassMode || !interactive) { volumesInUse = true; volumesLeft.push_back (volume); continue; } else { if (AskYesNo (StringFormatter (LangString["UNMOUNT_LOCK_FAILED"], wstring (volume->Path)), true, true)) { BusyScope busy (this); volume = Core->DismountVolume (volume, true); } else throw UserAbort (SRC_POS); } } catch (...) { if (twoPassMode && firstPass) volumesLeft.push_back (volume); else throw; } if (volume->HiddenVolumeProtectionTriggered) ShowWarning (StringFormatter (LangString["DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"], wstring (volume->Path))); if (Preferences.Verbose) { if (!message.IsEmpty()) message += L'\n'; message += StringFormatter (LangString["LINUX_VOL_DISMOUNTED"], wstring (volume->Path)); } } if (twoPassMode && firstPass) { volumes = volumesLeft; if (volumesInUse && interactive) { if (AskYesNo (LangString["UNMOUNTALL_LOCK_FAILED"], true, true)) ignoreOpenFiles = true; else throw UserAbort (SRC_POS); } } else break; firstPass = false; } if (Preferences.Verbose && !message.IsEmpty()) ShowInfo (message); } void UserInterface::DisplayVolumeProperties (const VolumeInfoList &volumes) const { if (volumes.size() < 1) throw_err (LangString["NO_VOLUMES_MOUNTED"]); wxString prop; foreach_ref (const VolumeInfo &volume, volumes) { prop << LangString["TOKEN_SLOT_ID"] << L": " << StringConverter::FromNumber (volume.SlotNumber) << L'\n'; prop << LangString["VOLUME"] << L": " << wstring (volume.Path) << L'\n'; #ifndef TC_WINDOWS prop << LangString["VIRTUAL_DEVICE"] << L": " << wstring (volume.VirtualDevice) << L'\n'; #endif prop << LangString["MOUNT_POINT"] << L": " << wstring (volume.MountPoint) << L'\n'; prop << LangString["SIZE"] << L": " << SizeToString (volume.Size) << L'\n'; prop << LangString["TYPE"] << L": " << VolumeTypeToString (volume.Type, volume.Protection) << L'\n'; prop << LangString["READ_ONLY"] << L": " << LangString [volume.Protection == VolumeProtection::ReadOnly ? "UISTR_YES" : "UISTR_NO"] << L'\n'; wxString protection; if (volume.Type == VolumeType::Hidden) protection = LangString["NOT_APPLICABLE_OR_NOT_AVAILABLE"]; else if (volume.HiddenVolumeProtectionTriggered) protection = LangString["HID_VOL_DAMAGE_PREVENTED"]; else protection = LangString [volume.Protection == VolumeProtection::HiddenVolumeReadOnly ? "UISTR_YES" : "UISTR_NO"]; prop << LangString["HIDDEN_VOL_PROTECTION"] << L": " << protection << L'\n'; prop << LangString["ENCRYPTION_ALGORITHM"] << L": " << volume.EncryptionAlgorithmName << L'\n'; prop << LangString["KEY_SIZE"] << L": " << StringFormatter (L"{0} {1}", volume.EncryptionAlgorithmKeySize * 8, LangString ["BITS"]) << L'\n'; if (volume.EncryptionModeName == L"XTS") prop << LangString["SECONDARY_KEY_SIZE_XTS"] << L": " << StringFormatter (L"{0} {1}", volume.EncryptionAlgorithmKeySize * 8, LangString ["BITS"]) << L'\n';; wstringstream blockSize; blockSize << volume.EncryptionAlgorithmBlockSize * 8; if (volume.EncryptionAlgorithmBlockSize != volume.EncryptionAlgorithmMinBlockSize) blockSize << L"/" << volume.EncryptionAlgorithmMinBlockSize * 8; prop << LangString["BLOCK_SIZE"] << L": " << blockSize.str() + L" " + LangString ["BITS"] << L'\n'; prop << LangString["MODE_OF_OPERATION"] << L": " << volume.EncryptionModeName << L'\n'; prop << LangString["PKCS5_PRF"] << L": " << volume.Pkcs5PrfName << L'\n'; prop << LangString["VOLUME_FORMAT_VERSION"] << L": " << (volume.MinRequiredProgramVersion < 0x10b ? 1 : 2) << L'\n'; prop << LangString["BACKUP_HEADER"] << L": " << LangString[volume.MinRequiredProgramVersion >= 0x10b ? "UISTR_YES" : "UISTR_NO"] << L'\n'; #ifdef TC_LINUX if (string (volume.VirtualDevice).find ("/dev/mapper/veracrypt") != 0) { #endif prop << LangString["TOTAL_DATA_READ"] << L": " << SizeToString (volume.TotalDataRead) << L'\n'; prop << LangString["TOTAL_DATA_WRITTEN"] << L": " << SizeToString (volume.TotalDataWritten) << L'\n'; #ifdef TC_LINUX } #endif prop << L'\n'; } ShowString (prop); } wxString UserInterface::ExceptionToMessage (const exception &ex) { wxString message; const Exception *e = dynamic_cast (&ex); if (e) { message = ExceptionToString (*e); // System exception const SystemException *sysEx = dynamic_cast (&ex); if (sysEx) { if (!message.IsEmpty()) { message += L"\n\n"; } message += wxString (sysEx->SystemText()).Trim (true); } if (!message.IsEmpty()) { // Subject if (!e->GetSubject().empty()) { message = message.Trim (true); if (message.EndsWith (L".")) message.Truncate (mess
/*
 Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved.

 Governed by the TrueCrypt License 3.0 the full text of which is contained in
 the file License.txt included in TrueCrypt binary and source code distribution
 packages.
*/

#include "System.h"
#include <wx/tokenzr.h>
#include "Platform/FileStream.h"
#include "Xml.h"

namespace VeraCrypt
{
	XmlParser::XmlParser (const FilePath &fileName)
	{
		make_shared_auto (File, file);
		file->Open (fileName);
		FileStream stream (file);

		XmlText = wxString::FromUTF8 (stream.ReadToEnd().c_str());
	}

	wxString XmlParser::ConvertEscapedChars (wxString xmlString) const
	{
		xmlString.Replace (L"&lt;", L"<");
		xmlString.Replace (L"&gt;", L">");
		xmlString.Replace (L"&amp;", L"&");
		xmlString.Replace (L"&quot;", L"\"");
		return xmlString;
	}

	XmlNodeList XmlParser::GetNodes (const wxString &nodeName) const
	{
		XmlNodeList nodeList;

		size_t nodePos = 0;
		while ((nodePos = XmlText.find (L"<" + nodeName, nodePos)) != string::npos)
		{
			XmlNode xmlNode;
			xmlNode.Name = nodeName;

			size_t nodeEnd = XmlText.find (L">", nodePos);
			if (nodeEnd == string::npos)
				throw ParameterIncorrect (SRC_POS);

			wxString nodeTagText = XmlText.substr (nodePos + 1, nodeEnd - nodePos - 1);
			nodePos = nodeEnd;

			if (nodeTagText.size() > nodeName.size() && nodeTagText[nodeName.size()] != L' ' && nodeTagText[nodeName.size()] != L'/')
				continue;

			nodeTagText = nodeTagText.substr (nodeName.size());


			// Attributes
			wxStringTokenizer tokenizer (nodeTagText, L"\"", wxTOKEN_RET_EMPTY);
			while (tokenizer.HasMoreTokens())
			{
				wxString attributeName = tokenizer.GetNextToken();
				attributeName.Replace (L" ", L"", true);
				attributeName.Replace (L"=", L"");

				if (!attributeName.empty() && tokenizer.HasMoreTokens())
				{
					wxString attributeText = tokenizer.GetNextToken();
					xmlNode.Attributes[attributeName] = ConvertEscapedChars (attributeText);
				}
			}

			// Inner text
			if (!nodeTagText.EndsWith (L"/"))
			{
				size_t innerTextPos = nodeEnd + 1;
				size_t innerTextEnd = XmlText.find (L"</" + nodeName + L">", innerTextPos);
				if (innerTextEnd == string::npos)
					throw ParameterIncorrect (SRC_POS);

				xmlNode.InnerText = ConvertEscapedChars (XmlText.substr (innerTextPos, innerTextEnd - innerTextPos));
				nodePos = innerTextEnd;
			}

			nodeList.push_back (xmlNode);
		}

		return nodeList;
	}

	XmlWriter::XmlWriter (const FilePath &fileName)
	{
		MemOutStream.reset (new wxMemoryOutputStream);
		TextOutStream.reset (new wxTextOutputStream (*MemOutStream));
		OutFile.Open (fileName, File::CreateWrite);

		*TextOutStream << L"<?xml version=\"1.0\" encoding=\"utf-8\"?>" << endl << L"<VeraCrypt>" << endl;
		CurrentIndentLevel = 0;
	}

	void XmlWriter::Close()
	{
		if (MemOutStream.get())
		{
			*TextOutStream << L"</VeraCrypt>" << endl;

			wxStreamBuffer *buf = MemOutStream->GetOutputStreamBuffer();
			OutFile.Write (ConstBufferPtr (reinterpret_cast <byte *> (buf->GetBufferStart()), buf->GetBufferSize()));
			OutFile.Close();

			TextOutStream.reset();
			MemOutStream.reset();
		}
	}

	wxString XmlWriter::EscapeChars (wxString rawString) const
	{
		rawString.Replace (L"<", L"&lt;");
		rawString.Replace (L">", L"&gt;");
		rawString.Replace (L"&", L"&amp;");
		rawString.Replace (L"\"", L"&quot;");
		return rawString;
	}

	void XmlWriter::WriteNode (const XmlNode &xmlNode)
	{
		XmlNodeList nodes;
		nodes.push_back (xmlNode);
		WriteNodes (nodes);
	}

	void XmlWriter::WriteNodes (const XmlNodeList &xmlNodes)
	{
		CurrentIndentLevel++;
		wxString indent;
		for (int i = 0; i < CurrentIndentLevel; ++i)
			indent += L"\t";

		foreach (const XmlNode &node, xmlNodes)
		{
			*TextOutStream << indent << L"<" << node.Name;

			typedef pair <wxString, wxString> AttribPair;
			foreach (AttribPair attrib, node.Attributes)
			{
				*TextOutStream << L" " << attrib.first << L"=\"" << EscapeChars (attrib.second) << L"\"";
			}

			if (!node.InnerNodes.empty())
			{
				*TextOutStream << L">" << endl;
				WriteNodes (node.InnerNodes);
				*TextOutStream << indent;
			}
			else if (!node.InnerText.empty())
			{
				*TextOutStream << L">" << EscapeChars (node.InnerText);
			}
			else
			{
				*TextOutStream << L"/>" << endl;
				continue;
			}

			*TextOutStream << L"</" << node.Name << L">" << endl;
		}

		CurrentIndentLevel--;
	}

	XmlWriter::~XmlWriter ()
	{
		try
		{
			Close();
		}
		catch (...) { }
	}
}
" "--force\n" " Force mounting of a volume in use, dismounting of a volume in use, or\n" " overwriting a file. Note that this option has no effect on some platforms.\n" "\n" "--fs-options=OPTIONS\n" " Filesystem mount options. The OPTIONS argument is passed to mount(8)\n" " command with option -o when a filesystem on a VeraCrypt volume is mounted.\n" " This option is not available on some platforms.\n" "\n" "--hash=HASH\n" " Use specified hash algorithm when creating a new volume or changing password\n" " and/or keyfiles. This option also specifies the mixing PRF of the random\n" " number generator.\n" "\n" "-k, --keyfiles=KEYFILE1[,KEYFILE2,KEYFILE3,...]\n" " Use specified keyfiles when mounting a volume or when changing password\n" " and/or keyfiles. When a directory is specified, all files inside it will be\n" " used (non-recursively). Multiple keyfiles must be separated by comma.\n" " Use double comma (,,) to specify a comma contained in keyfile's name.\n" " Keyfile stored on a security token must be specified as\n" " token://slot/SLOT_NUMBER/file/FILENAME for a security token keyfile\n" " and emv://slot/SLOT_NUMBER for an EMV token keyfile.\n" " An empty keyfile (-k \"\") disables\n" " interactive requests for keyfiles. See also options --import-token-keyfiles,\n" " --list-token-keyfiles, --list-securitytoken-keyfiles, --list-emvtoken-keyfiles,\n" " --new-keyfiles, --protection-keyfiles.\n" "\n" "--load-preferences\n" " Load user preferences.\n" "\n" "-m, --mount-options=OPTION1[,OPTION2,OPTION3,...]\n" " Specifies comma-separated mount options for a VeraCrypt volume:\n" " headerbak: Use backup headers when mounting a volume.\n" " nokernelcrypto: Do not use kernel cryptographic services.\n" " readonly|ro: Mount volume as read-only.\n" " system: Mount partition using system encryption.\n" " timestamp|ts: Do not restore host-file modification timestamp when a volume\n" " is dismounted (note that the operating system under certain circumstances\n" " does not alter host-file timestamps, which may be mistakenly interpreted\n" " to mean that this option does not work).\n" " See also option --fs-options.\n" "\n" "--new-keyfiles=KEYFILE1[,KEYFILE2,KEYFILE3,...]\n" " Add specified keyfiles to a volume. This option can only be used with command\n" " -C.\n" "\n" "--new-password=PASSWORD\n" " Specifies a new password. This option can only be used with command -C.\n" "\n" "--new-pim=PIM\n" " Specifies a new PIM. This option can only be used with command -C.\n" "\n" "-p, --password=PASSWORD\n" " Use specified password to mount/open a volume. An empty password can also be\n" " specified (-p \"\"). Note that passing a password on the command line is\n" " potentially insecure as the password may be visible in the process list\n" " (see ps(1)) and/or stored in a command history file or system logs.\n" "\n" "--pim=PIM\n" " Use specified PIM to mount/open a volume. Note that passing a PIM on the \n" " command line is potentially insecure as the PIM may be visible in the process \n" " list (see ps(1)) and/or stored in a command history file or system logs.\n" "\n" "--protect-hidden=yes|no\n" " Write-protect a hidden volume when mounting an outer volume. Before mounting\n" " the outer volume, the user will be prompted for a password to open the hidden\n" " volume. The size and position of the hidden volume is then determined and the\n" " outer volume is mounted with all sectors belonging to the hidden volume\n" " protected against write operations. When a write to the protected area is\n" " prevented, the whole volume is switched to read-only mode. Verbose list\n" " (-v -l) can be used to query the state of the hidden volume protection.\n" " Warning message is displayed when a volume switched to read-only is being\n" " dismounted.\n" "\n" "--protection-keyfiles=KEYFILE1[,KEYFILE2,KEYFILE3,...]\n" " Use specified keyfiles to open a hidden volume to be protected. This option\n" " may be used only when mounting an outer volume with hidden volume protected.\n" " See also options -k and --protect-hidden.\n" "\n" "--protection-password=PASSWORD\n" " Use specified password to open a hidden volume to be protected. This option\n" " may be used only when mounting an outer volume with hidden volume protected.\n" " See also options -p and --protect-hidden.\n" "\n" "--quick\n" " Do not encrypt free space when creating a device-hosted volume. This option\n" " must not be used when creating an outer volume.\n" "\n" "--random-source=FILE\n" " Use FILE as a source of random data (e.g., when creating a volume) instead\n" " of requiring the user to type random characters.\n" "\n" "--slot=SLOT\n" " Use specified slot number when mounting, dismounting, or listing a volume.\n" "\n" "--size=SIZE[K|KiB|M|MiB|G|GiB|T|TiB] or --size=max\n" " Use specified size when creating a new volume. If no suffix is indicated,\n" " then SIZE is interpreted in bytes. Suffixes K, M, G or T can be used to\n" " indicate a value in KiB, MiB, GiB or TiB respectively.\n" " If max is specified, the new volume will use all available free disk space.\n" "\n" "-t, --text\n" " Use text user interface. Graphical user interface is used by default if\n" " available. This option must be specified as the first argument.\n" "\n" "--token-lib=LIB_PATH\n" " Use specified PKCS #11 security token library.\n" "\n" "--volume-type=TYPE\n" " Use specified volume type when creating a new volume. TYPE can be 'normal'\n" " or 'hidden'. See option -c for more information on creating hidden volumes.\n" "\n" "-v, --verbose\n" " Enable verbose output.\n" "\n" "\n" "IMPORTANT:\n" "\n" "If you want to use VeraCrypt, you must follow the security requirements and\n" "security precautions listed in chapter 'Security Requirements and Precautions'\n" "in the VeraCrypt documentation (file 'VeraCrypt User Guide.pdf').\n" "\n" "\nExamples:\n\n" "Create a new volume:\n" "veracrypt -t -c\n" "\n" "Mount a volume:\n" "veracrypt volume.hc /media/veracrypt1\n" "\n" "Mount a volume as read-only, using keyfiles:\n" "veracrypt -m ro -k keyfile1,keyfile2 volume.hc\n" "\n" "Mount a volume without mounting its filesystem:\n" "veracrypt --filesystem=none volume.hc\n" "\n" "Mount a volume prompting only for its password:\n" "veracrypt -t -k \"\" --pim=0 --protect-hidden=no volume.hc /media/veracrypt1\n" "\n" "Dismount a volume:\n" "veracrypt -d volume.hc\n" "\n" "Dismount all mounted volumes:\n" "veracrypt -d\n" ); #ifndef TC_NO_GUI if (Application::GetUserInterfaceType() == UserInterfaceType::Graphic) { wxDialog dialog (nullptr, wxID_ANY, LangString["LINUX_CMD_HELP"], wxDefaultPosition); wxTextCtrl *textCtrl = new wxTextCtrl (&dialog, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY); textCtrl->SetFont (wxFont (wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, L"Courier")); textCtrl->SetValue (helpText); int fontWidth, fontHeight; textCtrl->GetTextExtent (L"A", &fontWidth, &fontHeight); dialog.SetSize (wxSize (fontWidth * 85, fontHeight * 29)); wxBoxSizer *sizer = new wxBoxSizer (wxVERTICAL); sizer->Add (textCtrl, 1, wxALL | wxEXPAND, 5); sizer->Add (new wxButton (&dialog, wxID_OK, LangString["IDOK"]), 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 5); dialog.SetSizer (sizer); dialog.Layout(); dialog.ShowModal(); } else #endif // !TC_NO_GUI { ShowString (L"\n\n"); ShowString (helpText); } } return true; case CommandId::ExportTokenKeyfile: ExportTokenKeyfile(); return true; case CommandId::ImportTokenKeyfiles: ImportTokenKeyfiles(); return true; case CommandId::ListTokenKeyfiles: ListTokenKeyfiles(); return true; case CommandId::ListSecurityTokenKeyfiles: ListSecurityTokenKeyfiles(); return true; case CommandId::ListEMVTokenKeyfiles: ListEMVTokenKeyfiles(); return true; case CommandId::ListVolumes: if (Preferences.Verbose) DisplayVolumeProperties (cmdLine.ArgVolumes); else ListMountedVolumes (cmdLine.ArgVolumes); return true; case CommandId::RestoreHeaders: RestoreVolumeHeaders (cmdLine.ArgVolumePath); return true; case CommandId::SavePreferences: Preferences.Save(); return true; case CommandId::Test: Test(); return true; default: throw ParameterIncorrect (SRC_POS); } return false; } void UserInterface::SetPreferences (const UserPreferences &preferences) { Preferences = preferences; Cipher::EnableHwSupport (!preferences.DefaultMountOptions.NoHardwareCrypto); PreferencesUpdatedEvent.Raise(); } void UserInterface::ShowError (const exception &ex) const { if (!dynamic_cast (&ex)) DoShowError (ExceptionToMessage (ex)); } wxString UserInterface::SizeToString (uint64 size) const { wstringstream s; if (size > 1024ULL*1024*1024*1024*1024*99) s << size/1024/1024/1024/1024/1024 << L" " << LangString["PB"].c_str(); else if (size > 1024ULL*1024*1024*1024*1024) return wxString::Format (L"%.1f %s", (double)(size/1024.0/1024/1024/1024/1024), LangString["PB"].c_str()); else if (size > 1024ULL*1024*1024*1024*99) s << size/1024/1024/1024/1024 << L" " << LangString["TB"].c_str(); else if (size > 1024ULL*1024*1024*1024) return wxString::Format (L"%.1f %s", (double)(size/1024.0/1024/1024/1024), LangString["TB"].c_str()); else if (size > 1024ULL*1024*1024*99) s << size/1024/1024/1024 << L" " << LangString["GB"].c_str(); else if (size > 1024ULL*1024*1024) return wxString::Format (L"%.1f %s", (double)(size/1024.0/1024/1024), LangString["GB"].c_str()); else if (size > 1024ULL*1024*99) s << size/1024/1024 << L" " << LangString["MB"].c_str(); else if (size > 1024ULL*1024) return wxString::Format (L"%.1f %s", (double)(size/1024.0/1024), LangString["MB"].c_str()); else if (size > 1024ULL) s << size/1024 << L" " << LangString["KB"].c_str(); else s << size << L" " << LangString["BYTE"].c_str(); return s.str(); } wxString UserInterface::SpeedToString (uint64 speed) const { wstringstream s; if (speed > 1024ULL*1024*1024*1024*1024*99) s << speed/1024/1024/1024/1024/1024 << L" " << LangString["PB_PER_SEC"].c_str(); else if (speed > 1024ULL*1024*1024*1024*1024) return wxString::Format (L"%.1f %s", (double)(speed/1024.0/1024/1024/1024/1024), LangString["PB_PER_SEC"].c_str()); else if (speed > 1024ULL*1024*1024*1024*99) s << speed/1024/1024/1024/1024 << L" " << LangString["TB_PER_SEC"].c_str(); else if (speed > 1024ULL*1024*1024*1024) return wxString::Format (L"%.1f %s", (double)(speed/1024.0/1024/1024/1024), LangString["TB_PER_SEC"].c_str()); else if (speed > 1024ULL*1024*1024*99) s << speed/1024/1024/1024 << L" " << LangString["GB_PER_SEC"].c_str(); else if (speed > 1024ULL*1024*999) return wxString::Format (L"%.1f %s", (double)(speed/1024.0/1024/1024), LangString["GB_PER_SEC"].c_str()); else if (speed > 1024ULL*1024*9) s << speed/1024/1024 << L" " << LangString["MB_PER_SEC"].c_str(); else if (speed > 1024ULL*999) return wxString::Format (L"%.1f %s", (double)(speed/1024.0/1024), LangString["MB_PER_SEC"].c_str()); else if (speed > 1024ULL) s << speed/1024 << L" " << LangString["KB_PER_SEC"].c_str(); else s << speed << L" " << LangString["B_PER_SEC"].c_str(); return s.str(); } void UserInterface::Test () const { if (!PlatformTest::TestAll()) throw TestFailed (SRC_POS); EncryptionTest::TestAll(); // StringFormatter if (StringFormatter (L"{9} {8} {7} {6} {5} {4} {3} {2} {1} {0} {{0}}", "1", L"2", '3', L'4', 5, 6, 7, 8, 9, 10) != L"10 9 8 7 6 5 4 3 2 1 {0}") throw TestFailed (SRC_POS); try { StringFormatter (L"{0} {1}", 1); throw TestFailed (SRC_POS); } catch (StringFormatterException&) { } try { StringFormatter (L"{0} {1} {1}", 1, 2, 3); throw TestFailed (SRC_POS); } catch (StringFormatterException&) { } try { StringFormatter (L"{0} 1}", 1, 2); throw TestFailed (SRC_POS); } catch (StringFormatterException&) { } try { StringFormatter (L"{0} {1", 1, 2); throw TestFailed (SRC_POS); } catch (StringFormatterException&) { } ShowInfo ("TESTS_PASSED"); } wxString UserInterface::TimeSpanToString (uint64 seconds) const { wstringstream s; if (seconds >= 60 * 60 * 24 * 2) s << seconds / (60 * 24 * 60) << L" " << LangString["DAYS"].c_str(); else if (seconds >= 120 * 60) s << seconds / (60 * 60) << L" " << LangString["HOURS"].c_str(); else if (seconds >= 120) s << seconds / 60 << L" " << LangString["MINUTES"].c_str(); else s << seconds << L" " << LangString["SECONDS"].c_str(); return s.str(); } bool UserInterface::VolumeHasUnrecommendedExtension (const VolumePath &path) const { wxString ext = wxFileName (wxString (wstring (path)).Lower()).GetExt(); return ext.IsSameAs (L"exe") || ext.IsSameAs (L"sys") || ext.IsSameAs (L"dll"); } wxString UserInterface::VolumeTimeToString (VolumeTime volumeTime) const { wxString dateStr = VolumeTimeToDateTime (volumeTime).Format(); #ifdef TC_WINDOWS FILETIME ft; *(unsigned __int64 *)(&ft) = volumeTime; SYSTEMTIME st; FileTimeToSystemTime (&ft, &st); wchar_t wstr[1024]; if (GetDateFormat (LOCALE_USER_DEFAULT, 0, &st, 0, wstr, array_capacity (wstr)) != 0) { dateStr = wstr; GetTimeFormat (LOCALE_USER_DEFAULT, 0, &st, 0, wstr, array_capacity (wstr)); dateStr += wxString (L" ") + wstr; } #endif return dateStr; } wxString UserInterface::VolumeTypeToString (VolumeType::Enum type, VolumeProtection::Enum protection) const { wxString sResult; switch (type) { case VolumeType::Normal: sResult = LangString[protection == VolumeProtection::HiddenVolumeReadOnly ? "OUTER" : "NORMAL"]; break; case VolumeType::Hidden: sResult = LangString["HIDDEN"]; break; default: sResult = L"?"; break; } return sResult; } #define VC_CONVERT_EXCEPTION(NAME) if (dynamic_cast (ex)) throw (NAME&) *ex; void UserInterface::ThrowException (Exception* ex) { VC_CONVERT_EXCEPTION (PasswordIncorrect); VC_CONVERT_EXCEPTION (PasswordKeyfilesIncorrect); VC_CONVERT_EXCEPTION (PasswordOrKeyboardLayoutIncorrect); VC_CONVERT_EXCEPTION (PasswordOrMountOptionsIncorrect); VC_CONVERT_EXCEPTION (ProtectionPasswordIncorrect); VC_CONVERT_EXCEPTION (ProtectionPasswordKeyfilesIncorrect); VC_CONVERT_EXCEPTION (PasswordEmpty); VC_CONVERT_EXCEPTION (PasswordTooLong); VC_CONVERT_EXCEPTION (PasswordUTF8TooLong); VC_CONVERT_EXCEPTION (PasswordLegacyUTF8TooLong); VC_CONVERT_EXCEPTION (PasswordUTF8Invalid); VC_CONVERT_EXCEPTION (UnportablePassword); VC_CONVERT_EXCEPTION (ElevationFailed); VC_CONVERT_EXCEPTION (RootDeviceUnavailable); VC_CONVERT_EXCEPTION (DriveLetterUnavailable); VC_CONVERT_EXCEPTION (DriverError); VC_CONVERT_EXCEPTION (DeviceSectorSizeMismatch); VC_CONVERT_EXCEPTION (EncryptedSystemRequired); VC_CONVERT_EXCEPTION (HigherFuseVersionRequired); VC_CONVERT_EXCEPTION (KernelCryptoServiceTestFailed); VC_CONVERT_EXCEPTION (LoopDeviceSetupFailed); VC_CONVERT_EXCEPTION (MountPointRequired); VC_CONVERT_EXCEPTION (MountPointUnavailable); VC_CONVERT_EXCEPTION (NoDriveLetterAvailable); VC_CONVERT_EXCEPTION (TemporaryDirectoryFailure); VC_CONVERT_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection); VC_CONVERT_EXCEPTION (UnsupportedSectorSizeNoKernelCrypto); VC_CONVERT_EXCEPTION (VolumeAlreadyMounted); VC_CONVERT_EXCEPTION (VolumeSlotUnavailable); VC_CONVERT_EXCEPTION (UserInterfaceException); VC_CONVERT_EXCEPTION (MissingArgument); VC_CONVERT_EXCEPTION (NoItemSelected); VC_CONVERT_EXCEPTION (StringFormatterException); VC_CONVERT_EXCEPTION (ExecutedProcessFailed); VC_CONVERT_EXCEPTION (AlreadyInitialized); VC_CONVERT_EXCEPTION (AssertionFailed); VC_CONVERT_EXCEPTION (ExternalException); VC_CONVERT_EXCEPTION (InsufficientData); VC_CONVERT_EXCEPTION (NotApplicable); VC_CONVERT_EXCEPTION (NotImplemented); VC_CONVERT_EXCEPTION (NotInitialized); VC_CONVERT_EXCEPTION (ParameterIncorrect); VC_CONVERT_EXCEPTION (ParameterTooLarge); VC_CONVERT_EXCEPTION (PartitionDeviceRequired); VC_CONVERT_EXCEPTION (StringConversionFailed); VC_CONVERT_EXCEPTION (TerminalNotFound); VC_CONVERT_EXCEPTION (TestFailed); VC_CONVERT_EXCEPTION (TimeOut); VC_CONVERT_EXCEPTION (UnknownException); VC_CONVERT_EXCEPTION (UserAbort) VC_CONVERT_EXCEPTION (CipherInitError); VC_CONVERT_EXCEPTION (WeakKeyDetected); VC_CONVERT_EXCEPTION (HigherVersionRequired); VC_CONVERT_EXCEPTION (KeyfilePathEmpty); VC_CONVERT_EXCEPTION (MissingVolumeData); VC_CONVERT_EXCEPTION (MountedVolumeInUse); VC_CONVERT_EXCEPTION (UnsupportedSectorSize); VC_CONVERT_EXCEPTION (VolumeEncryptionNotCompleted); VC_CONVERT_EXCEPTION (VolumeHostInUse); VC_CONVERT_EXCEPTION (VolumeProtected); VC_CONVERT_EXCEPTION (VolumeReadOnly); VC_CONVERT_EXCEPTION (Pkcs11Exception); VC_CONVERT_EXCEPTION (InvalidSecurityTokenKeyfilePath); VC_CONVERT_EXCEPTION (SecurityTokenLibraryNotInitialized); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileAlreadyExists); VC_CONVERT_EXCEPTION (SecurityTokenKeyfileNotFound); VC_CONVERT_EXCEPTION (SystemException); VC_CONVERT_EXCEPTION (CipherException); VC_CONVERT_EXCEPTION (VolumeException); VC_CONVERT_EXCEPTION (PasswordException); VC_CONVERT_EXCEPTION (PCSCException); VC_CONVERT_EXCEPTION (CommandAPDUNotValid); VC_CONVERT_EXCEPTION (ExtendedAPDUNotSupported); VC_CONVERT_EXCEPTION (ScardLibraryInitializationFailed); VC_CONVERT_EXCEPTION (EMVUnknownCardType); VC_CONVERT_EXCEPTION (EMVSelectAIDFailed); VC_CONVERT_EXCEPTION (EMVIccCertNotFound); VC_CONVERT_EXCEPTION (EMVIssuerCertNotFound); VC_CONVERT_EXCEPTION (EMVCPLCNotFound); VC_CONVERT_EXCEPTION (InvalidEMVPath); VC_CONVERT_EXCEPTION (EMVKeyfileDataNotFound); VC_CONVERT_EXCEPTION (EMVPANNotFound); throw *ex; } }