Repository navigation
Expand file tree
/
Copy pathUserInterface.cpp
More file actions
1494 lines (1282 loc) · 49.5 KB
/
Copy pathUserInterface.cpp
File metadata and controls
1494 lines (1282 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2008-2010 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 <set>
#include <typeinfo>
#include <wx/apptrait.h>
#include <wx/cmdline.h>
#include "Platform/PlatformTest.h"
#ifdef TC_UNIX
#include <errno.h>
#include "Platform/Unix/Process.h"
#endif
#include "Platform/SystemInfo.h"
#include "Common/SecurityToken.h"
#include "Volume/EncryptionTest.h"
#include "Application.h"
#include "FavoriteVolume.h"
#include "UserInterface.h"
namespace TrueCrypt
{
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 (_("Your system uses an old version of the Linux kernel.\n\nDue to a bug in the Linux kernel, your system may stop responding when writing data to a TrueCrypt volume. This problem can be solved by upgrading the kernel to version 2.6.24 or later."));
}
#endif // TC_LINUX
}
void UserInterface::CloseExplorerWindows (shared_ptr <VolumeInfo> 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 <Args *> (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 <Args *> (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 <VolumeInfo> 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 <VolumeInfo> volume, volumes)
CloseExplorerWindows (volume);
}
#endif
while (!volumes.empty())
{
VolumeInfoList volumesLeft;
foreach (shared_ptr <VolumeInfo> 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 (_("Volume \"{0}\" has been 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 << _("Slot") << 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 < 0x600 ? 1 : 2) << L'\n';
prop << LangString["BACKUP_HEADER"] << L": " << LangString[volume.MinRequiredProgramVersion >= 0x600 ? "UISTR_YES" : "UISTR_NO"] << L'\n';
#ifdef TC_LINUX
if (string (volume.VirtualDevice).find ("/dev/mapper/truecrypt") != 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) const
{
wxString message;
const Exception *e = dynamic_cast <const Exception *> (&ex);
if (e)
{
message = ExceptionToString (*e);
// System exception
const SystemException *sysEx = dynamic_cast <const SystemException *> (&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 (message.size() - 1);
if (!message.EndsWith (L":"))
message << L":\n";
else
message << L"\n";
message << e->GetSubject();
}
#ifdef TC_UNIX
if (sysEx && sysEx->GetErrorCode() == EIO)
message << L"\n\n" << LangString["ERR_HARDWARE_ERROR"];
#endif
#ifdef DEBUG
if (sysEx && sysEx->what())
message << L"\n\n" << StringConverter::ToWide (sysEx->what());
#endif
return message;
}
}
// bad_alloc
const bad_alloc *outOfMemory = dynamic_cast <const bad_alloc *> (&ex);
if (outOfMemory)
return _("Out of memory.");
// Unresolved exceptions
string typeName (StringConverter::GetTypeName (typeid (ex)));
size_t pos = typeName.find ("TrueCrypt::");
if (pos != string::npos)
{
return StringConverter::ToWide (typeName.substr (pos + string ("TrueCrypt::").size()))
+ L" at " + StringConverter::ToWide (ex.what());
}
return StringConverter::ToWide (typeName) + L" at " + StringConverter::ToWide (ex.what());
}
wxString UserInterface::ExceptionToString (const Exception &ex) const
{
// Error messages
const ErrorMessage *errMsgEx = dynamic_cast <const ErrorMessage *> (&ex);
if (errMsgEx)
return wstring (*errMsgEx).c_str();
// ExecutedProcessFailed
const ExecutedProcessFailed *execEx = dynamic_cast <const ExecutedProcessFailed *> (&ex);
if (execEx)
{
wstring errOutput;
// ElevationFailed
if (dynamic_cast <const ElevationFailed*> (&ex))
errOutput += wxString (_("Failed to obtain administrator privileges")) + (StringConverter::Trim (execEx->GetErrorOutput()).empty() ? L". " : L": ");
errOutput += StringConverter::ToWide (execEx->GetErrorOutput());
if (errOutput.empty())
return errOutput + StringFormatter (_("Command \"{0}\" returned error {1}."), execEx->GetCommand(), execEx->GetExitCode());
return wxString (errOutput).Trim (true);
}
// PasswordIncorrect
if (dynamic_cast <const PasswordException *> (&ex))
{
wxString message = ExceptionTypeToString (typeid (ex));
#ifndef TC_NO_GUI
if (Application::GetUserInterfaceType() == UserInterfaceType::Graphic && wxGetKeyState (WXK_CAPITAL))
message += wxString (L"\n\n") + LangString["CAPSLOCK_ON"];
#endif
if (Keyfile::WasHiddenFilePresentInKeyfilePath())
{
#ifdef TC_UNIX
message += _("\n\nWarning: Hidden files are present in a keyfile path. If you need to use them as keyfiles, remove the leading dot from their filenames. Hidden files are visible only if enabled in system options.");
#else
message += LangString["HIDDEN_FILES_PRESENT_IN_KEYFILE_PATH"];
#endif
}
return message;
}
// PKCS#11 Exception
if (dynamic_cast <const Pkcs11Exception *> (&ex))
{
string errorString = string (dynamic_cast <const Pkcs11Exception &> (ex));
if (LangString.Exists (errorString))
return LangString[errorString];
if (errorString.find ("CKR_") == 0)
{
errorString = errorString.substr (4);
for (size_t i = 0; i < errorString.size(); ++i)
{
if (errorString[i] == '_')
errorString[i] = ' ';
}
}
return LangString["SECURITY_TOKEN_ERROR"] + L":\n\n" + StringConverter::ToWide (errorString);
}
// Other library exceptions
return ExceptionTypeToString (typeid (ex));
}
wxString UserInterface::ExceptionTypeToString (const std::type_info &ex) const
{
#define EX2MSG(exception, message) do { if (ex == typeid (exception)) return (message); } while (false)
EX2MSG (DriveLetterUnavailable, LangString["DRIVE_LETTER_UNAVAILABLE"]);
EX2MSG (EncryptedSystemRequired, _("This operation must be performed only when the system hosted on the volume is running."));
EX2MSG (ExternalException, LangString["EXCEPTION_OCCURRED"]);
EX2MSG (InsufficientData, _("Not enough data available."));
EX2MSG (InvalidSecurityTokenKeyfilePath, LangString["INVALID_TOKEN_KEYFILE_PATH"]);
EX2MSG (HigherVersionRequired, LangString["NEW_VERSION_REQUIRED"]);
EX2MSG (KernelCryptoServiceTestFailed, _("Kernel cryptographic service test failed. The cryptographic service of your kernel most likely does not support volumes larger than 2 TB.\n\nPossible solutions:\n- Upgrade the Linux kernel to version 2.6.33 or later.\n- Disable use of the kernel cryptographic services (Settings > Preferences > System Integration) or use 'nokernelcrypto' mount option on the command line."));
EX2MSG (KeyfilePathEmpty, LangString["ERR_KEYFILE_PATH_EMPTY"]);
EX2MSG (LoopDeviceSetupFailed, _("Failed to set up a loop device."));
EX2MSG (MissingArgument, _("A required argument is missing."));
EX2MSG (MissingVolumeData, _("Volume data missing."));
EX2MSG (MountPointRequired, _("Mount point required."));
EX2MSG (MountPointUnavailable, _("Mount point is already in use."));
EX2MSG (NoDriveLetterAvailable, LangString["NO_FREE_DRIVES"]);
EX2MSG (PasswordEmpty, _("No password or keyfile specified."));
EX2MSG (PasswordIncorrect, LangString["PASSWORD_WRONG"]);
EX2MSG (PasswordKeyfilesIncorrect, LangString["PASSWORD_OR_KEYFILE_WRONG"]);
EX2MSG (PasswordOrKeyboardLayoutIncorrect, LangString["PASSWORD_OR_KEYFILE_WRONG"] + _("\n\nNote that pre-boot authentication passwords need to be typed in the pre-boot environment where non-US keyboard layouts are not available. Therefore, pre-boot authentication passwords must always be typed using the standard US keyboard layout (otherwise, the password will be typed incorrectly in most cases). However, note that you do NOT need a real US keyboard; you just need to change the keyboard layout in your operating system."));
EX2MSG (PasswordOrMountOptionsIncorrect, LangString["PASSWORD_OR_KEYFILE_OR_MODE_WRONG"] + _("\n\nNote: If you are attempting to mount a partition located on an encrypted system drive without pre-boot authentication or to mount the encrypted system partition of an operating system that is not running, you can do so by selecting 'Options >' > 'Mount partition using system encryption'."));
EX2MSG (PasswordTooLong, StringFormatter (_("Password is longer than {0} characters."), (int) VolumePassword::MaxSize));
EX2MSG (PartitionDeviceRequired, _("Partition device required."));
EX2MSG (ProtectionPasswordIncorrect, _("Incorrect password to the protected hidden volume or the hidden volume does not exist."));
EX2MSG (ProtectionPasswordKeyfilesIncorrect,_("Incorrect keyfile(s) and/or password to the protected hidden volume or the hidden volume does not exist."));
EX2MSG (RootDeviceUnavailable, LangString["NODRIVER"]);
EX2MSG (SecurityTokenKeyfileAlreadyExists, LangString["TOKEN_KEYFILE_ALREADY_EXISTS"]);
EX2MSG (SecurityTokenKeyfileNotFound, LangString["TOKEN_KEYFILE_NOT_FOUND"]);
EX2MSG (SecurityTokenLibraryNotInitialized, LangString["PKCS11_MODULE_INIT_FAILED"]);
EX2MSG (StringConversionFailed, _("Invalid characters encountered."));
EX2MSG (StringFormatterException, _("Error while parsing formatted string."));
EX2MSG (TemporaryDirectoryFailure, _("Failed to create a file or directory in a temporary directory.\n\nPlease make sure that the temporary directory exists, its security permissions allow you to access it, and there is sufficient disk space."));
EX2MSG (UnportablePassword, LangString["UNSUPPORTED_CHARS_IN_PWD"]);
#if defined (TC_LINUX)
EX2MSG (UnsupportedSectorSize, LangString["SECTOR_SIZE_UNSUPPORTED"]);
EX2MSG (UnsupportedSectorSizeHiddenVolumeProtection, _("Error: The drive uses a sector size other than 512 bytes.\n\nDue to limitations of components available on your platform, outer volumes hosted on the drive cannot be mounted using hidden volume protection.\n\nPossible solutions:\n- Use a drive with 512-byte sectors.\n- Create a file-hosted volume (container) on the drive.\n- Backup the contents of the hidden volume and then update the outer volume."));
EX2MSG (UnsupportedSectorSizeNoKernelCrypto, _("Error: The drive uses a sector size other than 512 bytes.\n\nDue to limitations of components available on your platform, partition/device-hosted volumes on the drive can only be mounted using kernel cryptographic services.\n\nPossible solutions:\n- Enable use of the kernel cryptographic services (Preferences > System Integration).\n- Use a drive with 512-byte sectors.\n- Create a file-hosted volume (container) on the drive."));
#else
EX2MSG (UnsupportedSectorSize, _("Error: The drive uses a sector size other than 512 bytes.\n\nDue to limitations of components available on your platform, partition/device-hosted volumes cannot be created/used on the drive.\n\nPossible solutions:\n- Create a file-hosted volume (container) on the drive.\n- Use a drive with 512-byte sectors.\n- Use TrueCrypt on another platform."));
#endif
EX2MSG (VolumeAlreadyMounted, LangString["VOL_ALREADY_MOUNTED"]);
EX2MSG (VolumeEncryptionNotCompleted, LangString["ERR_ENCRYPTION_NOT_COMPLETED"]);
EX2MSG (VolumeHostInUse, _("The host file/device is already in use."));
EX2MSG (VolumeSlotUnavailable, _("Volume slot unavailable."));
#ifdef TC_MACOSX
EX2MSG (HigherFuseVersionRequired, _("TrueCrypt requires MacFUSE 1.3 or later."));
#endif
#undef EX2MSG
return L"";
}
void UserInterface::Init ()
{
SetAppName (Application::GetName());
SetClassName (Application::GetName());
LangString.Init();
Core->Init();
wxCmdLineParser parser;
parser.SetCmdLine (argc, argv);
CmdLine.reset (new CommandLineInterface (parser, InterfaceType));
SetPreferences (CmdLine->Preferences);
Core->SetApplicationExecutablePath (Application::GetExecutablePath());
if (!Preferences.NonInteractive)
{
Core->SetAdminPasswordCallback (GetAdminPasswordRequestHandler());
}
else
{
struct AdminPasswordRequestHandler : public GetStringFunctor
{
virtual void operator() (string &str)
{
throw ElevationFailed (SRC_POS, "sudo", 1, "");
}
};
Core->SetAdminPasswordCallback (shared_ptr <GetStringFunctor> (new AdminPasswordRequestHandler));
}
Core->WarningEvent.Connect (EventConnector <UserInterface> (this, &UserInterface::OnWarning));
Core->VolumeMountedEvent.Connect (EventConnector <UserInterface> (this, &UserInterface::OnVolumeMounted));
if (!CmdLine->Preferences.SecurityTokenModule.IsEmpty() && !SecurityToken::IsInitialized())
{
try
{
InitSecurityTokenLibrary();
}
catch (exception &e)
{
if (Preferences.NonInteractive)
throw;
ShowError (e);
}
}
}
void UserInterface::ListMountedVolumes (const VolumeInfoList &volumes) const
{
if (volumes.size() < 1)
throw_err (LangString["NO_VOLUMES_MOUNTED"]);
wxString message;
foreach_ref (const VolumeInfo &volume, volumes)
{
message << volume.SlotNumber << L": " << StringConverter::QuoteSpaces (volume.Path);
if (!volume.VirtualDevice.IsEmpty())
message << L' ' << wstring (volume.VirtualDevice);
else
message << L" - ";
if (!volume.MountPoint.IsEmpty())
message << L' ' << StringConverter::QuoteSpaces (volume.MountPoint);
else
message << L" - ";
message << L'\n';
}
ShowString (message);
}
VolumeInfoList UserInterface::MountAllDeviceHostedVolumes (MountOptions &options) const
{
BusyScope busy (this);
VolumeInfoList newMountedVolumes;
if (!options.MountPoint)
options.MountPoint.reset (new DirectoryPath);
Core->CoalesceSlotNumberAndMountPoint (options);
bool sharedAccessAllowed = options.SharedAccessAllowed;
bool someVolumesShared = false;
HostDeviceList devices;
foreach (shared_ptr <HostDevice> device, Core->GetHostDevices (true))
{
devices.push_back (device);
foreach (shared_ptr <HostDevice> partition, device->Partitions)
devices.push_back (partition);
}
set <wstring> mountedVolumes;
foreach_ref (const VolumeInfo &v, Core->GetMountedVolumes())
mountedVolumes.insert (v.Path);
bool protectedVolumeMounted = false;
bool legacyVolumeMounted = false;
foreach_ref (const HostDevice &device, devices)
{
if (mountedVolumes.find (wstring (device.Path)) != mountedVolumes.end())
continue;
Yield();
options.SlotNumber = Core->GetFirstFreeSlotNumber (options.SlotNumber);
options.MountPoint.reset (new DirectoryPath);
options.Path.reset (new VolumePath (device.Path));
try
{
try
{
options.SharedAccessAllowed = sharedAccessAllowed;
newMountedVolumes.push_back (Core->MountVolume (options));
}
catch (VolumeHostInUse&)
{
if (!sharedAccessAllowed)
{
try
{
options.SharedAccessAllowed = true;
newMountedVolumes.push_back (Core->MountVolume (options));
someVolumesShared = true;
}
catch (VolumeHostInUse&)
{
continue;
}
}
else
continue;
}
if (newMountedVolumes.back()->Protection == VolumeProtection::HiddenVolumeReadOnly)
protectedVolumeMounted = true;
if (newMountedVolumes.back()->EncryptionAlgorithmMinBlockSize == 8)
legacyVolumeMounted = true;
}
catch (DriverError&) { }
catch (MissingVolumeData&) { }
catch (PasswordException&) { }
catch (SystemException&) { }
catch (ExecutedProcessFailed&) { }
}
if (newMountedVolumes.empty())
{
ShowWarning (LangString [options.Keyfiles && !options.Keyfiles->empty() ? "PASSWORD_OR_KEYFILE_WRONG_AUTOMOUNT" : "PASSWORD_WRONG_AUTOMOUNT"]);
}
else
{
if (someVolumesShared)
ShowWarning ("DEVICE_IN_USE_INFO");
if (legacyVolumeMounted)
ShowWarning ("WARN_64_BIT_BLOCK_CIPHER");
if (protectedVolumeMounted)
ShowInfo (LangString[newMountedVolumes.size() > 1 ? "HIDVOL_PROT_WARN_AFTER_MOUNT_PLURAL" : "HIDVOL_PROT_WARN_AFTER_MOUNT"]);
}
if (!newMountedVolumes.empty() && GetPreferences().CloseSecurityTokenSessionsAfterMount)
SecurityToken::CloseAllSessions();
return newMountedVolumes;
}
VolumeInfoList UserInterface::MountAllFavoriteVolumes (MountOptions &options)
{
BusyScope busy (this);
VolumeInfoList newMountedVolumes;
foreach_ref (const FavoriteVolume &favorite, FavoriteVolume::LoadList())
{
shared_ptr <VolumeInfo> mountedVolume = Core->GetMountedVolume (favorite.Path);
if (mountedVolume)
{
if (mountedVolume->MountPoint != favorite.MountPoint)
ShowInfo (StringFormatter (LangString["VOLUME_ALREADY_MOUNTED"], wstring (favorite.Path)));
continue;
}
favorite.ToMountOptions (options);
if (Preferences.NonInteractive)
{
BusyScope busy (this);
newMountedVolumes.push_back (Core->MountVolume (options));
}
else
{
try
{
BusyScope busy (this);
newMountedVolumes.push_back (Core->MountVolume (options));
}
catch (...)
{
UserPreferences prefs = GetPreferences();
if (prefs.CloseSecurityTokenSessionsAfterMount)
Preferences.CloseSecurityTokenSessionsAfterMount = false;
shared_ptr <VolumeInfo> volume = MountVolume (options);
if (prefs.CloseSecurityTokenSessionsAfterMount)
Preferences.CloseSecurityTokenSessionsAfterMount = true;
if (!volume)
break;
newMountedVolumes.push_back (volume);
}
}
}
if (!newMountedVolumes.empty() && GetPreferences().CloseSecurityTokenSessionsAfterMount)
SecurityToken::CloseAllSessions();
return newMountedVolumes;
}
shared_ptr <VolumeInfo> UserInterface::MountVolume (MountOptions &options) const
{
shared_ptr <VolumeInfo> volume;
try
{
volume = Core->MountVolume (options);
}
catch (VolumeHostInUse&)
{
if (options.SharedAccessAllowed)
throw_err (LangString["FILE_IN_USE_FAILED"]);
if (!AskYesNo (StringFormatter (LangString["VOLUME_HOST_IN_USE"], wstring (*options.Path)), false, true))
throw UserAbort (SRC_POS);
try
{
options.SharedAccessAllowed = true;
volume = Core->MountVolume (options);
}
catch (VolumeHostInUse&)
{
throw_err (LangString["FILE_IN_USE_FAILED"]);
}
}
if (volume->EncryptionAlgorithmMinBlockSize == 8)
ShowWarning ("WARN_64_BIT_BLOCK_CIPHER");
if (VolumeHasUnrecommendedExtension (*options.Path))
ShowWarning ("EXE_FILE_EXTENSION_MOUNT_WARNING");
if (options.Protection == VolumeProtection::HiddenVolumeReadOnly)
ShowInfo ("HIDVOL_PROT_WARN_AFTER_MOUNT");
if (GetPreferences().CloseSecurityTokenSessionsAfterMount)
SecurityToken::CloseAllSessions();
return volume;
}
void UserInterface::OnUnhandledException ()
{
try
{
throw;
}
catch (UserAbort&)
{
}
catch (exception &e)
{
ShowError (e);
}
catch (...)
{
ShowError (_("Unknown exception occurred."));
}
Yield();
Application::SetExitCode (1);
}
void UserInterface::OnVolumeMounted (EventArgs &args)
{
shared_ptr <VolumeInfo> mountedVolume = (dynamic_cast <VolumeEventArgs &> (args)).mVolume;
if (Preferences.OpenExplorerWindowAfterMount && !mountedVolume->MountPoint.IsEmpty())
OpenExplorerWindow (mountedVolume->MountPoint);
}
void UserInterface::OnWarning (EventArgs &args)
{
ExceptionEventArgs &e = dynamic_cast <ExceptionEventArgs &> (args);
ShowWarning (e.mException);
}
void UserInterface::OpenExplorerWindow (const DirectoryPath &path)
{
if (path.IsEmpty())
return;
list <string> args;
#ifdef TC_WINDOWS
wstring p (Directory::AppendSeparator (path));
SHFILEINFO fInfo;
SHGetFileInfo (p.c_str(), 0, &fInfo, sizeof (fInfo), 0); // Force explorer to discover the drive
ShellExecute (GetTopWindow() ? static_cast <HWND> (GetTopWindow()->GetHandle()) : nullptr, L"open", p.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined (TC_MACOSX)
args.push_back (string (path));
try
{
Process::Execute ("open", args);
}
catch (exception &e) { ShowError (e); }
#else
// MIME handler for directory seems to be unavailable through wxWidgets
wxString desktop = GetTraits()->GetDesktopEnvironment();
if (desktop == L"GNOME" || desktop.empty())
{
args.push_back ("--no-default-window");
args.push_back ("--no-desktop");
args.push_back (string (path));
try
{
Process::Execute ("nautilus", args, 2000);
}
catch (TimeOut&) { }
catch (exception &e) { ShowError (e); }
}
else if (desktop == L"KDE")
{
try
{
args.push_back (string (path));
Process::Execute ("dolphin", args, 2000);
}
catch (TimeOut&) { }
catch (exception&)
{
args.clear();
args.push_back ("openURL");
args.push_back (string (path));
try
{
Process::Execute ("kfmclient", args, 2000);
}
catch (TimeOut&) { }
catch (exception &e) { ShowError (e); }
}
}
#endif
}
bool UserInterface::ProcessCommandLine ()
{
CommandLineInterface &cmdLine = *CmdLine;
switch (cmdLine.ArgCommand)
{
case CommandId::None:
return false;
case CommandId::AutoMountDevices:
case CommandId::AutoMountFavorites:
case CommandId::AutoMountDevicesFavorites:
case CommandId::MountVolume:
{
cmdLine.ArgMountOptions.Path = cmdLine.ArgVolumePath;
cmdLine.ArgMountOptions.MountPoint = cmdLine.ArgMountPoint;
cmdLine.ArgMountOptions.Password = cmdLine.ArgPassword;
cmdLine.ArgMountOptions.Keyfiles = cmdLine.ArgKeyfiles;
cmdLine.ArgMountOptions.SharedAccessAllowed = cmdLine.ArgForce;
VolumeInfoList mountedVolumes;
switch (cmdLine.ArgCommand)
{
case CommandId::AutoMountDevices:
case CommandId::AutoMountFavorites:
case CommandId::AutoMountDevicesFavorites:
{
if (cmdLine.ArgCommand == CommandId::AutoMountDevices || cmdLine.ArgCommand == CommandId::AutoMountDevicesFavorites)
{
if (Preferences.NonInteractive)
mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (cmdLine.ArgMountOptions);
else
mountedVolumes = MountAllDeviceHostedVolumes (cmdLine.ArgMountOptions);
}
if (cmdLine.ArgCommand == CommandId::AutoMountFavorites || cmdLine.ArgCommand == CommandId::AutoMountDevicesFavorites)
{
foreach (shared_ptr <VolumeInfo> v, MountAllFavoriteVolumes(cmdLine.ArgMountOptions))
mountedVolumes.push_back (v);
}
}
break;
break;
case CommandId::MountVolume:
if (Preferences.OpenExplorerWindowAfterMount)
{
// Open explorer window for an already mounted volume
shared_ptr <VolumeInfo> mountedVolume = Core->GetMountedVolume (*cmdLine.ArgMountOptions.Path);
if (mountedVolume && !mountedVolume->MountPoint.IsEmpty())
{
OpenExplorerWindow (mountedVolume->MountPoint);
break;
}
}
if (Preferences.NonInteractive)
{
// Volume path
if (!cmdLine.ArgMountOptions.Path)
throw MissingArgument (SRC_POS);
mountedVolumes.push_back (Core->MountVolume (cmdLine.ArgMountOptions));
}
else
{
shared_ptr <VolumeInfo> volume = MountVolume (cmdLine.ArgMountOptions);
if (!volume)
{
Application::SetExitCode (1);
throw UserAbort (SRC_POS);
}
mountedVolumes.push_back (volume);
}
break;
default:
throw ParameterIncorrect (SRC_POS);
}
if (Preferences.Verbose && !mountedVolumes.empty())
{
wxString message;
foreach_ref (const VolumeInfo &volume, mountedVolumes)
{
if (!message.IsEmpty())
message += L'\n';
message += StringFormatter (_("Volume \"{0}\" has been mounted."), wstring (volume.Path));
}
ShowInfo (message);
}
}
return true;
case CommandId::BackupHeaders:
BackupVolumeHeaders (cmdLine.ArgVolumePath);
return true;
case CommandId::ChangePassword:
ChangePassword (cmdLine.ArgVolumePath, cmdLine.ArgPassword, cmdLine.ArgKeyfiles, cmdLine.ArgNewPassword, cmdLine.ArgNewKeyfiles, cmdLine.ArgHash);
return true;
case CommandId::CreateKeyfile:
CreateKeyfile (cmdLine.ArgFilePath);
return true;
case CommandId::CreateVolume:
{
make_shared_auto (VolumeCreationOptions, options);
if (cmdLine.ArgHash)
{
options->VolumeHeaderKdf = Pkcs5Kdf::GetAlgorithm (*cmdLine.ArgHash);
RandomNumberGenerator::SetHash (cmdLine.ArgHash);
}
options->EA = cmdLine.ArgEncryptionAlgorithm;
options->Filesystem = cmdLine.ArgFilesystem;
options->Keyfiles = cmdLine.ArgKeyfiles;
options->Password = cmdLine.ArgPassword;
options->Quick = cmdLine.ArgQuick;
options->Size = cmdLine.ArgSize;
options->Type = cmdLine.ArgVolumeType;
if (cmdLine.ArgVolumePath)
options->Path = VolumePath (*cmdLine.ArgVolumePath);
CreateVolume (options);
return true;
}
case CommandId::DeleteSecurityTokenKeyfiles: