Setup.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211
  1. //---------------------------------------------------------------------------
  2. // Part of this code is
  3. // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
  4. //---------------------------------------------------------------------------
  5. #include <vcl.h>
  6. #pragma hdrstop
  7. #include <stdio.h>
  8. #include <tchar.h>
  9. #include <shlobj.h>
  10. #include <tlhelp32.h>
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <Exceptions.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <HelpWin.h>
  17. #include <Http.h>
  18. #include <CompThread.hpp>
  19. #include <FileInfo.h>
  20. #include "WinConfiguration.h"
  21. #include "WinInterface.h"
  22. #include "Tools.h"
  23. #include "Setup.h"
  24. #include <StrUtils.hpp>
  25. #include "ProgParams.h"
  26. #include <Consts.hpp>
  27. #include <GUITools.h>
  28. #include <PuttyTools.h>
  29. #include <VCLCommon.h>
  30. #include <WebBrowserEx.hpp>
  31. #include <DateUtils.hpp>
  32. //---------------------------------------------------------------------------
  33. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  34. _T("Session Manager\\Environment")
  35. // when the PATH registry key is over aprox 2048 characters,
  36. // PATH as well as WINDIR variables are actually not set, breaking the system
  37. #define MAX_PATH_LEN 2000
  38. /* Command line options. */
  39. UnicodeString LastPathError;
  40. //---------------------------------------------------------------------------
  41. UnicodeString NetVersionStr;
  42. UnicodeString PowerShellVersionStr;
  43. //---------------------------------------------------------------------------
  44. // Display the error "err_msg".
  45. void err_out(LPCTSTR err_msg)
  46. {
  47. LastPathError = err_msg;
  48. }
  49. //---------------------------------------------------------------------------
  50. // Display "base_err_msg" followed by the description of the system error
  51. // identified by "sys_err".
  52. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  53. {
  54. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  55. }
  56. //---------------------------------------------------------------------------
  57. // Works as "strcmp" but the comparison is not case sensitive.
  58. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  59. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  60. if (*str1 == L'\0')
  61. return 0;
  62. return tolower(*str1) - tolower(*str2);
  63. }
  64. //---------------------------------------------------------------------------
  65. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  66. // not present). The returned value must be freed with "free".
  67. LPTSTR unquote(LPCTSTR str){
  68. int last_pos;
  69. LPTSTR ret;
  70. size_t new_len;
  71. last_pos = _tcslen(str) - 1;
  72. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  73. new_len= (_tcslen(str) - 1);
  74. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  75. lstrcpyn(ret, &str[1], new_len);
  76. }
  77. else
  78. ret = _tcsdup(str);
  79. return ret;
  80. }
  81. //---------------------------------------------------------------------------
  82. // Find "what" in the ";" separated string "str" and returns a pointer to
  83. // the first letter of "what" in the string. If "next" is not "NULL" it
  84. // points to the first letter after "what" (excluding the trailing ";").
  85. // If "what" isn't find the functions returns "NULL".
  86. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  87. LPTSTR tok_buff;
  88. LPTSTR curr_tok;
  89. LPTSTR curr_tok_dup;
  90. BOOL path_eq;
  91. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  92. int pos = -1;
  93. LPTSTR ret;
  94. tok_buff = _tcsdup(str);
  95. curr_tok = _tcstok(tok_buff, _T(";"));
  96. while (pos == -1 && curr_tok){
  97. curr_tok_dup = unquote(curr_tok);
  98. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  99. GetShortPathName(curr_tok_dup, sh_path2,
  100. LENOF(sh_path2)) &&
  101. (tcharicmp(sh_path1, sh_path2) == 0);
  102. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  103. pos = curr_tok - tok_buff;
  104. }
  105. free(curr_tok_dup);
  106. curr_tok = _tcstok(NULL, _T(";"));
  107. if (pos != -1 && next){
  108. if (curr_tok)
  109. *next = str + (curr_tok - tok_buff);
  110. else
  111. *next = str + _tcslen(str);
  112. }
  113. }
  114. free(tok_buff);
  115. if (pos != -1)
  116. ret = str + pos;
  117. else
  118. ret = NULL;
  119. return ret;
  120. }
  121. //---------------------------------------------------------------------------
  122. void path_reg_propagate()
  123. {
  124. DWORD send_message_result;
  125. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  126. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  127. 5000, &send_message_result);
  128. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  129. {
  130. err_out_sys(_T("Cannot propagate the new enviroment to ")
  131. _T("other processes. The new value will be ")
  132. _T("avaible after a reboot."), GetLastError());
  133. SimpleErrorDialog(LastPathError);
  134. LastPathError = L"";
  135. }
  136. }
  137. //---------------------------------------------------------------------------
  138. // Add "path" to the registry. Return "TRUE" if the path has been added or
  139. // was already in the registry, "FALSE" otherwise.
  140. BOOL add_path_reg(LPCTSTR path){
  141. HKEY key;
  142. LONG ret;
  143. DWORD data_size;
  144. LPTSTR reg_str;
  145. BOOL func_ret = TRUE;
  146. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  147. KEY_WRITE | KEY_READ, &key);
  148. if (ret != ERROR_SUCCESS){
  149. err_out_sys(_T("Cannot open registry."), ret);
  150. return FALSE;
  151. }
  152. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  153. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  154. includes '\0'. */
  155. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  156. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  157. &data_size);
  158. if (ret != ERROR_SUCCESS){
  159. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  160. func_ret = FALSE;
  161. }
  162. else{
  163. if (!find_reg_str(reg_str, path, NULL)){
  164. _tcscat(reg_str, _T(";"));
  165. _tcscat(reg_str, path);
  166. size_t len = _tcslen(reg_str);
  167. if (len >= MAX_PATH_LEN)
  168. {
  169. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  170. func_ret = FALSE;
  171. }
  172. else
  173. {
  174. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  175. (LPBYTE)reg_str,
  176. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  177. if (ret != ERROR_SUCCESS){
  178. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  179. func_ret = FALSE;
  180. }
  181. /* Is this needed to make the new key avaible? */
  182. RegFlushKey(key);
  183. SetLastError(0);
  184. path_reg_propagate();
  185. }
  186. }
  187. }
  188. RegCloseKey(key);
  189. free(reg_str);
  190. return func_ret;
  191. }
  192. //---------------------------------------------------------------------------
  193. // Removes "path" from the registry. Return "TRUE" if the path has been
  194. // removed or it wasn't in the registry, "FALSE" otherwise.
  195. BOOL remove_path_reg(LPCTSTR path){
  196. HKEY key;
  197. LONG ret;
  198. DWORD data_size;
  199. LPTSTR reg_str;
  200. LPTSTR reg_str2;
  201. BOOL func_ret = TRUE;
  202. LPTSTR next;
  203. LPTSTR del_part;
  204. int last_pos;
  205. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  206. KEY_WRITE | KEY_READ, &key);
  207. if (ret != ERROR_SUCCESS){
  208. err_out_sys(_T("Cannot open registry."), ret);
  209. return FALSE;
  210. }
  211. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  212. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  213. includes '\0'. */
  214. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  215. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  216. (LPBYTE)reg_str, &data_size);
  217. if (ret != ERROR_SUCCESS){
  218. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  219. func_ret = FALSE;
  220. }
  221. else{
  222. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  223. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  224. *del_part = '\0';
  225. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  226. last_pos = _tcslen(reg_str2) - 1;
  227. if (last_pos != -1 && reg_str2[last_pos] == ';')
  228. reg_str2[last_pos] = '\0';
  229. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  230. (LPBYTE)reg_str2,
  231. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  232. if (ret != ERROR_SUCCESS){
  233. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  234. func_ret = FALSE;
  235. }
  236. free(reg_str2);
  237. /* Is this needed to make the new key avaible? */
  238. RegFlushKey(key);
  239. SetLastError(0);
  240. path_reg_propagate();
  241. }
  242. }
  243. RegCloseKey(key);
  244. free(reg_str);
  245. return func_ret;
  246. }
  247. //---------------------------------------------------------------------------
  248. //---------------------------------------------------------------------------
  249. void __fastcall AddSearchPath(const UnicodeString Path)
  250. {
  251. if (!add_path_reg(Path.c_str()))
  252. {
  253. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  254. }
  255. }
  256. //---------------------------------------------------------------------------
  257. void __fastcall RemoveSearchPath(const UnicodeString Path)
  258. {
  259. if (!remove_path_reg(Path.c_str()))
  260. {
  261. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  262. }
  263. }
  264. //---------------------------------------------------------------------------
  265. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  266. //---------------------------------------------------------------------------
  267. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  268. {
  269. if (Registry->OpenKey(Key, false))
  270. {
  271. std::unique_ptr<TStrings> List(new TStringList());
  272. Registry->GetValueNames(List.get());
  273. bool CanDelete = true;
  274. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  275. {
  276. UnicodeString ValueName = List->Strings[Index];
  277. if (!AllowRootValues)
  278. {
  279. CanDelete = false;
  280. }
  281. if ((ValueName != L"") &&
  282. (ValueName != L"URL Protocol") &&
  283. (ValueName != L"EditFlags") &&
  284. (ValueName != L"BrowserFlags"))
  285. {
  286. CanDelete = false;
  287. }
  288. }
  289. List->Clear();
  290. Registry->GetKeyNames(List.get());
  291. Registry->CloseKey();
  292. if (CanDelete)
  293. {
  294. for (int Index = 0; Index < List->Count; Index++)
  295. {
  296. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  297. }
  298. // will fail, if not all subkeys got removed
  299. Registry->DeleteKey(Key);
  300. }
  301. }
  302. }
  303. //---------------------------------------------------------------------------
  304. static void __fastcall RegisterProtocol(TRegistry * Registry,
  305. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  306. {
  307. if (Description.IsEmpty())
  308. {
  309. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  310. }
  311. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  312. if (Force || !Registry->KeyExists(ProtocolKey))
  313. {
  314. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  315. {
  316. Registry->WriteString(L"", Description);
  317. Registry->WriteString(L"URL Protocol", L"");
  318. Registry->WriteInteger(L"EditFlags", 0x02);
  319. Registry->WriteInteger(L"BrowserFlags", 0x08);
  320. if (Registry->OpenKey(L"DefaultIcon", true))
  321. {
  322. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  323. Registry->CloseKey();
  324. }
  325. else
  326. {
  327. Abort();
  328. }
  329. }
  330. else
  331. {
  332. Abort();
  333. }
  334. }
  335. }
  336. //---------------------------------------------------------------------------
  337. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  338. const UnicodeString & Protocol)
  339. {
  340. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  341. }
  342. //---------------------------------------------------------------------------
  343. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  344. {
  345. std::unique_ptr<TRegistry> Registry(new TRegistry());
  346. Registry->Access = KEY_WRITE | KEY_READ;
  347. Registry->RootKey = RootKey;
  348. return Registry.release();
  349. }
  350. //---------------------------------------------------------------------------
  351. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  352. const UnicodeString & Protocol, UnicodeString Description = L"")
  353. {
  354. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  355. RegisterProtocol(Registry.get(), Protocol, Description, true);
  356. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  357. Registry->OpenKey(L"shell", true) &&
  358. Registry->OpenKey(L"open", true) &&
  359. Registry->OpenKey(L"command", true))
  360. {
  361. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  362. Registry->CloseKey();
  363. }
  364. else
  365. {
  366. Abort();
  367. }
  368. }
  369. //---------------------------------------------------------------------------
  370. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  371. {
  372. try
  373. {
  374. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  375. // get rid of any HKCU registraction that would overrite the HKLM one
  376. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  377. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  378. {
  379. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  380. }
  381. }
  382. catch (Exception & E)
  383. {
  384. try
  385. {
  386. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  387. }
  388. catch(Exception & E)
  389. {
  390. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  391. }
  392. }
  393. }
  394. //---------------------------------------------------------------------------
  395. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  396. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  397. {
  398. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  399. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  400. if (Registry->OpenKey(DefaultIconKey, false))
  401. {
  402. UnicodeString Value = Registry->ReadString(L"");
  403. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  404. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  405. {
  406. Registry->DeleteValue(L"");
  407. }
  408. Registry->CloseKey();
  409. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  410. }
  411. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  412. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  413. {
  414. UnicodeString Value = Registry->ReadString(L"");
  415. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  416. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  417. {
  418. Registry->DeleteValue(L"");
  419. }
  420. Registry->CloseKey();
  421. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  422. }
  423. if (UnregisterProtocol)
  424. {
  425. ::UnregisterProtocol(Registry.get(), Protocol);
  426. }
  427. }
  428. //---------------------------------------------------------------------------
  429. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  430. {
  431. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  432. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  433. }
  434. //---------------------------------------------------------------------------
  435. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  436. {
  437. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  438. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  439. RegisterAsUrlHandler(Prefix + WebDAVProtocol.UpperCase());
  440. RegisterAsUrlHandler(Prefix + WebDAVSProtocol.UpperCase());
  441. RegisterAsUrlHandler(Prefix + S3Protocol.UpperCase());
  442. }
  443. //---------------------------------------------------------------------------
  444. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  445. {
  446. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  447. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  448. UnregisterAsUrlHandler(Prefix + WebDAVProtocol, UnregisterProtocol);
  449. UnregisterAsUrlHandler(Prefix + WebDAVSProtocol, UnregisterProtocol);
  450. UnregisterAsUrlHandler(Prefix + S3Protocol, UnregisterProtocol);
  451. }
  452. //---------------------------------------------------------------------------
  453. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  454. //---------------------------------------------------------------------------
  455. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  456. {
  457. // Register protocol, if it does not exist yet.
  458. // Prior to Windows 8, we need to register ourselves as legacy handler to
  459. // become the default handler. On Windows 8, it's automatic as long as no other
  460. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  461. RegisterAsUrlHandler(RootKey, Protocol);
  462. // see https://docs.microsoft.com/en-us/windows/desktop/shell/default-programs#registering-an-application-for-use-with-default-programs
  463. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  464. // create capabilities record
  465. // this has to be a separate branch from WinSCP one, as by its presence we
  466. // enforce registry storage usage, and the capabilities branch may exist
  467. // even if we are using INI file
  468. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  469. if (!Registry->OpenKey(CapabilitiesKey, true))
  470. {
  471. Abort();
  472. }
  473. UnicodeString Description = LoadStr(REGISTERED_APP_DESC2);
  474. Registry->WriteString(L"ApplicationDescription", Description);
  475. if (!Registry->OpenKey(L"UrlAssociations", true))
  476. {
  477. Abort();
  478. }
  479. Registry->WriteString(Protocol, GenericUrlHandler);
  480. Registry->CloseKey();
  481. // register application
  482. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  483. {
  484. Abort();
  485. }
  486. Registry->WriteString(AppNameString(), CapabilitiesKey);
  487. Registry->CloseKey();
  488. }
  489. //---------------------------------------------------------------------------
  490. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  491. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  492. {
  493. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  494. // unregister the protocol
  495. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  496. // remove capabilities record
  497. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  498. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  499. if (Registry->OpenKey(UrlAssociationsKey, false))
  500. {
  501. Registry->DeleteValue(Protocol);
  502. Registry->CloseKey();
  503. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  504. }
  505. if (Registry->OpenKey(CapabilitiesKey, false))
  506. {
  507. if (!Registry->HasSubKeys())
  508. {
  509. Registry->DeleteValue(L"ApplicationDescription");
  510. }
  511. Registry->CloseKey();
  512. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  513. }
  514. if (!Registry->KeyExists(CapabilitiesKey))
  515. {
  516. // unregister application
  517. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  518. {
  519. Registry->DeleteValue(AppNameString());
  520. Registry->CloseKey();
  521. }
  522. }
  523. }
  524. //---------------------------------------------------------------------------
  525. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  526. {
  527. // register URL handler, if it does not exist yet
  528. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  529. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  530. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  531. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  532. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  533. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  534. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  535. RegisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol);
  536. RegisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol);
  537. RegisterProtocolForDefaultPrograms(RootKey, S3Protocol);
  538. // deliberately not including http,
  539. // it's unlikely that anyone would like to change http handler
  540. // to non-browser application
  541. }
  542. //---------------------------------------------------------------------------
  543. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  544. {
  545. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  546. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  547. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  548. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  549. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  550. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol, ForceHandlerUnregistration);
  551. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol, ForceHandlerUnregistration);
  552. UnregisterProtocolForDefaultPrograms(RootKey, S3Protocol, ForceHandlerUnregistration);
  553. // we should not really need the "force" flag here, but why not
  554. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  555. }
  556. //---------------------------------------------------------------------------
  557. static void __fastcall RegisterForDefaultPrograms()
  558. {
  559. try
  560. {
  561. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  562. // make sure we unregister any legacy protocol handler for CU,
  563. // this is needed for Windows Vista+7
  564. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  565. }
  566. catch (Exception & E)
  567. {
  568. try
  569. {
  570. // Maybe we should skip this if HKLM key existed already (we are running non-privileged)
  571. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  572. }
  573. catch (Exception & E)
  574. {
  575. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  576. }
  577. }
  578. }
  579. //---------------------------------------------------------------------------
  580. static void __fastcall NotifyChangedAssociations()
  581. {
  582. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall RegisterForDefaultProtocols()
  586. {
  587. if (IsWinVista())
  588. {
  589. RegisterForDefaultPrograms();
  590. }
  591. else
  592. {
  593. RegisterAsNonBrowserUrlHandler(UnicodeString());
  594. }
  595. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  596. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  597. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  598. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  599. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  600. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  601. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  602. NotifyChangedAssociations();
  603. }
  604. //---------------------------------------------------------------------------
  605. void __fastcall UnregisterForProtocols()
  606. {
  607. UnregisterAsUrlHandlers(UnicodeString(), false);
  608. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  609. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  610. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  611. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  612. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  613. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  614. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  615. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  616. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  617. NotifyChangedAssociations();
  618. }
  619. //---------------------------------------------------------------------------
  620. void __fastcall LaunchAdvancedAssociationUI()
  621. {
  622. DebugAssert(IsWinVista());
  623. RegisterForDefaultPrograms();
  624. NotifyChangedAssociations();
  625. // sleep recommended by https://docs.microsoft.com/en-us/windows/desktop/shell/default-programs#becoming-the-default-browser
  626. Sleep(1000);
  627. if (IsWin10())
  628. {
  629. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  630. // https://stackoverflow.com/q/32178986/850848
  631. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  632. IOpenControlPanel * OpenControlPanel;
  633. HRESULT Result =
  634. CoCreateInstance(CLSID_OpenControlPanel,
  635. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  636. if (SUCCEEDED(Result))
  637. {
  638. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  639. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  640. OpenControlPanel->Release();
  641. }
  642. }
  643. else
  644. {
  645. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  646. HRESULT Result =
  647. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  648. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  649. if (SUCCEEDED(Result))
  650. {
  651. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  652. AppAssocRegUI->Release();
  653. }
  654. }
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TemporaryDirectoryCleanup()
  658. {
  659. bool Continue = true;
  660. TStrings * Folders = NULL;
  661. try
  662. {
  663. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  664. {
  665. Folders = WinConfiguration->FindTemporaryFolders();
  666. Continue = (Folders != NULL);
  667. if (Continue)
  668. {
  669. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  670. TQueryButtonAlias Aliases[1];
  671. Aliases[0].Button = qaRetry;
  672. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  673. TMessageParams Params(mpNeverAskAgainCheck);
  674. Params.Aliases = Aliases;
  675. Params.AliasesCount = LENOF(Aliases);
  676. unsigned int Answer = MoreMessageDialog(
  677. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  678. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  679. if (Answer == qaNeverAskAgain)
  680. {
  681. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  682. Answer = qaYes;
  683. }
  684. else if (Answer == qaRetry)
  685. {
  686. for (int Index = 0; Index < Folders->Count; Index++)
  687. {
  688. ShellExecute(Application->Handle, NULL,
  689. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  690. }
  691. }
  692. Continue = (Answer == qaYes);
  693. }
  694. }
  695. if (Continue)
  696. {
  697. try
  698. {
  699. WinConfiguration->CleanupTemporaryFolders(Folders);
  700. }
  701. catch (Exception &E)
  702. {
  703. ShowExtendedException(&E);
  704. }
  705. }
  706. }
  707. __finally
  708. {
  709. delete Folders;
  710. }
  711. }
  712. //-------------------------------------------- -------------------------------
  713. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  714. {
  715. int MajorVer = Version / (10000*100*100);
  716. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  717. int Release = (Version % (10000*100)) / (10000);
  718. UnicodeString Result;
  719. if (Release > 0)
  720. {
  721. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  722. }
  723. else
  724. {
  725. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  726. }
  727. return Result;
  728. }
  729. //---------------------------------------------------------------------------
  730. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  731. {
  732. int CurrentCompoundVer = Configuration->CompoundVersion;
  733. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  734. UnicodeString Medium = IsUWP() ? L"uwp" : L"app";
  735. // Beware that these parameters may get truncated if URL is too long,
  736. // such as with ERROR_REPORT_URL2
  737. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=%s&utm_campaign=%s", (Medium, Version));
  738. return AppendUrlParams(URL, Params);
  739. }
  740. //---------------------------------------------------------------------------
  741. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  742. {
  743. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  744. UnicodeString CurrentVersionStr =
  745. FORMAT(L"%d.%d.%d.%d",
  746. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  747. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  748. UnicodeString Params =
  749. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  750. (CurrentVersionStr,
  751. GUIConfiguration->AppliedLocaleHex,
  752. int(IsInstalled())));
  753. if (Configuration->IsUnofficial)
  754. {
  755. Params += L"&unofficial=1";
  756. }
  757. return AppendUrlParams(URL, Params);
  758. }
  759. //---------------------------------------------------------------------------
  760. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  761. {
  762. bool Beta;
  763. if (WinConfiguration->IsBeta)
  764. {
  765. Beta = true;
  766. }
  767. else
  768. {
  769. switch (WinConfiguration->Updates.BetaVersions)
  770. {
  771. case asAuto:
  772. Beta = WinConfiguration->AnyBetaInVersionHistory;
  773. break;
  774. case asOn:
  775. Beta = true;
  776. break;
  777. default:
  778. Beta = false;
  779. break;
  780. }
  781. }
  782. if (Beta || Force)
  783. {
  784. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  785. }
  786. return URL;
  787. }
  788. //---------------------------------------------------------------------------
  789. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  790. {
  791. std::unique_ptr<THttp> Http(new THttp());
  792. UnicodeString ProxyHost;
  793. int ProxyPort = 0;
  794. switch (Updates.ConnectionType)
  795. {
  796. case ctAuto:
  797. if (AutodetectProxy(ProxyHost, ProxyPort))
  798. {
  799. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  800. }
  801. break;
  802. case ctProxy:
  803. ProxyHost = Updates.ProxyHost;
  804. ProxyPort = Updates.ProxyPort;
  805. Configuration->Usage->Inc(L"UpdateProxyManual");
  806. break;
  807. }
  808. Http->ProxyHost = ProxyHost;
  809. Http->ProxyPort = ProxyPort;
  810. return Http.release();
  811. }
  812. //---------------------------------------------------------------------------
  813. THttp * __fastcall CreateHttp()
  814. {
  815. return CreateHttp(WinConfiguration->Updates);
  816. }
  817. //---------------------------------------------------------------------------
  818. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  819. {
  820. bool Complete = false;
  821. UnicodeString Response;
  822. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  823. try
  824. {
  825. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  826. URL = WantBetaUrl(URL, false);
  827. URL += L"&dotnet=" + Updates.DotNetVersion;
  828. URL += L"&console=" + Updates.ConsoleVersion;
  829. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  830. if (!LocaleVersion.IsEmpty())
  831. {
  832. URL += L"&localever=" + LocaleVersion;
  833. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  834. }
  835. if (!Updates.AuthenticationEmail.IsEmpty())
  836. {
  837. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  838. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  839. }
  840. CheckForUpdatesHTTP->URL = URL;
  841. // sanity check
  842. CheckForUpdatesHTTP->ResponseLimit = 102400;
  843. try
  844. {
  845. if (CollectUsage)
  846. {
  847. UnicodeString Usage = Configuration->Usage->Serialize();
  848. CheckForUpdatesHTTP->Post(Usage);
  849. }
  850. else
  851. {
  852. CheckForUpdatesHTTP->Get();
  853. }
  854. }
  855. catch (...)
  856. {
  857. if (CheckForUpdatesHTTP->IsCertificateError())
  858. {
  859. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  860. }
  861. throw;
  862. }
  863. Response = CheckForUpdatesHTTP->Response;
  864. }
  865. __finally
  866. {
  867. delete CheckForUpdatesHTTP;
  868. }
  869. int CurrentCompoundVer = Configuration->CompoundVersion;
  870. bool Changed = !Updates.HaveResults;
  871. Updates.LastCheck = Now();
  872. Updates.HaveResults = true;
  873. TUpdatesData PrevResults = Updates.Results;
  874. Updates.Results.Reset();
  875. Updates.Results.ForVersion = CurrentCompoundVer;
  876. while (!Response.IsEmpty())
  877. {
  878. UnicodeString Line = CutToChar(Response, L'\n', false);
  879. UnicodeString Name = CutToChar(Line, L'=', false);
  880. if (SameText(Name, "Version"))
  881. {
  882. int NewVersion = StrToCompoundVersion(Line);
  883. Changed |= (NewVersion != PrevResults.Version);
  884. if (NewVersion <= CurrentCompoundVer)
  885. {
  886. NewVersion = 0;
  887. }
  888. Updates.Results.Version = NewVersion;
  889. Complete = true;
  890. }
  891. else if (SameText(Name, L"Message"))
  892. {
  893. Changed |= (PrevResults.Message != Line);
  894. Updates.Results.Message = Line;
  895. }
  896. else if (SameText(Name, L"Critical"))
  897. {
  898. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  899. Changed |= (PrevResults.Critical != NewCritical);
  900. Updates.Results.Critical = NewCritical;
  901. }
  902. else if (SameText(Name, L"Release"))
  903. {
  904. Changed |= (PrevResults.Release != Line);
  905. Updates.Results.Release = Line;
  906. }
  907. else if (SameText(Name, L"Disabled"))
  908. {
  909. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  910. Changed |= (PrevResults.Disabled != NewDisabled);
  911. Updates.Results.Disabled = NewDisabled;
  912. Complete = true;
  913. }
  914. else if (SameText(Name, L"Url"))
  915. {
  916. Changed |= (PrevResults.Url != Line);
  917. Updates.Results.Url = Line;
  918. }
  919. else if (SameText(Name, L"UrlButton"))
  920. {
  921. Changed |= (PrevResults.UrlButton != Line);
  922. Updates.Results.UrlButton = Line;
  923. }
  924. else if (SameText(Name, L"NewsUrl"))
  925. {
  926. Changed |= (PrevResults.NewsUrl != Line);
  927. Updates.Results.NewsUrl = Line;
  928. }
  929. else if (SameText(Name, L"NewsSize"))
  930. {
  931. TSize NewsSize;
  932. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  933. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  934. Changed |= (PrevResults.NewsSize != NewsSize);
  935. Updates.Results.NewsSize = NewsSize;
  936. }
  937. else if (SameText(Name, L"DownloadUrl"))
  938. {
  939. Changed |= (PrevResults.DownloadUrl != Line);
  940. Updates.Results.DownloadUrl = Line;
  941. }
  942. else if (SameText(Name, L"DownloadSize"))
  943. {
  944. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  945. }
  946. else if (SameText(Name, L"DownloadSha256"))
  947. {
  948. Updates.Results.DownloadSha256 = Line;
  949. }
  950. else if (SameText(Name, L"AuthenticationError"))
  951. {
  952. Changed |= (PrevResults.AuthenticationError != Line);
  953. Updates.Results.AuthenticationError = Line;
  954. }
  955. else if (SameText(Name, L"OpenGettingStarted"))
  956. {
  957. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  958. }
  959. else if (SameText(Name, L"DownloadingUrl"))
  960. {
  961. Updates.Results.DownloadingUrl = Line;
  962. }
  963. else if (SameText(Name, L"TipsSize"))
  964. {
  965. TSize TipsSize;
  966. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  967. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  968. Updates.Results.TipsSize = TipsSize;
  969. }
  970. else if (SameText(Name, L"TipsUrl"))
  971. {
  972. Updates.Results.TipsUrl = Line;
  973. }
  974. else if (SameText(Name, L"Tips"))
  975. {
  976. Updates.Results.Tips = Line;
  977. }
  978. else if (SameText(Name, L"TipsIntervalDays"))
  979. {
  980. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  981. if (TipsIntervalDays < 0)
  982. {
  983. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  984. }
  985. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  986. }
  987. else if (SameText(Name, L"TipsIntervalRuns"))
  988. {
  989. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  990. if (TipsIntervalRuns < 0)
  991. {
  992. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  993. }
  994. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  995. }
  996. }
  997. if (Changed)
  998. {
  999. Updates.ShownResults = false;
  1000. }
  1001. return Complete;
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1005. {
  1006. return DoQueryUpdates(Updates, false);
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1010. {
  1011. try
  1012. {
  1013. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1014. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1015. WinConfiguration->Updates = Updates;
  1016. if (!Complete)
  1017. {
  1018. EXCEPTION;
  1019. }
  1020. Configuration->Usage->Reset();
  1021. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1022. }
  1023. catch(Exception & E)
  1024. {
  1025. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1026. UnicodeString Message;
  1027. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1028. {
  1029. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1030. }
  1031. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1032. }
  1033. }
  1034. //---------------------------------------------------------------------------
  1035. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  1036. {
  1037. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1038. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1039. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1040. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  1041. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1042. Message = ReplaceStr(Message, L"|", L"\n");
  1043. return Message;
  1044. }
  1045. //---------------------------------------------------------------------------
  1046. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1047. TQueryType & Type, bool Force)
  1048. {
  1049. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1050. DebugAssert(Updates.HaveResults);
  1051. if (Updates.HaveResults)
  1052. {
  1053. if (Updates.Results.Disabled)
  1054. {
  1055. New = false;
  1056. if (Force)
  1057. {
  1058. Message = LoadStr(UPDATE_DISABLED);
  1059. }
  1060. }
  1061. else
  1062. {
  1063. New = (Updates.Results.Version > 0);
  1064. if (New)
  1065. {
  1066. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1067. if (!Updates.Results.Release.IsEmpty())
  1068. {
  1069. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1070. }
  1071. Message = FMTLOAD(NEW_VERSION4, (Version));
  1072. }
  1073. else
  1074. {
  1075. Message = LoadStr(NO_NEW_VERSION);
  1076. }
  1077. }
  1078. if (!Message.IsEmpty())
  1079. {
  1080. Message = MainInstructions(Message);
  1081. }
  1082. if (!Updates.Results.Message.IsEmpty())
  1083. {
  1084. Message +=
  1085. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1086. }
  1087. if (!Updates.Results.AuthenticationError.IsEmpty())
  1088. {
  1089. Message +=
  1090. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1091. }
  1092. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1093. }
  1094. else
  1095. {
  1096. New = false;
  1097. }
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1101. {
  1102. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall EnableAutomaticUpdates()
  1106. {
  1107. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/, unsigned int & /*Answer*/)
  1111. {
  1112. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1113. OpenBrowser(LoadStr(HISTORY_URL));
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1117. {
  1118. return static_cast<int>(Size / 1024);
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. class TUpdateDownloadThread : public TCompThread
  1122. {
  1123. public:
  1124. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1125. virtual __fastcall ~TUpdateDownloadThread();
  1126. void __fastcall CancelClicked(TObject * Sender);
  1127. bool __fastcall CancelDownload();
  1128. __property bool Done = { read = FDone };
  1129. protected:
  1130. virtual void __fastcall Execute();
  1131. void __fastcall UpdateDownloaded();
  1132. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1133. void __fastcall UpdateProgress();
  1134. void __fastcall ShowException();
  1135. void __fastcall DownloadNotVerified();
  1136. void __fastcall CancelForm();
  1137. private:
  1138. TCustomForm * FForm;
  1139. TProgressBar * FProgressBar;
  1140. __int64 FDownloaded;
  1141. std::unique_ptr<Exception> FException;
  1142. std::unique_ptr<THttp> FHttp;
  1143. TUpdatesConfiguration FUpdates;
  1144. bool FDone;
  1145. };
  1146. //---------------------------------------------------------------------------
  1147. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1148. TCompThread(true)
  1149. {
  1150. // cache, as the progress bar miht be destroyed already when
  1151. // we need the form at the end of Execute()
  1152. FForm = GetParentForm(ProgressBar);
  1153. FProgressBar = ProgressBar;
  1154. // cache to prevent concurrency
  1155. FUpdates = WinConfiguration->Updates;
  1156. FDone = false;
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1160. {
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TUpdateDownloadThread::Execute()
  1164. {
  1165. try
  1166. {
  1167. bool Retried = false;
  1168. bool Retry;
  1169. do
  1170. {
  1171. Retry = false;
  1172. try
  1173. {
  1174. FDownloaded = 0;
  1175. FHttp.reset(CreateHttp(FUpdates));
  1176. FHttp->URL = FUpdates.Results.DownloadUrl;
  1177. FHttp->OnDownload = HttpDownload;
  1178. FHttp->Get();
  1179. }
  1180. catch (EAbort &)
  1181. {
  1182. throw;
  1183. }
  1184. catch (Exception & E)
  1185. {
  1186. // The original URL failed, try to get a fresh one and retry
  1187. if (!Retried)
  1188. {
  1189. try
  1190. {
  1191. // Check if new update data (URL particlarly) is available
  1192. if (QueryUpdates(FUpdates) &&
  1193. !FUpdates.Results.DownloadUrl.IsEmpty())
  1194. {
  1195. Retry = true;
  1196. Retried = true;
  1197. }
  1198. }
  1199. catch (...)
  1200. {
  1201. }
  1202. }
  1203. if (!Retry)
  1204. {
  1205. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1206. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1207. }
  1208. }
  1209. }
  1210. while (Retry);
  1211. Synchronize(UpdateDownloaded);
  1212. }
  1213. catch (EAbort &)
  1214. {
  1215. // noop
  1216. }
  1217. catch (Exception & E)
  1218. {
  1219. Configuration->Usage->Inc(L"UpdateFailures");
  1220. FException.reset(CloneException(&E));
  1221. Synchronize(ShowException);
  1222. }
  1223. FDone = true;
  1224. Synchronize(CancelForm);
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. void __fastcall TUpdateDownloadThread::CancelForm()
  1228. {
  1229. FForm->ModalResult = mrCancel;
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1233. {
  1234. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1235. const char * Buffer = FHttp->ResponseRaw.c_str();
  1236. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1237. {
  1238. DownloadNotVerified();
  1239. }
  1240. UnicodeString Digest = Sha256(Buffer, Size);
  1241. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1242. {
  1243. DownloadNotVerified();
  1244. }
  1245. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1246. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1247. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1248. UnicodeString SetupPath = SetupPathBase;
  1249. int Index = 0;
  1250. while (FileExists(SetupPath))
  1251. {
  1252. Index++;
  1253. SetupPath =
  1254. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1255. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1256. }
  1257. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1258. FileStream->Write(Buffer, Size);
  1259. FileStream.reset(NULL);
  1260. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1261. if (FUpdates.Results.OpenGettingStarted)
  1262. {
  1263. Params += L" /OpenGettingStarted";
  1264. }
  1265. ExecuteShellChecked(SetupPath, Params);
  1266. Configuration->Usage->Inc(L"UpdateRuns");
  1267. TerminateApplication();
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1271. {
  1272. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1273. }
  1274. //---------------------------------------------------------------------------
  1275. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1276. {
  1277. FDownloaded = Size;
  1278. Synchronize(UpdateProgress);
  1279. // Do not waste bandwidth, if something goes wrong
  1280. if (FDownloaded > FUpdates.Results.DownloadSize)
  1281. {
  1282. DownloadNotVerified();
  1283. }
  1284. if (Terminated)
  1285. {
  1286. Cancel = true;
  1287. }
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1291. {
  1292. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TUpdateDownloadThread::ShowException()
  1296. {
  1297. DebugAssert(FException.get() != NULL);
  1298. ShowExtendedException(FException.get());
  1299. }
  1300. //---------------------------------------------------------------------------
  1301. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1302. {
  1303. bool Result = !Terminated;
  1304. if (Result)
  1305. {
  1306. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1307. Terminate();
  1308. }
  1309. return Result;
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1313. {
  1314. if (CancelDownload())
  1315. {
  1316. WaitFor();
  1317. }
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. //---------------------------------------------------------------------------
  1321. class TUpdateDownloadData : public TComponent
  1322. {
  1323. public:
  1324. TUpdateDownloadThread * Thread;
  1325. __fastcall TUpdateDownloadData() :
  1326. TComponent(NULL)
  1327. {
  1328. }
  1329. virtual __fastcall ~TUpdateDownloadData()
  1330. {
  1331. // will stop the thread
  1332. delete Thread;
  1333. }
  1334. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1335. {
  1336. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1337. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1338. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1339. }
  1340. };
  1341. //---------------------------------------------------------------------------
  1342. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1343. {
  1344. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1345. // If the form was closed by CancelForm at the end of the thread, do nothing
  1346. if (!UpdateDownloadData->Thread->Done)
  1347. {
  1348. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1349. // May this should actually call CancelClicked?
  1350. if (UpdateDownloadData->Thread->CancelDownload())
  1351. {
  1352. Action = caNone;
  1353. }
  1354. }
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender, unsigned int & /*Answer*/)
  1358. {
  1359. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1360. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1361. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1362. TPanel * Panel = CreateBlankPanel(Form);
  1363. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1364. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1365. ProgressBar->Top = 0;
  1366. ProgressBar->Left = 0;
  1367. ProgressBar->Width = Panel->Width;
  1368. ProgressBar->Parent = Panel;
  1369. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1370. Panel->Height = ProgressBar->Height;
  1371. InsertPanelToMessageDialog(Form, Panel);
  1372. Button->Enabled = false;
  1373. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1374. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1375. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1376. // The form becomes owner of the thread (via TUpdateDownloadData),
  1377. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1378. // But it gets done only after the form controls are gone, and the thread
  1379. // might try to access them meanwhile. So we stop the thread explicitly.
  1380. CancelButton->OnClick = Thread->CancelClicked;
  1381. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1382. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1383. Data->Thread = Thread;
  1384. Form->InsertComponent(Data);
  1385. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1386. if (!DownloadingUrl.IsEmpty())
  1387. {
  1388. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1389. }
  1390. DebugAssert(Form->OnClose == NULL);
  1391. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1392. Thread->Resume();
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1396. {
  1397. EnableAutomaticUpdates();
  1398. }
  1399. //---------------------------------------------------------------------------
  1400. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1401. {
  1402. const UnicodeString DonatePanelName = L"DonatePanel";
  1403. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1404. // OnShow can happen multiple times, for example when showing dialog on start up (being main window)
  1405. if (FindComponentRecursively(Dialog, DonatePanelName) == NULL)
  1406. {
  1407. TPanel * Panel = CreateBlankPanel(Dialog);
  1408. Panel->Name = DonatePanelName;
  1409. Panel->Caption = UnicodeString(); // override default use of Name
  1410. TStaticText * StaticText = new TStaticText(Panel);
  1411. StaticText->Top = 0;
  1412. StaticText->Left = 0;
  1413. StaticText->AutoSize = true;
  1414. StaticText->Caption = LoadStr(UPDATES_DONATE_LINK);
  1415. StaticText->Parent = Panel;
  1416. StaticText->OnClick = MakeMethod<TNotifyEvent>(NULL, UpdatesDonateClick);
  1417. StaticText->TabStop = true;
  1418. LinkLabel(StaticText);
  1419. Panel->Height = StaticText->Height;
  1420. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1421. // (what should not happen)
  1422. InsertPanelToMessageDialog(Dialog, Panel);
  1423. }
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. bool __fastcall CheckForUpdates(bool CachedResults)
  1427. {
  1428. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1429. bool Result = false;
  1430. TOperationVisualizer Visualizer;
  1431. try
  1432. {
  1433. if (ActiveForm)
  1434. {
  1435. DebugAssert(ActiveForm->Enabled);
  1436. ActiveForm->Enabled = false;
  1437. }
  1438. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1439. bool Cached =
  1440. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1441. CachedResults;
  1442. if (!Cached)
  1443. {
  1444. DoQueryUpdates(WinConfiguration->CollectUsage);
  1445. // reread new data
  1446. Updates = WinConfiguration->Updates;
  1447. }
  1448. if (!Updates.ShownResults)
  1449. {
  1450. Updates.ShownResults = true;
  1451. WinConfiguration->Updates = Updates;
  1452. }
  1453. DebugAssert(Updates.HaveResults);
  1454. UnicodeString Message;
  1455. bool New;
  1456. TQueryType Type;
  1457. GetUpdatesMessage(Message, New, Type, true);
  1458. Configuration->Usage->Inc(L"UpdateDisplays");
  1459. if (New)
  1460. {
  1461. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1462. }
  1463. if (Updates.HaveResults &&
  1464. (double(Updates.Period) > 0) &&
  1465. // do not chow next check time, if we have new version info
  1466. !New)
  1467. {
  1468. Message += L"\n\n" +
  1469. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1470. }
  1471. int Answers = qaOK |
  1472. // show "what's new" button only when change list URL was not provided in results
  1473. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1474. FLAGMASK(New, qaCancel) |
  1475. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1476. TQueryButtonAlias Aliases[4];
  1477. Aliases[0].Button = qaYes;
  1478. if (Updates.Results.UrlButton.IsEmpty())
  1479. {
  1480. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1481. }
  1482. else
  1483. {
  1484. Aliases[0].Alias = Updates.Results.UrlButton;
  1485. }
  1486. Aliases[1].Button = qaAll;
  1487. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1488. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, OpenHistory);
  1489. Aliases[2].Button = qaCancel;
  1490. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1491. // Used only when New == true, see AliasesCount below
  1492. Aliases[3].Button = qaOK;
  1493. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1494. if (!Updates.Results.DownloadUrl.IsEmpty())
  1495. {
  1496. Aliases[3].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, DownloadUpdate);
  1497. Aliases[3].ElevationRequired = true;
  1498. }
  1499. TMessageParams Params;
  1500. Params.Aliases = Aliases;
  1501. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1502. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1503. // alias "ok" button to "upgrade" only if we have new version
  1504. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1505. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1506. if (New)
  1507. {
  1508. Params.ImageName = L"Installer";
  1509. }
  1510. std::unique_ptr<TForm> Dialog(
  1511. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1512. if (New)
  1513. {
  1514. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1515. {
  1516. DebugAssert(Dialog->OnShow == NULL);
  1517. // InsertDonateLink need to be called only after MessageBrowser is created
  1518. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1519. }
  1520. }
  1521. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1522. switch (Answer)
  1523. {
  1524. case qaOK:
  1525. if (New)
  1526. {
  1527. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1528. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1529. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1530. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1531. OpenBrowser(UpgradeUrl);
  1532. Result = true;
  1533. }
  1534. break;
  1535. case qaYes:
  1536. OpenBrowser(Updates.Results.Url);
  1537. break;
  1538. case qaAll:
  1539. DebugFail();
  1540. break;
  1541. }
  1542. }
  1543. __finally
  1544. {
  1545. if (ActiveForm)
  1546. {
  1547. ActiveForm->Enabled = true;
  1548. }
  1549. }
  1550. return Result;
  1551. }
  1552. //---------------------------------------------------------------------------
  1553. class TUpdateThread : public TCompThread
  1554. {
  1555. public:
  1556. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1557. protected:
  1558. virtual void __fastcall Execute();
  1559. TThreadMethod FOnUpdatesChecked;
  1560. };
  1561. //---------------------------------------------------------------------------
  1562. TUpdateThread * UpdateThread = NULL;
  1563. //---------------------------------------------------------------------------
  1564. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1565. TCompThread(false),
  1566. FOnUpdatesChecked(OnUpdatesChecked)
  1567. {
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. void __fastcall TUpdateThread::Execute()
  1571. {
  1572. try
  1573. {
  1574. DoQueryUpdates(WinConfiguration->CollectUsage);
  1575. if (FOnUpdatesChecked != NULL)
  1576. {
  1577. Synchronize(FOnUpdatesChecked);
  1578. }
  1579. }
  1580. catch(...)
  1581. {
  1582. // ignore errors
  1583. }
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1587. {
  1588. DebugAssert(UpdateThread == NULL);
  1589. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. void __fastcall StopUpdateThread()
  1593. {
  1594. if (UpdateThread != NULL)
  1595. {
  1596. SAFE_DESTROY(UpdateThread);
  1597. }
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. void __fastcall SetupInitialize()
  1601. {
  1602. WinConfiguration->UpdateJumpList();
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1606. UnicodeString AdditionalParams, TStringList * Removed,
  1607. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1608. int IconIndex)
  1609. {
  1610. bool Result = false;
  1611. IObjectCollection * Collection = NULL;
  1612. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1613. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1614. {
  1615. try
  1616. {
  1617. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1618. int Count = 0;
  1619. for (int Index = 0; Index < Names->Count; Index++)
  1620. {
  1621. IShellLink * Link =
  1622. CreateDesktopSessionShortCut(
  1623. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1624. wchar_t Desc[2048];
  1625. if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1626. {
  1627. if (Removed->IndexOf(Desc) < 0)
  1628. {
  1629. try
  1630. {
  1631. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1632. Count++;
  1633. }
  1634. __finally
  1635. {
  1636. Link->Release();
  1637. }
  1638. }
  1639. else
  1640. {
  1641. Names->Delete(Index);
  1642. Index--;
  1643. }
  1644. }
  1645. }
  1646. if (Count > 0)
  1647. {
  1648. IObjectArray * Array;
  1649. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1650. {
  1651. try
  1652. {
  1653. Result = SUCCEEDED(
  1654. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1655. }
  1656. __finally
  1657. {
  1658. Array->Release();
  1659. }
  1660. }
  1661. }
  1662. }
  1663. __finally
  1664. {
  1665. Collection->Release();
  1666. }
  1667. }
  1668. return Result;
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1672. {
  1673. ICustomDestinationList * DestinationList = NULL;
  1674. IObjectArray * RemovedArray = NULL;
  1675. TStringList * Removed = NULL;
  1676. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1677. try
  1678. {
  1679. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1680. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1681. {
  1682. unsigned int MinSlots;
  1683. unsigned int * PMinSlots = &MinSlots;
  1684. void ** PRemovedArray = (void**)&RemovedArray;
  1685. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1686. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1687. {
  1688. Removed = new TStringList();
  1689. unsigned int RemovedCount;
  1690. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1691. {
  1692. RemovedCount = 0;
  1693. }
  1694. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1695. {
  1696. IShellLink * Link;
  1697. wchar_t Desc[2048];
  1698. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1699. SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1700. {
  1701. Removed->Add(Desc);
  1702. }
  1703. }
  1704. AddJumpListCategory(
  1705. WorkspaceNames, L"", Removed, DestinationList,
  1706. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1707. AddJumpListCategory(
  1708. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1709. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1710. if (DestinationList != NULL)
  1711. {
  1712. DestinationList->CommitList();
  1713. }
  1714. }
  1715. }
  1716. }
  1717. __finally
  1718. {
  1719. SetErrorMode(OldErrMode);
  1720. if (RemovedArray != NULL)
  1721. {
  1722. RemovedArray->Release();
  1723. }
  1724. if (DestinationList != NULL)
  1725. {
  1726. DestinationList->Release();
  1727. }
  1728. delete Removed;
  1729. }
  1730. }
  1731. //---------------------------------------------------------------------------
  1732. bool __fastcall AnyOtherInstanceOfSelf()
  1733. {
  1734. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1735. bool Result = false;
  1736. try
  1737. {
  1738. unsigned int Process = GetCurrentProcessId();
  1739. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1740. PROCESSENTRY32 ProcessEntry;
  1741. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1742. if (Process32First(Snapshot, &ProcessEntry))
  1743. {
  1744. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1745. {
  1746. // we should check if the process is running in the same session,
  1747. // but for that we probably need some special privileges
  1748. if ((Process != ProcessEntry.th32ProcessID) &&
  1749. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1750. {
  1751. Result = true;
  1752. }
  1753. }
  1754. }
  1755. }
  1756. __finally
  1757. {
  1758. CloseHandle(Snapshot);
  1759. }
  1760. return Result;
  1761. }
  1762. //---------------------------------------------------------------------------
  1763. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1764. {
  1765. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1766. Registry->RootKey = RootKey;
  1767. bool Result =
  1768. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1769. if (Result)
  1770. {
  1771. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1772. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1773. Result =
  1774. !InstallPath.IsEmpty() &&
  1775. IsPathToSameFile(ExePath, InstallPath);
  1776. }
  1777. return Result;
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. bool __fastcall IsInstalled()
  1781. {
  1782. return
  1783. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1784. DoIsInstalled(HKEY_CURRENT_USER);
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1788. {
  1789. std::unique_ptr<TStringList> List(new TStringList());
  1790. List->CommaText = Text;
  1791. return List.release();
  1792. }
  1793. //---------------------------------------------------------------------------
  1794. UnicodeString __fastcall FirstUnshownTip()
  1795. {
  1796. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1797. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1798. Tips->CaseSensitive = false;
  1799. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1800. TipsSeen->CaseSensitive = false;
  1801. int LastTipSeen = -1;
  1802. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1803. {
  1804. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1805. if (TipIndex >= 0)
  1806. {
  1807. LastTipSeen = TipIndex;
  1808. }
  1809. }
  1810. UnicodeString Result;
  1811. if (LastTipSeen < Tips->Count - 1)
  1812. {
  1813. Result = Tips->Strings[LastTipSeen + 1];
  1814. }
  1815. return Result;
  1816. }
  1817. //---------------------------------------------------------------------------
  1818. class TTipsData : public TComponent
  1819. {
  1820. public:
  1821. __fastcall TTipsData() :
  1822. TComponent(NULL)
  1823. {
  1824. }
  1825. int Index;
  1826. TStringList * Tips;
  1827. static TTipsData * __fastcall Retrieve(TObject * Object)
  1828. {
  1829. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1830. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1831. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1832. }
  1833. };
  1834. //---------------------------------------------------------------------------
  1835. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1836. {
  1837. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1841. {
  1842. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1843. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(YesButtonName)));
  1844. PrevButton->Enabled = (TipsData->Index > 0);
  1845. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1846. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1847. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(FindComponentRecursively(Form, MainMessageLabelName)));
  1848. MessageLabel->Caption = TipsMessage(TipsData);
  1849. }
  1850. //---------------------------------------------------------------------------
  1851. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1852. {
  1853. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1854. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1855. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. static void __fastcall TipSeen(const UnicodeString & Tip)
  1859. {
  1860. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1861. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1862. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1863. WinConfiguration->TipsShown = Now();
  1864. WinConfiguration->RunsSinceLastTip = 0;
  1865. // prevent parallel app instances showing the same tip
  1866. WinConfiguration->Save();
  1867. }
  1868. //---------------------------------------------------------------------------
  1869. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender, unsigned int & /*Answer*/)
  1870. {
  1871. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1872. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1873. TipsData->Index += reinterpret_cast<int>(Data);
  1874. UpdateTipsForm(Form);
  1875. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1876. UnicodeString Url = TipUrl(TipsData);
  1877. NavigateMessageDialogToUrl(Form, Url);
  1878. }
  1879. //---------------------------------------------------------------------------
  1880. static void __fastcall ShowTip(bool AutoShow)
  1881. {
  1882. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1883. UnicodeString Tip = FirstUnshownTip();
  1884. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1885. Tips->CaseSensitive = false;
  1886. int Index;
  1887. if (Tip.IsEmpty())
  1888. {
  1889. Index = Tips->Count - 1;
  1890. Tip = Tips->Strings[Index];
  1891. }
  1892. else
  1893. {
  1894. Index = Tips->IndexOf(Tip);
  1895. }
  1896. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1897. TipsData->Name = TTipsData::QualifiedClassName();
  1898. TipsData->Index = Index;
  1899. TipsData->Tips = Tips.get();
  1900. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1901. TQueryButtonAlias Aliases[3];
  1902. Aliases[0].Button = qaYes;
  1903. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1904. Aliases[0].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1905. Aliases[1].Button = qaNo;
  1906. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1907. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1908. Aliases[2].Button = qaCancel;
  1909. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1910. TMessageParams Params;
  1911. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1912. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1913. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1914. Params.Aliases = Aliases;
  1915. Params.AliasesCount = LENOF(Aliases);
  1916. Params.ImageName = L"Bulb On n p";
  1917. if (AutoShow)
  1918. {
  1919. // Won't be used automatically as we have more than the "OK" button
  1920. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1921. Params.NeverAskAgainAnswer = qaCancel;
  1922. Params.Params |= mpNeverAskAgainCheck;
  1923. }
  1924. int Answers = qaYes | qaNo | qaCancel;
  1925. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1926. Dialog->InsertComponent(TipsData.release());
  1927. UpdateTipsForm(Dialog.get());
  1928. TipSeen(Tip);
  1929. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1930. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1931. {
  1932. WinConfiguration->ShowTips = false;
  1933. }
  1934. WinConfiguration->Updates = Updates;
  1935. }
  1936. //---------------------------------------------------------------------------
  1937. void __fastcall AutoShowNewTip()
  1938. {
  1939. Configuration->Usage->Inc(L"TipsShownAuto");
  1940. ShowTip(true);
  1941. }
  1942. //---------------------------------------------------------------------------
  1943. void __fastcall ShowTips()
  1944. {
  1945. {
  1946. TOperationVisualizer Visualizer;
  1947. DoQueryUpdates(false);
  1948. }
  1949. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1950. {
  1951. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1952. }
  1953. Configuration->Usage->Inc(L"TipsShownCommand");
  1954. ShowTip(false);
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. void __fastcall TipsUpdateStaticUsage()
  1958. {
  1959. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1960. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1961. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1962. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1963. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1964. }
  1965. //---------------------------------------------------------------------------
  1966. static void ReadNetVersion(TRegistryStorage * Registry)
  1967. {
  1968. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  1969. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  1970. {
  1971. NetVersionStr = VersionStr;
  1972. }
  1973. }
  1974. //---------------------------------------------------------------------------
  1975. UnicodeString __fastcall GetNetVersionStr()
  1976. {
  1977. if (NetVersionStr.IsEmpty())
  1978. {
  1979. NetVersionStr = L"0"; // not to retry on failure
  1980. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  1981. if (Registry->OpenRootKey(false))
  1982. {
  1983. std::unique_ptr<TStringList> Keys(new TStringList());
  1984. Registry->GetSubKeyNames(Keys.get());
  1985. for (int Index = 0; Index < Keys->Count; Index++)
  1986. {
  1987. UnicodeString Key = Keys->Strings[Index];
  1988. if (Registry->OpenSubKey(Key, false))
  1989. {
  1990. ReadNetVersion(Registry.get());
  1991. if (Registry->OpenSubKey(L"Full", false))
  1992. {
  1993. ReadNetVersion(Registry.get());
  1994. Registry->CloseSubKey();
  1995. }
  1996. if (Registry->OpenSubKey(L"Client", false))
  1997. {
  1998. ReadNetVersion(Registry.get());
  1999. Registry->CloseSubKey();
  2000. }
  2001. Registry->CloseSubKey();
  2002. }
  2003. }
  2004. }
  2005. }
  2006. return NetVersionStr;
  2007. }
  2008. //---------------------------------------------------------------------------
  2009. UnicodeString __fastcall GetPowerShellVersionStr()
  2010. {
  2011. if (PowerShellVersionStr.IsEmpty())
  2012. {
  2013. PowerShellVersionStr = 0; // not to retry on failure
  2014. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2015. if (Registry->OpenRootKey(false))
  2016. {
  2017. std::unique_ptr<TStringList> Keys(new TStringList());
  2018. Registry->GetSubKeyNames(Keys.get());
  2019. for (int Index = 0; Index < Keys->Count; Index++)
  2020. {
  2021. UnicodeString Key = Keys->Strings[Index];
  2022. if (Registry->OpenSubKey(Key + L"\\PowerShellEngine", false, true))
  2023. {
  2024. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2025. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2026. {
  2027. PowerShellVersionStr = VersionStr;
  2028. }
  2029. Registry->CloseSubKey();
  2030. }
  2031. }
  2032. }
  2033. }
  2034. return PowerShellVersionStr;
  2035. }