forked from FreeApophis/TrueCrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphicUserInterface.cpp
1691 lines (1405 loc) · 42.9 KB
/
GraphicUserInterface.cpp
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-2009 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"
#ifdef TC_UNIX
#include <wx/mimetype.h>
#include <wx/sckipc.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include "Platform/Unix/Process.h"
#endif
#include "Common/SecurityToken.h"
#include "Application.h"
#include "GraphicUserInterface.h"
#include "FatalErrorHandler.h"
#include "Forms/DeviceSelectionDialog.h"
#include "Forms/KeyfileGeneratorDialog.h"
#include "Forms/MainFrame.h"
#include "Forms/MountOptionsDialog.h"
#include "Forms/RandomPoolEnrichmentDialog.h"
#include "Forms/SecurityTokenKeyfilesDialog.h"
namespace TrueCrypt
{
GraphicUserInterface::GraphicUserInterface () :
ActiveFrame (nullptr),
BackgroundMode (false),
mMainFrame (nullptr)
{
#ifdef TC_UNIX
signal (SIGHUP, OnSignal);
signal (SIGINT, OnSignal);
signal (SIGQUIT, OnSignal);
signal (SIGTERM, OnSignal);
#endif
#ifdef TC_MACOSX
wxApp::s_macHelpMenuTitleName = _("&Help");
#endif
}
GraphicUserInterface::~GraphicUserInterface ()
{
try
{
if (RandomNumberGenerator::IsRunning())
RandomNumberGenerator::Stop();
}
catch (...) { }
FatalErrorHandler::Deregister();
#ifdef TC_UNIX
signal (SIGHUP, SIG_DFL);
signal (SIGINT, SIG_DFL);
signal (SIGQUIT, SIG_DFL);
signal (SIGTERM, SIG_DFL);
#endif
}
void GraphicUserInterface::AppendToListCtrl (wxListCtrl *listCtrl, const vector <wstring> &itemFields, int imageIndex, void *itemDataPtr) const
{
InsertToListCtrl (listCtrl, listCtrl->GetItemCount(), itemFields, imageIndex, itemDataPtr);
}
wxMenuItem *GraphicUserInterface::AppendToMenu (wxMenu &menu, const wxString &label, wxEvtHandler *handler, wxObjectEventFunction handlerFunction, int itemId) const
{
wxMenuItem *item = new wxMenuItem (&menu, itemId, label);
menu.Append (item);
if (handler)
handler->Connect (item->GetId(), wxEVT_COMMAND_MENU_SELECTED, handlerFunction);
return item;
}
bool GraphicUserInterface::AskYesNo (const wxString &message, bool defaultYes, bool warning) const
{
return ShowMessage (message,
wxYES_NO | (warning ? wxICON_EXCLAMATION : wxICON_QUESTION) | (defaultYes ? wxYES_DEFAULT : wxNO_DEFAULT)
) == wxYES;
}
void GraphicUserInterface::AutoDismountVolumes (VolumeInfoList mountedVolumes, bool alwaysForce)
{
size_t mountedVolumeCount = Core->GetMountedVolumes().size();
try
{
wxBusyCursor busy;
DismountVolumes (mountedVolumes, alwaysForce ? true : GetPreferences().ForceAutoDismount, false);
}
catch (...) { }
if (Core->GetMountedVolumes().size() < mountedVolumeCount)
OnVolumesAutoDismounted();
}
void GraphicUserInterface::BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const
{
wxWindow *parent = GetActiveWindow();
if (!volumePath || volumePath->IsEmpty())
volumePath = make_shared <VolumePath> (SelectVolumeFile (GetActiveWindow()));
if (volumePath->IsEmpty())
throw UserAbort (SRC_POS);
#ifdef TC_WINDOWS
if (Core->IsVolumeMounted (*volumePath))
{
ShowInfo ("DISMOUNT_FIRST");
return;
}
#endif
#ifdef TC_UNIX
// Temporarily take ownership of a device if the user is not an administrator
UserId origDeviceOwner ((uid_t) -1);
if (!Core->HasAdminPrivileges() && volumePath->IsDevice())
{
origDeviceOwner = FilesystemPath (wstring (*volumePath)).GetOwner();
Core->SetFileOwner (*volumePath, UserId (getuid()));
}
finally_do_arg2 (FilesystemPath, *volumePath, UserId, origDeviceOwner,
{
if (finally_arg2.SystemId != (uid_t) -1)
Core->SetFileOwner (finally_arg, finally_arg2);
});
#endif
ShowInfo ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO");
shared_ptr <Volume> normalVolume;
shared_ptr <Volume> hiddenVolume;
MountOptions normalVolumeMountOptions;
MountOptions hiddenVolumeMountOptions;
normalVolumeMountOptions.Path = volumePath;
hiddenVolumeMountOptions.Path = volumePath;
VolumeType::Enum volumeType = VolumeType::Normal;
// Open both types of volumes
while (true)
{
shared_ptr <Volume> volume;
MountOptions *options = (volumeType == VolumeType::Hidden ? &hiddenVolumeMountOptions : &normalVolumeMountOptions);
MountOptionsDialog dialog (parent, *options,
LangString[volumeType == VolumeType::Hidden ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD"],
true);
while (!volume)
{
dialog.Hide();
if (dialog.ShowModal() != wxID_OK)
return;
try
{
wxBusyCursor busy;
volume = Core->OpenVolume (
options->Path,
options->PreserveTimestamps,
options->Password,
options->Keyfiles,
options->Protection,
options->ProtectionPassword,
options->ProtectionKeyfiles,
true,
volumeType,
options->UseBackupHeaders
);
}
catch (PasswordException &e)
{
ShowWarning (e);
}
}
if (volumeType == VolumeType::Hidden)
hiddenVolume = volume;
else
normalVolume = volume;
// Ask whether a hidden volume is present
if (volumeType == VolumeType::Normal)
{
wxArrayString choices;
choices.Add (LangString["VOLUME_CONTAINS_HIDDEN"]);
choices.Add (LangString["VOLUME_DOES_NOT_CONTAIN_HIDDEN"]);
wxSingleChoiceDialog choiceDialog (parent, LangString["DOES_VOLUME_CONTAIN_HIDDEN"], Application::GetName(), choices);
choiceDialog.SetSize (wxSize (Gui->GetCharWidth (&choiceDialog) * 60, -1));
choiceDialog.SetSelection (-1);
if (choiceDialog.ShowModal() != wxID_OK)
return;
switch (choiceDialog.GetSelection())
{
case 0:
volumeType = VolumeType::Hidden;
continue;
case 1:
break;
default:
return;
}
}
break;
}
if (hiddenVolume)
{
if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV1Normal) && typeid (*hiddenVolume->GetLayout()) != typeid (VolumeLayoutV1Hidden))
throw ParameterIncorrect (SRC_POS);
if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV2Normal) && typeid (*hiddenVolume->GetLayout()) != typeid (VolumeLayoutV2Hidden))
throw ParameterIncorrect (SRC_POS);
}
// Ask user to select backup file path
wxString confirmMsg = LangString["CONFIRM_VOL_HEADER_BAK"];
confirmMsg.Replace (L"%hs", L"%s");
if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true))
return;
FilePathList files = SelectFiles (parent, wxEmptyString, true, false);
if (files.empty())
return;
File backupFile;
backupFile.Open (*files.front(), File::CreateWrite);
RandomNumberGenerator::Start();
UserEnrichRandomPool (nullptr);
{
wxBusyCursor busy;
// Re-encrypt volume header
SecureBuffer newHeaderBuffer (normalVolume->GetLayout()->GetHeaderSize());
Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, normalVolume->GetHeader(), normalVolumeMountOptions.Password, normalVolumeMountOptions.Keyfiles);
backupFile.Write (newHeaderBuffer);
if (hiddenVolume)
{
// Re-encrypt hidden volume header
Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, hiddenVolume->GetHeader(), hiddenVolumeMountOptions.Password, hiddenVolumeMountOptions.Keyfiles);
}
else
{
// Store random data in place of hidden volume header
shared_ptr <EncryptionAlgorithm> ea = normalVolume->GetEncryptionAlgorithm();
Core->RandomizeEncryptionAlgorithmKey (ea);
ea->Encrypt (newHeaderBuffer);
}
backupFile.Write (newHeaderBuffer);
}
ShowWarning ("VOL_HEADER_BACKED_UP");
}
void GraphicUserInterface::BeginInteractiveBusyState (wxWindow *window)
{
static auto_ptr <wxCursor> arrowWaitCursor;
if (arrowWaitCursor.get() == nullptr)
arrowWaitCursor.reset (new wxCursor (wxCURSOR_ARROWWAIT));
window->SetCursor (*arrowWaitCursor);
}
void GraphicUserInterface::CreateKeyfile (shared_ptr <FilePath> keyfilePath) const
{
try
{
KeyfileGeneratorDialog dialog (GetActiveWindow());
dialog.ShowModal();
}
catch (exception &e)
{
ShowError (e);
}
}
void GraphicUserInterface::ClearListCtrlSelection (wxListCtrl *listCtrl) const
{
foreach (long item, GetListCtrlSelectedItems (listCtrl))
listCtrl->SetItemState (item, 0, wxLIST_STATE_SELECTED);
}
wxHyperlinkCtrl *GraphicUserInterface::CreateHyperlink (wxWindow *parent, const wxString &linkUrl, const wxString &linkText) const
{
wxHyperlinkCtrl *hyperlink = new wxHyperlinkCtrl (parent, wxID_ANY, linkText, linkUrl, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE);
wxColour color = wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT);
hyperlink->SetHoverColour (color);
hyperlink->SetNormalColour (color);
hyperlink->SetVisitedColour (color);
return hyperlink;
}
void GraphicUserInterface::DoShowError (const wxString &message) const
{
ShowMessage (message, wxOK | wxICON_ERROR);
}
void GraphicUserInterface::DoShowInfo (const wxString &message) const
{
ShowMessage (message, wxOK | wxICON_INFORMATION);
}
void GraphicUserInterface::DoShowString (const wxString &str) const
{
ShowMessage (str, wxOK);
}
void GraphicUserInterface::DoShowWarning (const wxString &message) const
{
ShowMessage (message, wxOK
#ifndef TC_MACOSX
| wxICON_EXCLAMATION
#endif
);
}
void GraphicUserInterface::EndInteractiveBusyState (wxWindow *window) const
{
static auto_ptr <wxCursor> arrowCursor;
if (arrowCursor.get() == nullptr)
arrowCursor.reset (new wxCursor (wxCURSOR_ARROW));
window->SetCursor (*arrowCursor);
}
wxTopLevelWindow *GraphicUserInterface::GetActiveWindow () const
{
#ifdef TC_WINDOWS
return dynamic_cast <wxTopLevelWindow *> (wxGetActiveWindow());
#endif
#ifdef __WXGTK__
// GTK for some reason unhides a hidden window if it is a parent of a new window
if (IsInBackgroundMode())
return nullptr;
#endif
if (wxTopLevelWindows.size() == 1)
return dynamic_cast <wxTopLevelWindow *> (wxTopLevelWindows.front());
#ifdef __WXGTK__
wxLongLong startTime = wxGetLocalTimeMillis();
do
{
#endif
foreach (wxWindow *window, wxTopLevelWindows)
{
wxTopLevelWindow *topLevelWin = dynamic_cast <wxTopLevelWindow *> (window);
if (topLevelWin && topLevelWin->IsActive() && topLevelWin->IsShown())
return topLevelWin;
}
#ifdef __WXGTK__
Yield(); // GTK does a lot of operations asynchronously, which makes it prone to many race conditions
} while (wxGetLocalTimeMillis() - startTime < 500);
#endif
return dynamic_cast <wxTopLevelWindow *> (ActiveFrame ? ActiveFrame : GetTopWindow());
}
shared_ptr <GetStringFunctor> GraphicUserInterface::GetAdminPasswordRequestHandler ()
{
struct AdminPasswordRequestHandler : public GetStringFunctor
{
virtual void operator() (string &passwordStr)
{
wxPasswordEntryDialog dialog (Gui->GetActiveWindow(), _("Enter your user password or administrator password:"), _("Administrator privileges required"));
if (dialog.ShowModal() != wxID_OK)
throw UserAbort (SRC_POS);
wstring wPassword (dialog.GetValue()); // A copy of the password is created here by wxWidgets, which cannot be erased
finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });
StringConverter::ToSingle (wPassword, passwordStr);
}
};
return shared_ptr <GetStringFunctor> (new AdminPasswordRequestHandler);
}
int GraphicUserInterface::GetCharHeight (wxWindow *window) const
{
int width;
int height;
window->GetTextExtent (L"a", &width, &height);
if (height < 1)
return 14;
return height;
}
int GraphicUserInterface::GetCharWidth (wxWindow *window) const
{
int width;
int height;
window->GetTextExtent (L"a", &width, &height);
if (width < 1)
return 7;
return width;
}
wxFont GraphicUserInterface::GetDefaultBoldFont (wxWindow *window) const
{
return wxFont (
#ifdef __WXGTK__
9
#elif defined(TC_MACOSX)
13
#else
10
#endif
* GetCharHeight (window) / 13, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
#ifdef __WXGTK__
wxFONTWEIGHT_BOLD, false);
#elif defined(TC_MACOSX)
wxFONTWEIGHT_NORMAL, false);
#else
wxFONTWEIGHT_BOLD, false, L"Arial");
#endif
}
list <long> GraphicUserInterface::GetListCtrlSelectedItems (wxListCtrl *listCtrl) const
{
list <long> selectedItems;
long item = -1;
while ((item = listCtrl->GetNextItem (item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)) != -1)
selectedItems.push_back (item);
return selectedItems;
}
wxString GraphicUserInterface::GetListCtrlSubItemText (wxListCtrl *listCtrl, long itemIndex, int columnIndex) const
{
wxListItem item;
item.SetId (itemIndex);
item.SetColumn (columnIndex);
item.SetText (L"");
if (!listCtrl->GetItem (item))
throw ParameterIncorrect (SRC_POS);
return item.GetText();
}
int GraphicUserInterface::GetScrollbarWidth (wxWindow *window, bool noScrollBar) const
{
int offset = 0;
#ifdef TC_WINDOWS
offset = 4;
#elif defined (__WXGTK__)
offset = 7;
#elif defined (TC_MACOSX)
offset = 9;
#endif
if (noScrollBar)
return offset;
int width = wxSystemSettings::GetMetric (wxSYS_VSCROLL_X, window);
if (width == -1)
return 24;
return width + offset;
}
void GraphicUserInterface::InitSecurityTokenLibrary () const
{
if (Preferences.SecurityTokenModule.IsEmpty())
throw_err (LangString ["NO_PKCS11_MODULE_SPECIFIED"]);
struct PinRequestHandler : public GetPinFunctor
{
virtual void operator() (string &passwordStr)
{
if (Gui->GetPreferences().NonInteractive)
throw MissingArgument (SRC_POS);
wxPasswordEntryDialog dialog (Gui->GetActiveWindow(), wxString::Format (LangString["ENTER_TOKEN_PASSWORD"], StringConverter::ToWide (passwordStr).c_str()), LangString["IDD_TOKEN_PASSWORD"]);
dialog.SetSize (wxSize (Gui->GetCharWidth (&dialog) * 50, -1));
if (dialog.ShowModal() != wxID_OK)
throw UserAbort (SRC_POS);
wstring wPassword (dialog.GetValue()); // A copy of the password is created here by wxWidgets, which cannot be erased
finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });
StringConverter::ToSingle (wPassword, passwordStr);
}
};
struct WarningHandler : public SendExceptionFunctor
{
virtual void operator() (const Exception &e)
{
Gui->ShowError (e);
}
};
try
{
SecurityToken::InitLibrary (Preferences.SecurityTokenModule, auto_ptr <GetPinFunctor> (new PinRequestHandler), auto_ptr <SendExceptionFunctor> (new WarningHandler));
}
catch (Exception &e)
{
ShowError (e);
throw_err (LangString ["PKCS11_MODULE_INIT_FAILED"]);
}
}
void GraphicUserInterface::InsertToListCtrl (wxListCtrl *listCtrl, long itemIndex, const vector <wstring> &itemFields, int imageIndex, void *itemDataPtr) const
{
wxListItem item;
item.SetData (itemDataPtr);
item.SetId (itemIndex);
item.SetImage (imageIndex);
int col = 0;
foreach (wxString field, itemFields)
{
item.SetColumn (col++);
item.SetText (field);
if (col == 1)
{
throw_sys_if (listCtrl->InsertItem (item) == -1);
item.SetImage (-1);
continue;
}
listCtrl->SetItem (item);
}
}
bool GraphicUserInterface::IsTheOnlyTopLevelWindow (const wxWindow *window) const
{
foreach (wxWindow *w, wxTopLevelWindows)
{
if (w != window
&& (dynamic_cast <const wxFrame *> (w) || dynamic_cast <const wxDialog *> (w))
&& StringConverter::GetTypeName (typeid (*w)).find ("wxTaskBarIcon") == string::npos)
{
return false;
}
}
return true;
}
void GraphicUserInterface::ListSecurityTokenKeyfiles () const
{
SecurityTokenKeyfilesDialog dialog (nullptr);
dialog.ShowModal();
}
#ifdef TC_MACOSX
void GraphicUserInterface::MacOpenFile (const wxString &fileName)
{
OpenVolumeSystemRequestEventArgs eventArgs (fileName);
OpenVolumeSystemRequestEvent.Raise (eventArgs);
}
#endif
void GraphicUserInterface::MoveListCtrlItem (wxListCtrl *listCtrl, long itemIndex, long newItemIndex) const
{
if (itemIndex == newItemIndex || newItemIndex < 0
|| (newItemIndex > itemIndex && newItemIndex == listCtrl->GetItemCount()))
return;
wxListItem item;
item.SetId (itemIndex);
item.SetData ((void *) nullptr);
item.SetImage (-1);
if (!listCtrl->GetItem (item))
throw ParameterIncorrect (SRC_POS);
int itemState = listCtrl->GetItemState (itemIndex, wxLIST_STATE_SELECTED);
vector <wstring> itemFields (listCtrl->GetColumnCount());
for (size_t col = 0; col < itemFields.size(); ++col)
{
itemFields[col] = GetListCtrlSubItemText (listCtrl, itemIndex, col);
}
listCtrl->DeleteItem (itemIndex);
if (newItemIndex > listCtrl->GetItemCount() - 1)
AppendToListCtrl (listCtrl, itemFields, item.GetImage(), (void *) item.GetData());
else
InsertToListCtrl (listCtrl, newItemIndex, itemFields, item.GetImage(), (void *) item.GetData());
item.SetId (newItemIndex);
listCtrl->SetItemState (item, itemState, wxLIST_STATE_SELECTED);
}
VolumeInfoList GraphicUserInterface::MountAllDeviceHostedVolumes (MountOptions &options) const
{
MountOptionsDialog dialog (GetTopWindow(), options);
while (true)
{
options.Path.reset();
if (dialog.ShowModal() != wxID_OK)
return VolumeInfoList();
VolumeInfoList mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (options);
if (!mountedVolumes.empty())
return mountedVolumes;
}
}
shared_ptr <VolumeInfo> GraphicUserInterface::MountVolume (MountOptions &options) const
{
CheckRequirementsForMountingVolume();
shared_ptr <VolumeInfo> volume;
if (!options.Path || options.Path->IsEmpty())
options.Path = make_shared <VolumePath> (SelectVolumeFile (GetActiveWindow()));
if (options.Path->IsEmpty())
throw UserAbort (SRC_POS);
if (Core->IsVolumeMounted (*options.Path))
{
ShowInfo (StringFormatter (LangString["VOLUME_ALREADY_MOUNTED"], wstring (*options.Path)));
return volume;
}
try
{
if ((!options.Password || options.Password->IsEmpty())
&& (!options.Keyfiles || options.Keyfiles->empty())
&& !Core->IsPasswordCacheEmpty())
{
// Cached password
try
{
wxBusyCursor busy;
return UserInterface::MountVolume (options);
}
catch (PasswordException&) { }
}
if (!options.Keyfiles && GetPreferences().UseKeyfiles && !GetPreferences().DefaultKeyfiles.empty())
options.Keyfiles = make_shared <KeyfileList> (GetPreferences().DefaultKeyfiles);
if ((options.Password && !options.Password->IsEmpty())
|| (options.Keyfiles && !options.Keyfiles->empty()))
{
try
{
wxBusyCursor busy;
return UserInterface::MountVolume (options);
}
catch (PasswordException&) { }
}
VolumePassword password;
KeyfileList keyfiles;
MountOptionsDialog dialog (GetTopWindow(), options);
int incorrectPasswordCount = 0;
while (!volume)
{
dialog.Hide();
if (dialog.ShowModal() != wxID_OK)
return volume;
try
{
wxBusyCursor busy;
volume = UserInterface::MountVolume (options);
}
catch (PasswordIncorrect &e)
{
if (++incorrectPasswordCount > 2 && !options.UseBackupHeaders)
{
// Try to mount the volume using the backup header
options.UseBackupHeaders = true;
try
{
volume = UserInterface::MountVolume (options);
ShowWarning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
}
catch (...)
{
options.UseBackupHeaders = false;
ShowWarning (e);
}
}
else
ShowWarning (e);
}
catch (PasswordException &e)
{
ShowWarning (e);
}
}
}
catch (exception &e)
{
ShowError (e);
}
#ifdef TC_LINUX
if (volume && !Preferences.NonInteractive && !Preferences.DisableKernelEncryptionModeWarning
&& volume->EncryptionModeName != L"XTS"
&& (volume->EncryptionModeName != L"LRW" || volume->EncryptionAlgorithmMinBlockSize != 16 || volume->EncryptionAlgorithmKeySize != 32)
&& !AskYesNo (LangString["ENCRYPTION_MODE_NOT_SUPPORTED_BY_KERNEL"] + _("\n\nDo you want to show this message next time you mount such a volume?"), true, true))
{
UserPreferences prefs = GetPreferences();
prefs.DisableKernelEncryptionModeWarning = true;
Gui->SetPreferences (prefs);
}
#endif
return volume;
}
void GraphicUserInterface::OnAutoDismountAllEvent ()
{
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
if (!mountedVolumes.empty())
{
wxBusyCursor busy;
AutoDismountVolumes (mountedVolumes);
}
}
bool GraphicUserInterface::OnInit ()
{
Gui = this;
InterfaceType = UserInterfaceType::Graphic;
try
{
FatalErrorHandler::Register();
Init();
if (ProcessCommandLine() && !CmdLine->StartBackgroundTask)
{
Yield();
Application::SetExitCode (0);
return false;
}
// Check if another instance is already running and bring its windows to foreground
#ifndef TC_MACOSX
#ifdef TC_WINDOWS
const wxString serverName = Application::GetName() + L"-" + wxGetUserId();
class Connection : public wxDDEConnection
{
public:
Connection () { }
bool OnExecute (const wxString& topic, wxChar *data, int size, wxIPCFormat format)
{
if (topic == L"raise")
{
if (Gui->IsInBackgroundMode())
Gui->SetBackgroundMode (false);
Gui->mMainFrame->Show (true);
Gui->mMainFrame->Raise ();
return true;
}
return false;
}
};
#endif
wxLogLevel logLevel = wxLog::GetLogLevel();
wxLog::SetLogLevel (wxLOG_Error);
SingleInstanceChecker.reset (new wxSingleInstanceChecker (wxString (L".") + Application::GetName() + L"-lock-" + wxGetUserId()));
wxLog::SetLogLevel (logLevel);
if (SingleInstanceChecker->IsAnotherRunning())
{
#ifdef TC_WINDOWS
class Client: public wxDDEClient
{
public:
Client() {};
wxConnectionBase *OnMakeConnection () { return new Connection; }
};
auto_ptr <wxDDEClient> client (new Client);
auto_ptr <wxConnectionBase> connection (client->MakeConnection (L"localhost", serverName, L"raise"));
if (connection.get() && connection->Execute (nullptr))
{
connection->Disconnect();
Application::SetExitCode (0);
return false;
}
#endif
#if defined(TC_UNIX) && !defined(TC_MACOSX)
try
{
int showFifo = open (string (MainFrame::GetShowRequestFifoPath()).c_str(), O_WRONLY | O_NONBLOCK);
throw_sys_if (showFifo == -1);
byte buf[1] = { 1 };
if (write (showFifo, buf, 1) == 1)
{
close (showFifo);
Application::SetExitCode (0);
return false;
}
close (showFifo);
}
catch (...)
{
#ifdef DEBUG
throw;
#endif
}
#endif
wxLog::FlushActive();
Application::SetExitCode (1);
Gui->ShowInfo (_("TrueCrypt is already running."));
return false;
}
#ifdef TC_WINDOWS
class Server : public wxDDEServer
{
public:
wxConnectionBase *OnAcceptConnection (const wxString &topic)
{
if (topic == L"raise")
return new Connection;
return nullptr;
}
};
DDEServer.reset (new Server);
if (!DDEServer->Create (serverName))
wxLog::FlushActive();
#endif
#endif // !TC_MACOSX
Connect (wxEVT_END_SESSION, wxCloseEventHandler (GraphicUserInterface::OnEndSession));
#ifdef wxHAS_POWER_EVENTS
Gui->Connect (wxEVT_POWER_SUSPENDING, wxPowerEventHandler (GraphicUserInterface::OnPowerSuspending));
#endif
mMainFrame = new MainFrame (nullptr);
if (CmdLine->StartBackgroundTask)
{
UserPreferences prefs = GetPreferences ();
prefs.BackgroundTaskEnabled = true;
SetPreferences (prefs);
mMainFrame->Close();
}
else
{
mMainFrame->Show (true);
}
SetTopWindow (mMainFrame);
}
catch (exception &e)
{
ShowError (e);
return false;
}
return true;
}
void GraphicUserInterface::OnLogOff ()
{
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
if (GetPreferences().BackgroundTaskEnabled && GetPreferences().DismountOnLogOff
&& !mountedVolumes.empty())
{
wxLongLong startTime = wxGetLocalTimeMillis();
bool timeOver = false;
wxBusyCursor busy;
while (!timeOver && !mountedVolumes.empty())
{
try
{
timeOver = (wxGetLocalTimeMillis() - startTime >= 4000);
DismountVolumes (mountedVolumes, !timeOver ? false : GetPreferences().ForceAutoDismount, timeOver);
OnVolumesAutoDismounted();
break;
}
catch (UserAbort&)
{
return;
}
catch (...)
{
Thread::Sleep (500);
}
VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
}
}
}
#ifdef wxHAS_POWER_EVENTS
void GraphicUserInterface::OnPowerSuspending (wxPowerEvent& event)
{
size_t volumeCount = Core->GetMountedVolumes().size();
if (GetPreferences().BackgroundTaskEnabled && GetPreferences().DismountOnPowerSaving && volumeCount > 0)
{
OnAutoDismountAllEvent();
if (Core->GetMountedVolumes().size() < volumeCount)
ShowInfoTopMost (LangString["MOUNTED_VOLUMES_AUTO_DISMOUNTED"]);
}
}
#endif
void GraphicUserInterface::OnSignal (int signal)
{
#ifdef TC_UNIX
Gui->SingleInstanceChecker.reset();
_exit (1);
#endif
}
void GraphicUserInterface::OnVolumesAutoDismounted ()
{
if (GetPreferences().WipeCacheOnAutoDismount)
{
Core->WipePasswordCache();
SecurityToken::CloseAllSessions();
}
}
void GraphicUserInterface::OpenDocument (wxWindow *parent, const wxFileName &document)
{
if (!document.FileExists())
throw ParameterIncorrect (SRC_POS);
#ifdef TC_WINDOWS
if (int (ShellExecute (GetTopWindow() ? static_cast <HWND> (GetTopWindow()->GetHandle()) : nullptr, L"open",
document.GetFullPath().c_str(), nullptr, nullptr, SW_SHOWNORMAL)) >= 32)
return;
#else
wxMimeTypesManager mimeMgr;
wxFileType *fileType = mimeMgr.GetFileTypeFromExtension (document.GetExt());
if (fileType)
{
try
{
#ifdef TC_MACOSX