Setup.cpp 72 KB

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