forked from notepad-plus-plus/wingup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinmain.cpp
More file actions
1870 lines (1571 loc) · 56.5 KB
/
winmain.cpp
File metadata and controls
1870 lines (1571 loc) · 56.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 2007 Don HO <don.h@free.fr>
This file is part of GUP.
GUP is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
GUP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GUP. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../ZipLib/ZipFile.h"
#include "../ZipLib/utils/stream_utils.h"
#include <stdint.h>
#include <sys/stat.h>
#include <windows.h>
#include <fstream>
#include <string>
#include <sstream>
#include <commctrl.h>
#include <shlobj_core.h>
#include "resource.h"
#include <shlwapi.h>
#include "xmlTools.h"
#include "sha-256.h"
#include "dpiManager.h"
#include "Common.h"
#include "verifySignedfile.h"
#define CURL_STATICLIB
#include "../curl/include/curl/curl.h"
#define GUP_LOG_FILENAME L"c:\\tmp\\winup.log"
#ifdef _DEBUG
#define WRITE_LOG(fn, suffix, log) writeLog(fn, suffix, log);
#else
#define WRITE_LOG(fn, suffix, log)
#endif
using namespace std;
typedef vector<wstring> ParamVector;
HINSTANCE g_hInst = nullptr;
HHOOK g_hMsgBoxHook = nullptr;
HWND g_hAppWnd = nullptr;
DPIManager dpiManager;
static HWND hProgressDlg = nullptr;
static HWND hProgressBar = nullptr;
static bool doAbort = false;
static bool stopDL = false;
static wstring msgBoxTitle;
static wstring abortOrNot;
static wstring proxySrv = L"0.0.0.0";
static long proxyPort = 0;
static wstring winGupUserAgent = L"WinGup/";
static wstring dlFileName;
static wstring appIconFile;
static wstring nsisSilentInstallParam;
wstring FLAG_NSIS_SILENT_INSTALL_PARAM = L"/closeRunningNpp /S /runNppAfterSilentInstall";
static constexpr wchar_t MSGID_UPDATEAVAILABLE[] = L"An update package is available, do you want to download and install it?";
static constexpr wchar_t MSGID_VERSIONCURRENT[] = L"Current version is :";
static constexpr wchar_t MSGID_VERSIONNEW[] = L"Available version is :";
static constexpr wchar_t MSGID_DOWNLOADSTOPPED[] = L"Download is stopped by user. Update is aborted.";
static constexpr wchar_t MSGID_CLOSEAPP[] = L" is opened.\rUpdater will close it in order to process the installation.\rContinue?";
static constexpr wchar_t MSGID_ABORTORNOT[] = L"Do you want to abort update download?";
static constexpr wchar_t MSGID_UNZIPFAILED[] = L"Can't unzip:\nOperation not permitted or decompression failed";
static constexpr wchar_t MSGID_NODOWNLOADFOLDER[] = L"Can't find any folder for downloading.\rPlease check your environment variables\"%TMP%\", \"%TEMP%\" and \"%APPDATA%\"";
static constexpr wchar_t FLAG_OPTIONS[] = L"-options";
static constexpr wchar_t FLAG_VERBOSE[] = L"-verbose";
static constexpr wchar_t FLAG_HELP[] = L"--help";
static constexpr wchar_t FLAG_UUZIP[] = L"-unzipTo";
static constexpr wchar_t FLAG_CLEANUP[] = L"-clean";
static constexpr wchar_t FLAG_INFOURL[] = L"-infoUrl=";
static constexpr wchar_t FLAG_FORCEDOMAIN[] = L"-forceDomain=";
static constexpr wchar_t FLAG_CHKCERT_SIG[] = L"-chkCertSig=";
static constexpr wchar_t FLAG_CHKCERT_TRUSTCHAIN[] = L"-chkCertTrustChain";
static constexpr wchar_t FLAG_CHKCERT_REVOC[] = L"-chkCertRevoc";
static constexpr wchar_t FLAG_CHKCERT_NAME[] = L"-chkCertName=";
static constexpr wchar_t FLAG_CHKCERT_SUBJECT[] = L"-chkCertSubject=";
static constexpr wchar_t FLAG_CHKCERT_KEYID[] = L"-chkCertKeyId=";
static constexpr wchar_t FLAG_CHKCERT_AUTHORITYKEYID[] = L"-chkCertAuthorityKeyId=";
static constexpr wchar_t FLAG_ERRLOGPATH[] = L"-errLogPath=";
static constexpr wchar_t MSGID_HELP[] =
L"Usage:\r\n\
\r\n\
gup --help\r\n\
gup -options\r\n\
\r\n\
--help : Show this help message (and quit program).\r\n\
-options : Show the proxy configuration dialog (and quit program).\r\n\
\r\n\
Update mode:\r\n\
\r\n\
gup [-verbose] [-vVERSION_VALUE] [-pCUSTOM_PARAM]\r\n\
\r\n\
-v : Launch GUP with VERSION_VALUE.\r\n\
VERSION_VALUE is the current version number of program to update.\r\n\
If you pass the version number as the argument,\r\n\
then the version set in the gup.xml will be overrided.\r\n\
-p : Launch GUP with CUSTOM_PARAM.\r\n\
CUSTOM_PARAM will pass to destination by using GET method\r\n\
with argument name \"param\"\r\n\
-verbose: Show error/warning message if any.\r\n\
\r\n\
Update mode:\r\n\
\r\n\
gup [-vVERSION_VALUE] [-infoUrl=URL] [-forceDomain=URL_PREFIX]\r\n\
\r\n\
-infoUrl= : Use URL to override the value of \"InfoUr`\" tag in gup.xml.\r\n\
URL is the url to gain update and/or download information.\r\n\
-forceDomain= : Use URL_PREFIX to verify whether if the download link contain\r\n\
the domain prifix URL_PREFIX.If not, the download won't be processed.\r\n\
\r\n\
Update mode:\r\n\
\r\n\
gup [-vVERSION_VALUE] [-infoUrl=URL] [-chkCertSig=YES_NO] [-chkCertTrustChain]\r\n\
[-chkCertRevoc] [-chkCertName=\"CERT_NAME\"] [-chkCertSubject=\"CERT_SUBNAME\"]\r\n\
[-chkCertKeyId=CERT_KEYID] [-chkCertAuthorityKeyId=CERT_AUTHORITYKEYID]\r\n\
[-errLogPath=\"YOUR\\ERR\\LOG\\PATH.LOG\"]\r\n\
\r\n\
-chkCertSig= : Enable signature check on downloaded binary with \"-chkCertSig=yes\".\r\n\
Otherwise all the other \"-chkCert*\" options will be ignored.\r\n\
-chkCertTrustChain : Enable signature chain of trust verification.\r\n\
-chkCertRevoc : Enable the verification of certificate revocation state.\r\n\
-chkCertName= : Verify certificate name (quotes allowed for white-spaces).\r\n\
-chkCertSubject= : Verify subject name (quotes allowed for white-spaces).\r\n\
-chkCertKeyId= : Verify certificate key identifier.\r\n\
-chkCertAuthorityKeyId= : Verify certificate authority key identifier.\r\n\
-errLogPath= : override the default error log path. The default value is:\r\n\
\"%LOCALAPPDATA%\\WinGUp\\log\\securityError.log\"\r\n\
\r\n\
Download & unzip mode:\r\n\
\r\n\
gup -clean FOLDER_TO_ACTION\r\n\
gup -unzipTo [-clean] FOLDER_TO_ACTION ZIP_URL\r\n\
\r\n\
-clean : Delete all files in FOLDER_TO_ACTION.\r\n\
-unzipTo : Download zip file from ZIP_URL then unzip it into FOLDER_TO_ACTION.\r\n\
ZIP_URL : The URL to download zip file.\r\n\
FOLDER_TO_ACTION : The folder where we clean or/and unzip to.\r\n\
";
HFONT hCmdLineEditFont = nullptr;
INT_PTR CALLBACK helpDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM)
{
switch (message)
{
case WM_INITDIALOG:
{
// Center dialog on screen
RECT rc;
GetWindowRect(hDlg, &rc);
int x = (GetSystemMetrics(SM_CXSCREEN) - (rc.right - rc.left)) / 2;
int y = (GetSystemMetrics(SM_CYSCREEN) - (rc.bottom - rc.top)) / 2;
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
SetDlgItemText(hDlg, IDC_COMMANDLINEARGS_EDIT, MSGID_HELP);
// Create DPI-aware monospace font
NONCLIENTMETRICS ncm {};
ncm.cbSize = sizeof(NONCLIENTMETRICS);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0);
// Use the system font height but change to monospace
hCmdLineEditFont = CreateFont(
ncm.lfMessageFont.lfHeight, // DPI-aware height from system
0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, FIXED_PITCH | FF_MODERN,
L"Lucida Console");
if (hCmdLineEditFont)
SendDlgItemMessage(hDlg, IDC_COMMANDLINEARGS_EDIT, WM_SETFONT, (WPARAM)hCmdLineEditFont, TRUE);
}
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, IDOK);
return TRUE;
}
break;
case WM_DESTROY:
if (hCmdLineEditFont)
{
DeleteObject(hCmdLineEditFont);
hCmdLineEditFont = nullptr;
}
break;
}
return FALSE;
}
class DlgIconHelper
{
public:
DlgIconHelper()
{
g_hMsgBoxHook = SetWindowsHookEx(WH_CALLWNDPROC, CallWndProc, NULL, GetCurrentThreadId());
}
~DlgIconHelper()
{
UnhookWindowsHookEx(g_hMsgBoxHook);
}
static LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
CWPSTRUCT* pcwp = (CWPSTRUCT*)lParam;
if (pcwp->message == WM_INITDIALOG)
{
setIcon(pcwp->hwnd, appIconFile);
}
}
return CallNextHookEx(g_hMsgBoxHook, nCode, wParam, lParam);
}
static void setIcon(HWND hwnd, const wstring& iconFile)
{
if (!iconFile.empty())
{
HICON hIcon = nullptr, hIconSm = nullptr;
hIcon = reinterpret_cast<HICON>(LoadImage(NULL, iconFile.c_str(), IMAGE_ICON, 32, 32, LR_LOADFROMFILE));
hIconSm = reinterpret_cast<HICON>(LoadImage(NULL, iconFile.c_str(), IMAGE_ICON, 16, 16, LR_LOADFROMFILE));
if (hIcon && hIconSm)
{
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIconSm);
}
}
}
};
DlgIconHelper dlgIconHelper;
void parseCommandLine(const wchar_t* commandLine, ParamVector& paramVector)
{
if (!commandLine)
return;
wchar_t* cmdLine = new wchar_t[lstrlen(commandLine) + 1];
lstrcpy(cmdLine, commandLine);
wchar_t* cmdLinePtr = cmdLine;
bool isBetweenFileNameQuotes = false;
bool isStringInArg = false;
bool isInWhiteSpace = true;
int zArg = 0; // for "-z" argument: Causes Notepad++ to ignore the next command line argument (a single word, or a phrase in quotes).
// The only intended and supported use for this option is for the Notepad Replacement syntax.
bool shouldBeTerminated = false; // If "-z" argument has been found, zArg value will be increased from 0 to 1.
// then after processing next argument of "-z", zArg value will be increased from 1 to 2.
// when zArg == 2 shouldBeTerminated will be set to true - it will trigger the treatment which consider the rest as a argument, with or without white space(s).
size_t commandLength = lstrlen(cmdLinePtr);
std::vector<wchar_t*> args;
for (size_t i = 0; i < commandLength && !shouldBeTerminated; ++i)
{
switch (cmdLinePtr[i])
{
case '\"': //quoted filename, ignore any following whitespace
{
if (!isStringInArg && !isBetweenFileNameQuotes && i > 0 && cmdLinePtr[i - 1] == '=')
{
isStringInArg = true;
}
else if (isStringInArg)
{
isStringInArg = false;
}
else if (!isBetweenFileNameQuotes) //" will always be treated as start or end of param, in case the user forgot to add an space
{
args.push_back(cmdLinePtr + i + 1); //add next param(since zero terminated original, no overflow of +1)
isBetweenFileNameQuotes = true;
cmdLinePtr[i] = 0;
if (zArg == 1)
{
++zArg; // zArg == 2
}
}
else //if (isBetweenFileNameQuotes)
{
isBetweenFileNameQuotes = false;
//because we don't want to leave in any quotes in the filename, remove them now (with zero terminator)
cmdLinePtr[i] = 0;
}
isInWhiteSpace = false;
}
break;
case '\t': //also treat tab as whitespace
case ' ':
{
isInWhiteSpace = true;
if (!isBetweenFileNameQuotes && !isStringInArg)
{
cmdLinePtr[i] = 0; //zap spaces into zero terminators, unless its part of a filename
size_t argsLen = args.size();
if (argsLen > 0 && lstrcmp(args[argsLen - 1], L"-z") == 0)
++zArg; // "-z" argument is found: change zArg value from 0 (initial) to 1
}
}
break;
default: //default wchar_t, if beginning of word, add it
{
if (!isBetweenFileNameQuotes && !isStringInArg && isInWhiteSpace)
{
args.push_back(cmdLinePtr + i); //add next param
if (zArg == 2)
{
shouldBeTerminated = true; // stop the processing, and keep the rest string as it in the vector
}
isInWhiteSpace = false;
}
}
}
}
paramVector.assign(args.begin(), args.end());
delete[] cmdLine;
}
bool isInList(const wchar_t* token2Find, ParamVector & params)
{
size_t nbItems = params.size();
for (size_t i = 0; i < nbItems; ++i)
{
if (!lstrcmp(token2Find, params.at(i).c_str()))
{
params.erase(params.begin() + i);
return true;
}
}
return false;
}
bool getParamVal(wchar_t c, ParamVector & params, wstring & value)
{
value = L"";
size_t nbItems = params.size();
for (size_t i = 0; i < nbItems; ++i)
{
const wchar_t* token = params.at(i).c_str();
if (token[0] == '-' && lstrlen(token) >= 2 && token[1] == c) //dash, and enough chars
{
value = (token + 2);
params.erase(params.begin() + i);
return true;
}
}
return false;
}
bool getParamValFromString(const wchar_t* str, ParamVector& params, std::wstring& value)
{
value = L"";
size_t nbItems = params.size();
for (size_t i = 0; i < nbItems; ++i)
{
const wchar_t* token = params.at(i).c_str();
std::wstring tokenStr = token;
size_t pos = tokenStr.find(str);
if (pos != std::wstring::npos && pos == 0)
{
value = (token + lstrlen(str));
params.erase(params.begin() + i);
return true;
}
}
return false;
}
wstring PathAppend(wstring& strDest, const wstring& str2append)
{
if (strDest.empty() && str2append.empty()) // "" + ""
{
strDest = L"\\";
return strDest;
}
if (strDest.empty() && !str2append.empty()) // "" + titi
{
strDest = str2append;
return strDest;
}
if (strDest[strDest.length() - 1] == '\\' && (!str2append.empty() && str2append[0] == '\\')) // toto\ + \titi
{
strDest.erase(strDest.length() - 1, 1);
strDest += str2append;
return strDest;
}
if ((strDest[strDest.length() - 1] == '\\' && (!str2append.empty() && str2append[0] != '\\')) // toto\ + titi
|| (strDest[strDest.length() - 1] != '\\' && (!str2append.empty() && str2append[0] == '\\'))) // toto + \titi
{
strDest += str2append;
return strDest;
}
// toto + titi
strDest += L"\\";
strDest += str2append;
return strDest;
};
vector<wstring> tokenizeString(const wstring & tokenString, const char delim)
{
//Vector is created on stack and copied on return
std::vector<wstring> tokens;
// Skip delimiters at beginning.
string::size_type lastPos = tokenString.find_first_not_of(delim, 0);
// Find first "non-delimiter".
string::size_type pos = tokenString.find_first_of(delim, lastPos);
while (pos != std::string::npos || lastPos != std::string::npos)
{
// Found a token, add it to the vector.
tokens.push_back(tokenString.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = tokenString.find_first_not_of(delim, pos);
// Find next "non-delimiter"
pos = tokenString.find_first_of(delim, lastPos);
}
return tokens;
};
bool deleteFileOrFolder(const wstring& f2delete)
{
auto len = f2delete.length();
wchar_t* actionFolder = new wchar_t[len + 2];
lstrcpy(actionFolder, f2delete.c_str());
actionFolder[len] = 0;
actionFolder[len + 1] = 0;
SHFILEOPSTRUCT fileOpStruct = { 0 };
fileOpStruct.hwnd = NULL;
fileOpStruct.pFrom = actionFolder;
fileOpStruct.pTo = NULL;
fileOpStruct.wFunc = FO_DELETE;
fileOpStruct.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_ALLOWUNDO;
fileOpStruct.fAnyOperationsAborted = false;
fileOpStruct.hNameMappings = NULL;
fileOpStruct.lpszProgressTitle = NULL;
int res = SHFileOperation(&fileOpStruct);
if (res != 0)
{
// beware that some of the SHFileOperation error codes are not the standard WIN32 ones
// (e.g. 124 (0x7C) here means DE_INVALIDFILES and not the usual ERROR_INVALID_LEVEL)
WRITE_LOG(GUP_LOG_FILENAME, L"deleteFileOrFolder, SHFileOperation failed with error code: ", std::to_wstring(res).c_str());
}
delete[] actionFolder;
return (res == 0);
};
// unzipDestTo should be plugin home root + plugin folder name
// ex: %APPDATA%\..\local\Notepad++\plugins\myAwesomePlugin
bool decompress(const wstring& zipFullFilePath, const wstring& unzipDestTo)
{
// if destination folder doesn't exist, create it.
if (!::PathFileExists(unzipDestTo.c_str()))
{
if (!::CreateDirectory(unzipDestTo.c_str(), NULL))
return false;
}
string zipFullFilePathA = ws2s(zipFullFilePath);
ZipArchive::Ptr archive = ZipFile::Open(zipFullFilePathA.c_str());
std::istream* decompressStream = nullptr;
auto count = archive->GetEntriesCount();
if (!count) // wrong archive format
return false;
for (size_t i = 0; i < count; ++i)
{
ZipArchiveEntry::Ptr entry = archive->GetEntry(static_cast<int>(i));
assert(entry != nullptr);
//("[+] Trying no pass...\n");
decompressStream = entry->GetDecompressionStream();
assert(decompressStream != nullptr);
wstring file2extrait = s2ws(entry->GetFullName());
wstring extraitFullFilePath = unzipDestTo;
PathAppend(extraitFullFilePath, file2extrait);
// file2extrait be separated into an array
vector<wstring> strArray = tokenizeString(file2extrait, '/');
wstring folderPath = unzipDestTo;
if (entry->IsDirectory())
{
// if folder doesn't exist, create it.
if (!::PathFileExists(extraitFullFilePath.c_str()))
{
const size_t msgLen = 1024;
wchar_t msg[msgLen];
swprintf(msg, msgLen, L"[+] Create folder '%s'\n", file2extrait.c_str());
OutputDebugString(msg);
for (size_t k = 0; k < strArray.size(); ++k)
{
PathAppend(folderPath, strArray[k]);
if (!::PathFileExists(folderPath.c_str()))
{
::CreateDirectory(folderPath.c_str(), NULL);
}
else if (!::PathIsDirectory(folderPath.c_str())) // The unzip core component is not reliable for the file/directory detection
{ // Hence such hack to make the result is as correct as possible
// if it's a file, remove it
deleteFileOrFolder(folderPath);
// create it
::CreateDirectory(folderPath.c_str(), NULL);
}
}
}
}
else // it's a file
{
const size_t msgLen = 1024;
wchar_t msg[msgLen];
swprintf(msg, msgLen, L"[+] Extracting file '%s'\n", file2extrait.c_str());
OutputDebugString(msg);
for (size_t k = 0; k < strArray.size() - 1; ++k) // loop on only directory, not on file (which is the last element)
{
PathAppend(folderPath, strArray[k]);
if (!::PathFileExists(folderPath.c_str()))
{
::CreateDirectory(folderPath.c_str(), NULL);
}
else if (!::PathIsDirectory(folderPath.c_str())) // The unzip core component is not reliable for the file/directory detection
{ // Hence such hack to make the result is as correct as possible
// if it's a file, remove it
deleteFileOrFolder(folderPath);
// create it
::CreateDirectory(folderPath.c_str(), NULL);
}
}
std::ofstream destFile;
destFile.open(extraitFullFilePath, std::ios::binary | std::ios::trunc);
utils::stream::copy(*decompressStream, destFile);
destFile.flush();
destFile.close();
}
}
// check installed dll
wstring pluginFolder = PathFindFileName(unzipDestTo.c_str());
wstring installedPluginPath = unzipDestTo + L"\\" + pluginFolder + L".dll";
if (::PathFileExists(installedPluginPath.c_str()))
{
// DLL is deployed correctly.
// OK and nothing to do.
}
else
{
// Remove installed plugin
MessageBox(NULL, TEXT("The plugin package is built wrongly. This plugin will be uninstalled."), TEXT("GUP"), MB_OK | MB_APPLMODAL);
deleteFileOrFolder(unzipDestTo);
return FALSE;
}
return true;
};
static void goToScreenCenter(HWND hwnd)
{
RECT screenRc;
::SystemParametersInfo(SPI_GETWORKAREA, 0, &screenRc, 0);
POINT center;
center.x = screenRc.left + (screenRc.right - screenRc.left) / 2;
center.y = screenRc.top + (screenRc.bottom - screenRc.top)/2;
RECT rc;
::GetWindowRect(hwnd, &rc);
int x = center.x - (rc.right - rc.left)/2;
int y = center.y - (rc.bottom - rc.top)/2;
::SetWindowPos(hwnd, HWND_TOP, x, y, rc.right - rc.left, rc.bottom - rc.top, SWP_SHOWWINDOW);
};
// This is the getUpdateInfo call back function used by curl
static size_t getUpdateInfoCallback(char *data, size_t size, size_t nmemb, std::string *updateInfo)
{
// What we will return
size_t len = size * nmemb;
// Is there anything in the buffer?
if (updateInfo != NULL)
{
// Append the data to the buffer
updateInfo->append(data, len);
}
return len;
}
static size_t getDownloadData(unsigned char *data, size_t size, size_t nmemb, FILE *fp)
{
if (doAbort)
return 0;
size_t len = size * nmemb;
fwrite(data, len, 1, fp);
return len;
};
static size_t setProgress(HWND, double dlTotal, double dlSoFar, double, double)
{
while (stopDL)
::Sleep(1000);
size_t downloadedRatio = SendMessage(hProgressBar, PBM_DELTAPOS, 0, 0);
if (dlTotal != 0)
{
size_t step = size_t((dlSoFar * 100.0 / dlTotal) - downloadedRatio);
SendMessage(hProgressBar, PBM_SETSTEP, (WPARAM)step, 0);
SendMessage(hProgressBar, PBM_STEPIT, 0, 0);
}
const size_t percentageLen = 1024;
wchar_t percentage[percentageLen];
swprintf(percentage, percentageLen, L"Downloading %s: %Iu %%", dlFileName.c_str(), downloadedRatio);
::SetWindowText(hProgressDlg, percentage);
if (downloadedRatio == 100)
SendMessage(hProgressDlg, WM_COMMAND, IDOK, 0);
return 0;
};
LRESULT CALLBACK progressBarDlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM )
{
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_PROGRESS_CLASS;
InitCommonControlsEx(&InitCtrlEx);
switch(Msg)
{
case WM_INITDIALOG:
{
hProgressDlg = hWndDlg;
int x = dpiManager.scaleX(20);
int y = dpiManager.scaleY(20);
int width = dpiManager.scaleX(280);
int height = dpiManager.scaleY(17);
hProgressBar = CreateWindowEx(0, PROGRESS_CLASS, NULL, WS_CHILD | WS_VISIBLE,
x, y, width, height,
hWndDlg, NULL, g_hInst, NULL);
SendMessage(hProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
SendMessage(hProgressBar, PBM_SETSTEP, 1, 0);
DlgIconHelper::setIcon(hProgressDlg, appIconFile);
goToScreenCenter(hWndDlg);
return TRUE;
}
case WM_COMMAND:
switch(wParam)
{
case IDOK:
EndDialog(hWndDlg, 0);
return TRUE;
case IDCANCEL:
stopDL = true;
if (abortOrNot == L"")
abortOrNot = MSGID_ABORTORNOT;
int abortAnswer = ::MessageBox(hWndDlg, abortOrNot.c_str(), msgBoxTitle.c_str(), MB_YESNO);
if (abortAnswer == IDYES)
{
doAbort = true;
EndDialog(hWndDlg, 0);
}
stopDL = false;
return TRUE;
}
break;
}
return FALSE;
}
struct UpdateAvailableDlgStrings
{
wstring _title;
wstring _message;
wstring _customButton;
wstring _yesButton;
wstring _yesSilentButton;
wstring _noButton;
};
LRESULT CALLBACK yesNoNeverDlgProc(HWND hWndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
if (lParam)
{
UpdateAvailableDlgStrings* pUaDlgStrs = reinterpret_cast<UpdateAvailableDlgStrings*>(lParam);
if (!(pUaDlgStrs->_message).empty())
::SetDlgItemText(hWndDlg, IDC_YESNONEVERMSG, pUaDlgStrs->_message.c_str());
if (!(pUaDlgStrs->_title).empty())
::SetWindowText(hWndDlg, pUaDlgStrs->_title.c_str());
if (!pUaDlgStrs->_customButton.empty())
::SetDlgItemText(hWndDlg, IDCANCEL, pUaDlgStrs->_customButton.c_str());
if (!pUaDlgStrs->_yesButton.empty())
::SetDlgItemText(hWndDlg, IDYES, pUaDlgStrs->_yesButton.c_str());
if (!pUaDlgStrs->_yesSilentButton.empty())
::SetDlgItemText(hWndDlg, IDOK, pUaDlgStrs->_yesSilentButton.c_str());
if (!pUaDlgStrs->_noButton.empty())
::SetDlgItemText(hWndDlg, IDNO, pUaDlgStrs->_noButton.c_str());
if (!g_hAppWnd)
{
::EnableWindow(::GetDlgItem(hWndDlg, IDCANCEL), FALSE); // no app-wnd to sent the updates disabling message signal
FLAG_NSIS_SILENT_INSTALL_PARAM = L"/closeRunningNpp /S";
}
}
goToScreenCenter(hWndDlg);
return TRUE;
}
case WM_COMMAND:
{
switch (wParam)
{
case IDOK:
case IDYES:
case IDNO:
case IDCANCEL:
EndDialog(hWndDlg, wParam);
return TRUE;
default:
break;
}
}
case WM_DESTROY:
{
return TRUE;
}
}
return FALSE;
}
LRESULT CALLBACK proxyDlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM)
{
switch(Msg)
{
case WM_INITDIALOG:
::SetDlgItemText(hWndDlg, IDC_PROXYSERVER_EDIT, proxySrv.c_str());
::SetDlgItemInt(hWndDlg, IDC_PORT_EDIT, proxyPort, FALSE);
goToScreenCenter(hWndDlg);
return TRUE;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
{
wchar_t proxyServer[MAX_PATH];
::GetDlgItemText(hWndDlg, IDC_PROXYSERVER_EDIT, proxyServer, MAX_PATH);
proxySrv = proxyServer;
proxyPort = ::GetDlgItemInt(hWndDlg, IDC_PORT_EDIT, NULL, FALSE);
EndDialog(hWndDlg, 1);
return TRUE;
}
case IDCANCEL:
EndDialog(hWndDlg, 0);
return TRUE;
}
break;
}
return FALSE;
}
struct UpdateCheckParams
{
GupNativeLang& _nativeLang;
GupParameters& _gupParams;
};
LRESULT CALLBACK updateCheckDlgProc(HWND hWndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
auto* params = reinterpret_cast<UpdateCheckParams*>(lParam);
if (params)
{
const wstring& title = params->_gupParams.getMessageBoxTitle();
if (!title.empty())
::SetWindowText(hWndDlg, title.c_str());
wstring dlStr = params->_nativeLang.getMessageString("MSGID_DOWNLOADPAGE");
wstring moreInfoStr = params->_nativeLang.getMessageString("MSGID_MOREINFO");
if (!dlStr.empty() && !moreInfoStr.empty())
{
wstring goToDlStr = params->_nativeLang.getMessageString("MSGID_GOTODOWNLOADPAGETEXT");
if (!goToDlStr.empty())
{
wstring moreInfoLink = L"<a id=\"id_moreinfo\">";
moreInfoLink += moreInfoStr;
moreInfoLink += L"</a>";
wstring textWithLink = stringReplace(goToDlStr, L"$MSGID_MOREINFO$", moreInfoLink);
wstring dlLink = L"<a id=\"id_download\">";
dlLink += dlStr;
dlLink += L"</a>";
textWithLink = stringReplace(textWithLink, L"$MSGID_DOWNLOADPAGE$", dlLink);
::SetDlgItemText(hWndDlg, IDC_DOWNLOAD_LINK, textWithLink.c_str());
}
}
}
goToScreenCenter(hWndDlg);
return TRUE;
}
case WM_COMMAND:
{
switch LOWORD((wParam))
{
case IDOK:
case IDYES:
case IDNO:
case IDCANCEL:
EndDialog(hWndDlg, wParam);
return TRUE;
default:
break;
}
}
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code)
{
case NM_CLICK:
case NM_RETURN:
{
PNMLINK pNMLink = (PNMLINK)lParam;
LITEM item = pNMLink->item;
if (lstrcmpW(item.szID, L"id_download") == 0)
{
::ShellExecute(NULL, TEXT("open"), TEXT("https://notepad-plus-plus.org/downloads/"), NULL, NULL, SW_SHOWNORMAL);
EndDialog(hWndDlg, wParam);
}
else if (lstrcmpW(item.szID, L"id_moreinfo") == 0)
{
::ShellExecute(NULL, TEXT("open"), TEXT("https://npp-user-manual.org/docs/upgrading/#new-version-available-but-auto-updater-find-nothing"), NULL, NULL, SW_SHOWNORMAL);
EndDialog(hWndDlg, wParam);
}
break;
}
}
break;
}
return FALSE;
}
static DWORD WINAPI launchProgressBar(void *)
{
::DialogBox(g_hInst, MAKEINTRESOURCE(IDD_PROGRESS_DLG), NULL, reinterpret_cast<DLGPROC>(progressBarDlgProc));
return 0;
}
bool downloadBinary(const wstring& urlFrom, const wstring& destTo, const wstring& sha2HashToCheck, pair<wstring, int> proxyServerInfo, bool isSilentMode, const pair<wstring, wstring>& stoppedMessage)
{
FILE* pFile = _wfopen(destTo.c_str(), L"wb");
if (!pFile)
return false;
// Download the install package from indicated location
char errorBuffer[CURL_ERROR_SIZE] = { 0 };
CURLcode res = CURLE_FAILED_INIT;
CURL* curl = curl_easy_init();
::CreateThread(NULL, 0, launchProgressBar, NULL, 0, NULL);
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, ws2s(urlFrom).c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getDownloadData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, pFile);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, setProgress);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, hProgressBar);
curl_easy_setopt(curl, CURLOPT_USERAGENT, ws2s(winGupUserAgent).c_str());
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
if (!proxyServerInfo.first.empty() && proxyServerInfo.second != -1)
{
curl_easy_setopt(curl, CURLOPT_PROXY, ws2s(proxyServerInfo.first).c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxyServerInfo.second);
curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
}
curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST | CURLSSLOPT_NO_REVOKE);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
if (res != CURLE_OK)
{
if (!isSilentMode && doAbort == false)
{
std::wstring errMsg = L"A fail occurred while trying to download: \n" + urlFrom + L"\n\n" + s2ws(errorBuffer);
::MessageBoxW(NULL, errMsg.c_str(), L"curl error", MB_OK | MB_SYSTEMMODAL); // MB_SYSTEMMODAL ... need the WS_EX_TOPMOST (due to the possible progress-dlg...)
}
if (doAbort)
{
::MessageBox(NULL, stoppedMessage.first.c_str(), stoppedMessage.second.c_str(), MB_OK);
}
doAbort = false;
return false;
}
fflush(pFile);
fclose(pFile);
//
// Check the hash if need
//
bool ok = true;
if (!sha2HashToCheck.empty())