[36e306]: ThisMfcApp.cpp  Maximize  Restore  History

Download this file

1150 lines (989 with data), 35.2 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
/*
* Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license.php
*/
/// \file ThisMfcApp.cpp
/// \brief App object of MFC version of Password Safe
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "corelib/PWSrand.h"
#include "corelib/PWSdirs.h"
#include "corelib/sha256.h"
#include "corelib/sha1.h"
#include "corelib/SysInfo.h"
#if defined(POCKET_PC)
#include "pocketpc/PocketPC.h"
#include "pocketpc/resource.h"
#else
#include <errno.h>
#include <io.h>
#include "resource.h"
#include "resource2.h" // Menu, Toolbar & Accelerator resources
#include "resource3.h" // String resources
#endif
#include "ThisMfcApp.h"
#include "corelib/Util.h"
#include "corelib/BlowFish.h"
#include "DboxMain.h"
#include "CryptKeyEntry.h"
#include "PWSRecentFileList.h"
#include "corelib/PWSprefs.h"
#include "Shlwapi.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
BEGIN_MESSAGE_MAP(ThisMfcApp, CWinApp)
// ON_COMMAND(ID_HELP, CWinApp::OnHelp)
ON_COMMAND(ID_HELP, OnHelp)
END_MESSAGE_MAP()
// Need it outside as everyone needs it!
CLIPFORMAT gbl_ccddCPFID;
DWORD gbl_randID;
ThisMfcApp::ThisMfcApp() :
#if defined(POCKET_PC)
m_bUseAccelerator( false ),
#else
m_bUseAccelerator( true ),
#endif
m_pMRU( NULL ), m_TrayLockedState(LOCKED), m_TrayIcon(NULL),
m_HotKeyPressed(false)
{
// {kjp} Temporary until I'm sure that PwsPlatform.h configures the endianness properly
#if defined(POCKET_PC)
// Double check that *_ENDIAN has been correctly set!
#if defined(PWS_LITTLE_ENDIAN)
unsigned char buf[4] = { 1, 0, 0, 0 };
unsigned int ii = 1;
#define ENDIANNESS1 0 // Little
#define ENDIANNESS2 1 // Big
#elif defined(PWS_BIG_ENDIAN)
unsigned char buf[4] = { 0, 0, 0, 1 };
unsigned int ii = 1;
#define ENDIANNESS1 1 // Big
#define ENDIANNESS2 0 // Little
#endif
if (*(unsigned int*)buf != ii) {
CString cs_msg, cs_e1, cs_e2;
cs_e1.LoadString(ENDIANNESS1 == 0 ? IDS_LITTLEENDIAN : IDS_BIGENDIAN);
cs_e2.LoadString(ENDIANNESS2 == 0 ? IDS_LITTLEENDIAN : IDS_BIGENDIAN);
cs_msg.Format(IDS_ENDIANERROR, cs_e1, cs_e2);
AfxMessageBox(cs_msg);
}
#endif
EnableHtmlHelp();
CoInitialize(NULL); // Initializes the COM library (for XML processing)
AfxOleInit();
}
ThisMfcApp::~ThisMfcApp()
{
delete m_TrayIcon;
delete m_pMRU;
delete m_mainmenu;
PWSprefs::DeleteInstance();
PWSrand::DeleteInstance();
CoUninitialize(); // Uninitialize COM library
#if !defined(POCKET_PC)
// WinApp::HtmlHelp asserts that main windows is valid, which (1) isn't true
// here, and (2) is irrelevant for HH_CLOSE_ALL, so we call ::HtmlHelp
::HtmlHelp(NULL, NULL, HH_CLOSE_ALL, 0);
#endif
}
#if !defined(POCKET_PC)
static void Usage()
{
AfxMessageBox(IDS_USAGE);
}
// tests if file exists, returns empty string if so, displays error message if not
static BOOL CheckFile(const CString &fn)
{
DWORD status = ::GetFileAttributes(fn);
CString cs_msg(_T(""));
if (status == -1) {
cs_msg.Format(IDS_FILEERROR1, fn);
} else if (status & FILE_ATTRIBUTE_DIRECTORY) {
cs_msg.Format(IDS_FILEERROR2, fn);
}
if (cs_msg.IsEmpty()) {
return TRUE;
} else {
AfxMessageBox(cs_msg);
return FALSE;
}
}
//Complain if the file has not opened correctly
static void
ErrorMessages(const CString &fn, FILE *fp)
{
#if !defined(POCKET_PC)
if (fp == NULL) {
CString cs_text1(MAKEINTRESOURCE(IDS_ERRORMESSAGE)), cs_text2;
switch (errno) {
case EACCES:
cs_text2.LoadString(IDS_FILEREADONLY);
break;
case EEXIST:
cs_text2.LoadString(IDS_FILEEXISTS);
break;
case EINVAL:
cs_text2.LoadString(IDS_INVALIDFLAG);
break;
case EMFILE:
cs_text2.LoadString(IDS_NOMOREHANDLES);
break;
case ENOENT:
cs_text2.LoadString(IDS_FILEPATHNOTFOUND);
break;
default:
break;
}
cs_text1 += cs_text2;
cs_text2.LoadString(IDS_TERMINATE);
cs_text1 += cs_text2;
CString cs_title = _T("Password Safe - ") + fn;
AfxGetMainWnd()->MessageBox(cs_text1, cs_title, MB_ICONEXCLAMATION|MB_OK);
}
#endif
}
static BOOL EncryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
FILE *in;
#if _MSC_VER >= 1400
_tfopen_s(&in, fn, _T("rb"));
#else
in = _tfopen(fn, _T("rb"));
#endif
if (in != NULL) {
len = PWSUtil::fileLength(in);
buf = new unsigned char[len];
fread(buf, 1, len, in);
fclose(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
CString out_fn = fn;
out_fn += CIPHERTEXT_SUFFIX;
FILE *out;
#if _MSC_VER >= 1400
_tfopen_s(&out, out_fn, _T("wb"));
#else
out = _tfopen(out_fn, _T("wb"));
#endif
if (out != NULL) {
#ifdef KEEP_FILE_MODE_BWD_COMPAT
fwrite( &len, 1, sizeof(len), out);
#else
unsigned char randstuff[StuffSize];
unsigned char randhash[SHA1::HASHLEN]; // HashSize
PWSrand::GetInstance()->GetRandomData( randstuff, 8 );
// miserable bug - have to fix this way to avoid breaking existing files
randstuff[8] = randstuff[9] = TCHAR('\0');
GenRandhash(passwd,
randstuff,
randhash);
fwrite(randstuff, 1, 8, out);
fwrite(randhash, 1, sizeof(randhash), out);
#endif // KEEP_FILE_MODE_BWD_COMPAT
unsigned char thesalt[SaltLength];
PWSrand::GetInstance()->GetRandomData( thesalt, SaltLength );
fwrite(thesalt, 1, SaltLength, out);
unsigned char ipthing[8];
PWSrand::GetInstance()->GetRandomData( ipthing, 8 );
fwrite(ipthing, 1, 8, out);
LPCTSTR pwd = LPCTSTR(passwd);
Fish *fish = BlowFish::MakeBlowFish((unsigned char *)pwd, passwd.GetLength(),
thesalt, SaltLength);
_writecbc(out, buf, len, (unsigned char)0, fish, ipthing);
delete fish;
fclose(out);
} else {
ErrorMessages(out_fn, out);
delete [] buf;
return FALSE;
}
delete[] buf;
return TRUE;
}
static BOOL DecryptFile(const CString &fn, const CMyString &passwd)
{
unsigned int len;
unsigned char* buf;
FILE *in;
#if _MSC_VER >= 1400
_tfopen_s(&in, fn, _T("rb"));
#else
in = _tfopen(fn, _T("rb"));
#endif
if (in != NULL) {
unsigned char salt[SaltLength];
unsigned char ipthing[8];
unsigned char randstuff[StuffSize];
unsigned char randhash[SHA1::HASHLEN];
#ifdef KEEP_FILE_MODE_BWD_COMPAT
fread(&len, 1, sizeof(len), in); // XXX portability issue
#else
fread(randstuff, 1, 8, in);
randstuff[8] = randstuff[9] = TCHAR('\0'); // ugly bug workaround
fread(randhash, 1, sizeof(randhash), in);
unsigned char temphash[SHA1::HASHLEN];
GenRandhash(passwd,
randstuff,
temphash);
if (0 != memcmp((char*)randhash,
(char*)temphash, SHA1::HASHLEN)) {
fclose(in);
AfxMessageBox(IDS_BADPASSWORD);
return FALSE;
}
#endif // KEEP_FILE_MODE_BWD_COMPAT
buf = NULL; // allocated by _readcbc - see there for apologia
fread(salt, 1, SaltLength, in);
fread(ipthing, 1, 8, in);
LPCTSTR pwd = LPCTSTR(passwd);
unsigned char dummyType;
Fish *fish = BlowFish::MakeBlowFish((unsigned char *)pwd, passwd.GetLength(),
salt, SaltLength);
if (_readcbc(in, buf, len,dummyType, fish, ipthing) == 0) {
delete fish;
delete[] buf; // if not yet allocated, delete[] NULL, which is OK
return FALSE;
}
delete fish;
fclose(in);
} else {
ErrorMessages(fn, in);
return FALSE;
}
size_t suffix_len = strlen(CIPHERTEXT_SUFFIX);
size_t filepath_len = fn.GetLength();
CString out_fn = fn;
out_fn = out_fn.Left(static_cast<int>(filepath_len - suffix_len));
#if _MSC_VER >= 1400
FILE *out;
_tfopen_s(&out, out_fn, _T("wb"));
#else
FILE *out = _tfopen(out_fn, _T("wb"));
#endif
if (out != NULL) {
fwrite(buf, 1, len, out);
fclose(out);
} else
ErrorMessages(out_fn, out);
delete[] buf; // allocated by _readcbc
return TRUE;
}
#endif
int
ThisMfcApp::ExitInstance()
{
if(m_hInstResDLL != NULL)
FreeLibrary(m_hInstResDLL);
CWinApp::ExitInstance();
return 0;
}
// Listener window whose sole purpose in life is to receive
// the "AppStop" message from the U3 framework and then
// cause a semi-graceful exit.
class CLWnd : public CWnd
{
public:
CLWnd(DboxMain &dbox) : m_dbox(dbox) {}
virtual LRESULT WindowProc(UINT message,
WPARAM wParam, LPARAM lParam)
{
if (message != (WM_APP+0x765))
return CWnd::WindowProc(message, wParam, lParam);
else
m_dbox.U3ExitNow();
return 0L;
}
private:
DboxMain &m_dbox;
};
void ThisMfcApp::LoadLocalizedStuff()
{
/*
Looks for localized version of resources and help files, loads them if found
Format of resource-only DLL names (in dir returned by GetExeDir)
pwsafeLL_CC.dll
or
pwsafeLL.dll
where LL = ISO 639-1 two-character Language code e.g. EN, FR, DE, HE...
see http://www.loc.gov/standards/iso639-2/
and CC = ISO 3166-1 two-character Country code e.g. US, GB, FR, CA...
see http://www.iso.org/iso/en/prods-services/iso3166ma/index.html
Although ISO 639 has been superceded, MS only supports the new RFC 3066bis in
.NET V2 and later applications (CultureInfo Class)
or under Vista (via LOCALE_SNAME).
Older native and .NET V1 applications only support the ISO 639-1 two character
language codes.
We will use locale info from ::GetLocaleInfo unless PWS_LANG is defined.
Search order will be pwsafeLL_CC.dll, followed by pwsafeLL.dll. If neither exist or
can't be found, the resources embedded in the executable pwsafe.exe will be used
(US English i.e. equivalent to pwsafeEN_US.dll)).
Likewise, we will look for localized versions of pwsafe.chm in GetHelpDir,
defaulting to pwsafe.chm if not found.
*/
CString cs_PWS_LANG, cs_LANG, cs_CTRY;
BOOL bPLRC = cs_PWS_LANG.GetEnvironmentVariable(_T("PWS_LANG"));
if (bPLRC == TRUE) { // did user override via PWS_LANG env var?
cs_LANG = cs_PWS_LANG;
cs_CTRY = _T("");
} else { // no override, use Locale info
int inum;
TCHAR szLang[4], szCtry[4];
inum = ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME,
szLang, 4);
ASSERT(inum == 3);
_tcsupr(szLang);
TRACE(_T("%s LOCALE_SISO639LANGNAME=%s\n"), PWSUtil::GetTimeStamp(), szLang);
inum = ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
szCtry, 4);
ASSERT(inum == 3);
TRACE(_T("%s LOCALE_SISO3166CTRYNAME=%s\n"), PWSUtil::GetTimeStamp(), szCtry);
cs_LANG = szLang; cs_CTRY = szCtry;
}
const CString cs_ExePath(PWSdirs::GetExeDir());
CString cs_ResPath;
cs_ResPath.Format(_T("%spwsafe%s_%s.dll"), cs_ExePath, cs_LANG, cs_CTRY);
m_hInstResDLL = LoadLibrary(cs_ResPath);
if(m_hInstResDLL == NULL) {
cs_ResPath.Format(_T("%spwsafe%s.dll"), cs_ExePath, cs_LANG);
m_hInstResDLL = LoadLibrary(cs_ResPath);
}
if(m_hInstResDLL == NULL) {
TRACE(_T("%s Could not load language DLLs - using embedded resources.\n"),
PWSUtil::GetTimeStamp());
} else { // successfully loaded a resource dll, check version
CString csResLibInfo(GetVersionInfoFromFile(cs_ResPath));
CString csExeFileInfo(m_csFileVersionString);
if (csExeFileInfo != csResLibInfo) {
TRACE(_T("%s Executable/Resource-Only DLL (%s) version mismatch %s/%s.\n"),
PWSUtil::GetTimeStamp(), cs_ResPath, csExeFileInfo, csResLibInfo);
FreeLibrary(m_hInstResDLL);
m_hInstResDLL = NULL;
} else { // Passed version check
TRACE(_T("%s Using language DLL '%s'.\n"),
PWSUtil::GetTimeStamp(), cs_ResPath);
}
} // end of resource dll hunt
if (m_hInstResDLL != NULL)
AfxSetResourceHandle(m_hInstResDLL);
/**
* So far, we've handle the resource dll. Now go for the compiled helpfile
* in a similar manner.
*/
CString cs_HelpPath;
const CString cs_HelpDir(PWSdirs::GetHelpDir());
bool helpFileFound = false;
CString cs_PWS_HELP;
BOOL bPHRC = cs_PWS_HELP.GetEnvironmentVariable(_T("PWS_HELP"));
if (bPHRC == TRUE) {
cs_HelpPath.Format(_T("%spwsafe%s.chm"), cs_HelpDir, cs_PWS_HELP);
if (PathFileExists(cs_HelpPath)) {
helpFileFound = true;
if (m_pszHelpFilePath != NULL) free((void*)m_pszHelpFilePath);
m_pszHelpFilePath = _tcsdup(cs_HelpPath);
TRACE(_T("%s Help file overriden by user. Using %s.\n"),
PWSUtil::GetTimeStamp(), cs_HelpPath);
}
}
if (!helpFileFound) {
cs_HelpPath.Format(_T("%spwsafe%s_%s.chm"), cs_HelpDir, cs_LANG, cs_CTRY);
if (PathFileExists(cs_HelpPath)) {
helpFileFound = true;
}
}
if (!helpFileFound) {
cs_HelpPath.Format(_T("%spwsafe%s.chm"), cs_HelpDir, cs_LANG);
if (PathFileExists(cs_HelpPath)) {
helpFileFound = true;
}
}
if (!helpFileFound) {
cs_HelpPath.Format(_T("%spwsafe.chm"), cs_HelpDir);
if (PathFileExists(cs_HelpPath)) {
helpFileFound = true;
}
}
if (!helpFileFound) { // last resort
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
#if _MSC_VER >= 1400
_tsplitpath_s( m_pszHelpFilePath, NULL, 0, NULL, 0, fname,
_MAX_FNAME, ext, _MAX_EXT );
_tcslwr_s(fname, _MAX_FNAME);
_tcslwr_s(ext, _MAX_EXT);
#else
_tsplitpath( m_pszHelpFilePath, NULL, NULL, fname, ext );
_tcslwr(ext);
_tcslwr(fname);
#endif
cs_HelpPath.Format(_T("%s%s"), fname, ext);
TRACE(_T("%s Using help file: %s\n"), PWSUtil::GetTimeStamp(), cs_HelpPath);
}
if (m_pszHelpFilePath != NULL)
free((void*)m_pszHelpFilePath);
m_pszHelpFilePath = _tcsdup(cs_HelpPath);
TRACE(_T("%s Using help file: %s\n"), PWSUtil::GetTimeStamp(), cs_HelpPath);
m_csHelpFile = cs_HelpPath;
}
BOOL
ThisMfcApp::InitInstance()
{
/*
* It's always best to start at the beginning. [Glinda, Witch of the North]
*/
// Get application version information
GetApplicationVersionData();
LoadLocalizedStuff();
// PWScore needs it to get into database header if/when saved
m_core.SetApplicationMajorMinor(m_dwMajorMinor);
#if defined(POCKET_PC)
SHInitExtraControls();
#endif
/*
this instructs the app to use the registry instead of .ini files. The
path ends up being
HKEY_CURRENT_USER\Software\(companyname)\(appname)\(sectionname)\(valuename)
where companyname is what's set here, and appname is taken from
AFX_IDS_APP_TITLE (actually, CWinApp::m_pszAppName).
Notes:
1. I would love to move this to corelib/PWSprefs.cpp, but it's a protected
member function.
2. Prior to 3.05, the value was "Counterpane Systems". See PWSprefs.cpp
for discussion on how this is handled.
*/
SetRegistryKey(_T("Password Safe"));
// Register a clipboard format for column darg & drop.
CString cs_CPF(MAKEINTRESOURCE(IDS_CPF_CDD));
gbl_ccddCPFID = 0;
if (OpenClipboard(0)) {
unsigned int uiFormat = 0;
while ((uiFormat = EnumClipboardFormats(uiFormat)) != 0) {
char szName[512];
GetClipboardFormatName(uiFormat, szName, sizeof(szName));
if (cs_CPF.Compare(CString(szName)) == 0) {
gbl_ccddCPFID = (CLIPFORMAT)uiFormat;
break;
}
}
CloseClipboard();
}
if (gbl_ccddCPFID == 0)
gbl_ccddCPFID = (CLIPFORMAT)RegisterClipboardFormat(cs_CPF);
// Create arandom filed to use to check we are only D&D to ourselves
unsigned char randstuff[StuffSize];
PWSrand::GetInstance()->GetRandomData(randstuff, sizeof(DWORD));
memcpy((void *)&gbl_randID, randstuff, sizeof(DWORD));
// MUST (indirectly) create PWSprefs first
// Ensures all things like saving locations etc. are set up.
PWSprefs *prefs = PWSprefs::GetInstance();
CMenu* new_popupmenu = NULL;
int nMRUItems = prefs->GetPref(PWSprefs::MaxMRUItems);
m_mruonfilemenu = prefs->GetPref(PWSprefs::MRUOnFileMenu);
m_clipboard_set = false;
m_mainmenu = new CMenu;
m_mainmenu->LoadMenu(IDR_MAINMENU);
new_popupmenu = new CMenu;
// Look for "File" menu.
CString cs_text(MAKEINTRESOURCE(IDS_FILEMENU));
int pos = FindMenuItem(m_mainmenu, cs_text);
if (pos == -1) // E.g., in non-English versions
pos = 0; // best guess...
CMenu* file_submenu = m_mainmenu->GetSubMenu(pos);
if (file_submenu != NULL) // Look for "Close Database"
pos = FindMenuItem(file_submenu, ID_MENUITEM_CLOSE);
else
pos = -1;
m_pMRU = new CPWSRecentFileList( 0, _T("MRU"), _T("Safe%d"),
((nMRUItems != 0) ? nMRUItems : 1));
if (nMRUItems > 0) {
if (pos > -1) {
int irc;
// Create New Popup Menu
new_popupmenu->CreatePopupMenu();
CString cs_recent(MAKEINTRESOURCE(IDS_RECENT)),
cs_recentsafes(MAKEINTRESOURCE(IDS_RECENTSAFES));
if (!m_mruonfilemenu) { // MRU entries in popup menu
// Insert Item onto new popup
irc = new_popupmenu->InsertMenu(0, MF_BYPOSITION,
ID_FILE_MRU_ENTRY1, cs_recent);
ASSERT(irc != 0);
// Insert Popup onto main menu
irc = file_submenu->InsertMenu(pos + 2,
MF_BYPOSITION | MF_POPUP,
UINT_PTR(new_popupmenu->m_hMenu),
cs_recentsafes);
ASSERT(irc != 0);
} else { // MRU entries inline
irc = file_submenu->InsertMenu(pos + 2, MF_BYPOSITION,
ID_FILE_MRU_ENTRY1, cs_recent);
ASSERT(irc != 0);
} // m_mruonfilemenu
m_pMRU->ReadList();
} // pos > -1
} else { // nMRUItems <= 0
if (pos > -1) {
int irc;
// Remove extra separator
irc = file_submenu->RemoveMenu(pos + 1, MF_BYPOSITION);
ASSERT( irc != 0);
// Remove Clear MRU menu item.
irc = file_submenu->RemoveMenu(ID_MENUITEM_CLEAR_MRU, MF_BYCOMMAND);
ASSERT( irc != 0);
}
}
#ifdef DEMO
// add specific menu item for demo version
int hpos = FindMenuItem(m_mainmenu, CString(MAKEINTRESOURCE(IDS_HELPMENU)));
if (hpos == -1)
hpos = 4; // best guess...
CMenu* help_submenu = m_mainmenu->GetSubMenu(hpos);
if (help_submenu != NULL) {
help_submenu->InsertMenu(2, MF_BYPOSITION, ID_U3SHOP_WEBSITE,
CString(MAKEINTRESOURCE(IDS_U3PURCHASE)));
}
#endif /* DEMO */
DboxMain dbox(NULL);
/*
* Command line processing:
* Historically, it appears that if a filename was passed as a commadline argument,
* the application would prompt the user for the password, and the encrypt or decrypt
* the named file, based on the file's suffix. Ugh.
*
* What I'll do is as follows:
* If a file is given in the command line, it is used as the database, overriding the
* registry value. This will allow the user to have several databases, say, one for work
* and one for personal use, and to set up a different shortcut for each.
*
* I think I'll keep the old functionality, but activate it with a "-e" or "-d" flag. (ronys)
* {kjp} ... and I've removed all of it from the Pocket PC build.
*/
#if !defined(POCKET_PC)
if (m_lpCmdLine[0] != TCHAR('\0')) {
CString args = m_lpCmdLine;
if (args[0] != _T('-')) {
StripFileQuotes( args );
if (CheckFile(args)) {
dbox.SetCurFile(args);
} else {
return FALSE;
}
} else { // here if first char of arg is '-'
// first, let's check that there's a second arg
CString fn = args.Right(args.GetLength()-2);
fn.Trim();
if (!fn.IsEmpty())
StripFileQuotes( fn );
const int UC_arg1(toupper(args[1]));
// The following arguements require the database name and it exists!
if ((UC_arg1 == 'D' || UC_arg1 == 'E' || UC_arg1 == 'R' || UC_arg1 == 'V')
&& (fn.IsEmpty() || CheckFile(fn) == FALSE)) {
Usage();
return FALSE;
}
if (fn.IsEmpty())
fn = (CString)PWSprefs::GetInstance()->GetPref(PWSprefs::CurrentFile);
CMyString passkey;
if (UC_arg1 == 'E' || UC_arg1 == 'D') {
// get password from user if valid flag given. If note, default below will
// pop usage message
CCryptKeyEntry dlg(NULL);
INT_PTR nResponse = dlg.DoModal();
if (nResponse==IDOK) {
passkey = dlg.m_cryptkey1;
} else {
return FALSE;
}
}
BOOL status;
dbox.SetReadOnly(false);
switch (UC_arg1) {
case 'C':
dbox.SetStartClosed(true);
dbox.SetCurFile(_T(""));
break;
case 'D': // do decryption
status = DecryptFile(fn, passkey);
if (!status) {
// nothing to do - DecryptFile displays its own error messages
}
return TRUE;
case 'E': // do encrpytion
status = EncryptFile(fn, passkey);
if (!status) {
AfxMessageBox(IDS_ENCRYPTIONFAILED);
}
return TRUE;
case 'M': // closed & minimized
dbox.SetStartClosed(true);
dbox.SetStartSilent(true);
dbox.SetCurFile(_T(""));
break;
case 'R':
dbox.SetReadOnly(true);
dbox.SetCurFile(fn);
break;
case 'S':
dbox.SetStartSilent(true);
dbox.SetCurFile(fn);
break;
case 'V':
dbox.SetValidate(true);
dbox.SetCurFile(fn);
break;
default:
Usage();
return FALSE;
} // switch
} // else
} // m_lpCmdLine[0] != TCHAR('\0');
#endif
/*
* normal startup
*/
/*
Here's where PWS currently does DboxMain, which in turn will do
the initial PasskeyEntry (the one that looks like a splash screen).
This makes things very hard to control.
The app object (here) should instead do the initial PasskeyEntry,
and, if successful, move on to DboxMain. I think. {jpr}
*/
m_maindlg = &dbox;
m_pMainWnd = m_maindlg;
// JHF : no tray icon and menu for PPC
#if !defined(POCKET_PC)
//HICON stIcon = app.LoadIcon(IDI_TRAY);
//ASSERT(stIcon != NULL);
m_LockedIcon = app.LoadIcon(IDI_LOCKEDICON);
m_UnLockedIcon = app.LoadIcon(IDI_UNLOCKEDICON);
m_ClosedIcon = app.LoadIcon(IDI_TRAY);
m_TrayIcon = new CSystemTray(NULL, WM_ICON_NOTIFY, _T("PasswordSafe"),
m_LockedIcon, dbox.m_RUEList,
WM_ICON_NOTIFY, IDR_POPTRAY);
m_TrayIcon->SetTarget(&dbox);
#endif
// Set up an Accelerator table
#if !defined(POCKET_PC)
m_ghAccelTable = LoadAccelerators(AfxGetResourceHandle(),
MAKEINTRESOURCE(IDR_ACCS));
#endif
CLWnd ListenerWnd(dbox);
if (SysInfo::IsUnderU3()) {
// See comment under CLWnd to understand this.
ListenerWnd.m_hWnd = NULL;
if (!ListenerWnd.CreateEx(0, AfxRegisterWndClass(0),
_T("Pwsafe Listener"),
WS_OVERLAPPED, 0, 0, 0, 0, NULL, NULL)) {
ASSERT(0);
return FALSE;
}
}
//Run dialog
(void) dbox.DoModal();
/*
note that we don't particularly care what the response was
*/
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
delete new_popupmenu;
return FALSE;
}
void
ThisMfcApp::AddToMRU(const CString &pszFilename)
{
if (m_pMRU == NULL)
return;
CString csMRUFilename(pszFilename);
csMRUFilename.Trim();
if (!csMRUFilename.IsEmpty()) {
m_pMRU->Add(csMRUFilename);
m_pMRU->WriteList();
}
}
void
ThisMfcApp::ClearMRU()
{
if (m_pMRU == NULL)
return;
int numMRU = m_pMRU->GetSize();
for (int i = numMRU; i > 0; i--)
m_pMRU->Remove(i - 1);
m_pMRU->WriteList();
// Can't get the MRU list on the menu to tidy up automatically
// Do it manually!
CWnd* pMain = AfxGetMainWnd();
CMenu* xmainmenu = pMain->GetMenu();
// Look for "File" menu.
CString cs_text(MAKEINTRESOURCE(IDS_FILEMENU));
int pos = FindMenuItem(xmainmenu, cs_text);
if (pos == -1) // E.g., in non-English versions
pos = 0; // best guess...
CMenu* xfile_submenu = xmainmenu->GetSubMenu(pos);
if (xfile_submenu != NULL) // Look for MRU first entry
pos = FindMenuItem(xfile_submenu, ID_FILE_MRU_ENTRY1);
else
return;
if (pos > -1) {
// Recent databases are on the main File menu
for (int nID = numMRU; nID > 1; nID--)
xfile_submenu->RemoveMenu(ID_FILE_MRU_ENTRY1 + nID - 1, MF_BYCOMMAND);
return;
}
// Recent databases are on the popup menu off the main File menu
CMenu* xpopupmenu = xfile_submenu->GetSubMenu(3);
if (xpopupmenu != NULL) // Look for MRU first entry
pos = FindMenuItem(xpopupmenu, ID_FILE_MRU_ENTRY1);
else
return;
if (pos > -1) {
// Recent databases are on the main File menu
for (int nID = numMRU; nID > 1; nID--)
xfile_submenu->RemoveMenu(ID_FILE_MRU_ENTRY1 + nID - 1, MF_BYCOMMAND);
return;
}
}
void
ThisMfcApp::SetSystemTrayState(STATE s)
{
// need to protect against null m_TrayIcon due to
// tricky initialization order
if (m_TrayIcon != NULL && s != m_TrayLockedState) {
m_TrayLockedState = s;
HICON hIcon(m_LockedIcon);
switch (s) {
case LOCKED:
hIcon = m_LockedIcon;
break;
case UNLOCKED:
hIcon = m_UnLockedIcon;
break;
case CLOSED:
hIcon = m_ClosedIcon;
break;
default:
break;
}
m_TrayIcon->SetIcon(hIcon);
}
}
void
ThisMfcApp::SetClipboardData(const CMyString &data)
{
m_clipboard_set = PWSUtil::ToClipboard(data, m_clipboard_digest, m_pMainWnd->m_hWnd);
}
void
ThisMfcApp::ClearClipboardData()
{
// Clear the clipboard IFF its value is the same as last set by this app.
if (!m_clipboard_set)
return;
m_clipboard_set = PWSUtil::ClearClipboard(m_clipboard_digest,
m_pMainWnd->m_hWnd);
}
#if !defined(POCKET_PC)
// Removes quotation marks from file name parameters
// as in "file with spaces.pws"
void
ThisMfcApp::StripFileQuotes( CString& strFilename )
{
const TCHAR* szFilename = strFilename;
int nLen = strFilename.GetLength();
// if the filenames starts with a quote...
if ( *szFilename == TCHAR('\"') ) {
// remove leading quote
++szFilename;
--nLen;
// trailing quote is optional, remove if present
if ( szFilename[nLen - 1] == TCHAR('\"') )
--nLen;
strFilename = CString( szFilename, nLen );
}
}
#endif
#if !defined(POCKET_PC)
//Copied from Knowledge Base article Q100770
//But not for WinCE {kjp}
BOOL
ThisMfcApp::ProcessMessageFilter(int code, LPMSG lpMsg)
{
if (code < 0)
CWinApp::ProcessMessageFilter(code, lpMsg);
if (m_bUseAccelerator &&
m_maindlg != NULL &&
m_ghAccelTable != NULL &&
code != MSGF_MENU) {
if (::TranslateAccelerator(m_maindlg->m_hWnd, m_ghAccelTable, lpMsg))
return TRUE;
}
return CWinApp::ProcessMessageFilter(code, lpMsg);
}
#endif
void
ThisMfcApp::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#mainhelp"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
/*
* Following mess because CPropertySheet is too smart for its own
* good. The "Help" button there is mapped to the App framework,
* and that's that...
*/
CString cs_title;
CWnd *wnd = CWnd::GetCapture();
if (wnd == NULL)
wnd = CWnd::GetFocus();
if (wnd != NULL)
wnd = wnd->GetParent();
if (wnd != NULL) {
wnd->GetWindowText(cs_title);
}
CString cs_text(MAKEINTRESOURCE(IDS_OPTIONS));
if (cs_title != cs_text) {
::HtmlHelp(wnd != NULL ? wnd->m_hWnd : NULL,
(LPCTSTR)m_csHelpFile,
HH_DISPLAY_TOPIC, 0);
} else {
CString cs_HelpTopic;
cs_HelpTopic = m_csHelpFile + _T("::/html/display_tab.html");
::HtmlHelp(NULL, (LPCTSTR)cs_HelpTopic, HH_DISPLAY_TOPIC, 0);
}
#endif
}
// FindMenuItem() will find a menu item string from the specified
// popup menu and returns its position (0-based) in the specified
// popup menu. It returns -1 if no such menu item string is found.
int ThisMfcApp::FindMenuItem(CMenu* Menu, LPCTSTR MenuString)
{
ASSERT(Menu);
ASSERT(::IsMenu(Menu->GetSafeHmenu()));
int count = Menu->GetMenuItemCount();
for (int i = 0; i < count; i++) {
CString str;
if (Menu->GetMenuString(i, str, MF_BYPOSITION) &&
(_tcscmp(str, MenuString) == 0))
return i;
}
return -1;
}
// FindMenuItem() will find a menu item ID from the specified
// popup menu and returns its position (0-based) in the specified
// popup menu. It returns -1 if no such menu item string is found.
int ThisMfcApp::FindMenuItem(CMenu* Menu, int MenuID)
{
ASSERT(Menu);
ASSERT(::IsMenu(Menu->GetSafeHmenu()));
int count = Menu->GetMenuItemCount();
int id;
for (int i = 0; i < count; i++) {
id = Menu->GetMenuItemID(i); // id = 0 for Separator; 1 for popup
if ( id > 1 && id == MenuID)
return i;
}
return -1;
}
void
ThisMfcApp::GetApplicationVersionData()
{
TCHAR szFullPath[MAX_PATH];
DWORD dwVerHnd, dwVerInfoSize;
// Get version information from the application
::GetModuleFileName(NULL, szFullPath, sizeof(szFullPath));
dwVerInfoSize = ::GetFileVersionInfoSize(szFullPath, &dwVerHnd);
if (dwVerInfoSize > 0) {
char* pVersionInfo = new char[dwVerInfoSize];
if(pVersionInfo != NULL) {
BOOL bRet = ::GetFileVersionInfo((LPTSTR)szFullPath,
(DWORD)dwVerHnd,
(DWORD)dwVerInfoSize,
(LPVOID)pVersionInfo);
VS_FIXEDFILEINFO *szVer = NULL;
UINT uVerLength;
if (bRet) {
// get binary file version information
bRet = ::VerQueryValue(pVersionInfo, TEXT("\\"),
(LPVOID*)&szVer, &uVerLength);
if (bRet) {
m_dwMajorMinor = szVer->dwProductVersionMS;
m_dwBuildRevision = szVer->dwProductVersionLS;
} else {
m_dwMajorMinor = m_dwBuildRevision = (DWORD)-1;
}
struct TRANSARRAY {
WORD wLangID;
WORD wCharSet;
};
CString cs_text;
TCHAR *buffer, *lpsztext;
UINT buflen;
TRANSARRAY* lpTransArray;
VerQueryValue(pVersionInfo, _T("\\VarFileInfo\\Translation"),
(LPVOID*)&buffer, &buflen);
lpTransArray = (TRANSARRAY*) buffer;
// Get string File Version information
cs_text.Format(_T("\\StringFileInfo\\%04x%04x\\FileVersion"),
lpTransArray[0].wLangID, lpTransArray[0].wCharSet);
lpsztext = cs_text.GetBuffer(cs_text.GetLength() + sizeof(TCHAR));
bRet = ::VerQueryValue(pVersionInfo, lpsztext, (LPVOID*)&buffer, &buflen);
m_csFileVersionString = bRet ? buffer : _T("");
cs_text.ReleaseBuffer();
// Get string Legal Copyright information
cs_text.Format(_T("\\StringFileInfo\\%04x%04x\\LegalCopyright"),
lpTransArray[0].wLangID, lpTransArray[0].wCharSet);
lpsztext = cs_text.GetBuffer(cs_text.GetLength() + sizeof(TCHAR));
bRet = ::VerQueryValue(pVersionInfo, lpsztext, (LPVOID*)&buffer, &buflen);
m_csCopyrightString = bRet ? buffer : _T("All rights reserved.");
cs_text.ReleaseBuffer();
}
}
delete[] pVersionInfo;
}
}
CString
ThisMfcApp::GetVersionInfoFromFile(const CString &csFileName)
{
CString csFileVersionString(_T(""));
DWORD dwVerHnd, dwVerInfoSize;
// Get version information from the application
dwVerInfoSize = ::GetFileVersionInfoSize((LPTSTR)(LPCTSTR)csFileName, &dwVerHnd);
if (dwVerInfoSize > 0) {
char* pVersionInfo = new char[dwVerInfoSize];
if(pVersionInfo != NULL) {
BOOL bRet = ::GetFileVersionInfo((LPTSTR)(LPCTSTR)csFileName,
(DWORD)dwVerHnd,
(DWORD)dwVerInfoSize,
(LPVOID)pVersionInfo);
if (bRet) {
struct TRANSARRAY {
WORD wLangID;
WORD wCharSet;
};
CString cs_text;
TCHAR *buffer, *lpsztext;
UINT buflen;
TRANSARRAY* lpTransArray;
VerQueryValue(pVersionInfo, _T("\\VarFileInfo\\Translation"),
(LPVOID*)&buffer, &buflen);
lpTransArray = (TRANSARRAY*) buffer;
// Get string File Version information
cs_text.Format(_T("\\StringFileInfo\\%04x%04x\\FileVersion"),
lpTransArray[0].wLangID, lpTransArray[0].wCharSet);
lpsztext = cs_text.GetBuffer(cs_text.GetLength() + sizeof(TCHAR));
bRet = ::VerQueryValue(pVersionInfo, lpsztext, (LPVOID*)&buffer, &buflen);
csFileVersionString = bRet ? buffer : _T("");
cs_text.ReleaseBuffer();
}
}
delete[] pVersionInfo;
}
return csFileVersionString;
}

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks