Setup.cpp 71 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. //---------------------------------------------------------------------------
  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. }
  442. //---------------------------------------------------------------------------
  443. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  444. {
  445. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  446. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  447. UnregisterAsUrlHandler(Prefix + WebDAVProtocol, UnregisterProtocol);
  448. UnregisterAsUrlHandler(Prefix + WebDAVSProtocol, UnregisterProtocol);
  449. }
  450. //---------------------------------------------------------------------------
  451. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  452. //---------------------------------------------------------------------------
  453. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  454. {
  455. // Register protocol, if it does not exist yet.
  456. // Prior to Windows 8, we need to register ourselves as legacy handler to
  457. // become the default handler. On Windows 8, it's automatic as long as no other
  458. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  459. RegisterAsUrlHandler(RootKey, Protocol);
  460. // see https://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
  461. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  462. // create capabilities record
  463. // this has to be a separate branch from WinSCP one, as by its presence we
  464. // enforce registry storage usage, and the capabilities branch may exist
  465. // even if we are using INI file
  466. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  467. if (!Registry->OpenKey(CapabilitiesKey, true))
  468. {
  469. Abort();
  470. }
  471. UnicodeString Description = LoadStr(REGISTERED_APP_DESC2);
  472. Registry->WriteString(L"ApplicationDescription", Description);
  473. if (!Registry->OpenKey(L"UrlAssociations", true))
  474. {
  475. Abort();
  476. }
  477. Registry->WriteString(Protocol, GenericUrlHandler);
  478. Registry->CloseKey();
  479. // register application
  480. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  481. {
  482. Abort();
  483. }
  484. Registry->WriteString(AppNameString(), CapabilitiesKey);
  485. Registry->CloseKey();
  486. }
  487. //---------------------------------------------------------------------------
  488. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  489. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  490. {
  491. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  492. // unregister the protocol
  493. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  494. // remove capabilities record
  495. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  496. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  497. if (Registry->OpenKey(UrlAssociationsKey, false))
  498. {
  499. Registry->DeleteValue(Protocol);
  500. Registry->CloseKey();
  501. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  502. }
  503. if (Registry->OpenKey(CapabilitiesKey, false))
  504. {
  505. if (!Registry->HasSubKeys())
  506. {
  507. Registry->DeleteValue(L"ApplicationDescription");
  508. }
  509. Registry->CloseKey();
  510. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  511. }
  512. if (!Registry->KeyExists(CapabilitiesKey))
  513. {
  514. // unregister application
  515. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  516. {
  517. Registry->DeleteValue(AppNameString());
  518. Registry->CloseKey();
  519. }
  520. }
  521. }
  522. //---------------------------------------------------------------------------
  523. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  524. {
  525. // register URL handler, if it does not exist yet
  526. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  527. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  528. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  529. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  530. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  531. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  532. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  533. RegisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol);
  534. RegisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol);
  535. // deliberately not including http,
  536. // it's unlikely that anyone would like to change http handler
  537. // to non-browser application
  538. }
  539. //---------------------------------------------------------------------------
  540. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  541. {
  542. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  543. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  544. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  545. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  546. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  547. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol, ForceHandlerUnregistration);
  548. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol, ForceHandlerUnregistration);
  549. // we should not really need the "force" flag here, but why not
  550. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  551. }
  552. //---------------------------------------------------------------------------
  553. static void __fastcall RegisterForDefaultPrograms()
  554. {
  555. try
  556. {
  557. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  558. // make sure we unregister any legacy protocol handler for CU,
  559. // this is needed for Windows Vista+7
  560. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  561. }
  562. catch (Exception & E)
  563. {
  564. try
  565. {
  566. // Maybe we should skip this if HKLM key existed already (we are running non-privileged)
  567. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  568. }
  569. catch (Exception & E)
  570. {
  571. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  572. }
  573. }
  574. }
  575. //---------------------------------------------------------------------------
  576. static void __fastcall NotifyChangedAssociations()
  577. {
  578. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall RegisterForDefaultProtocols()
  582. {
  583. if (IsWinVista())
  584. {
  585. RegisterForDefaultPrograms();
  586. }
  587. else
  588. {
  589. RegisterAsNonBrowserUrlHandler(UnicodeString());
  590. }
  591. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  592. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  593. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  594. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  595. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  596. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  597. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  598. NotifyChangedAssociations();
  599. }
  600. //---------------------------------------------------------------------------
  601. void __fastcall UnregisterForProtocols()
  602. {
  603. UnregisterAsUrlHandlers(UnicodeString(), false);
  604. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  605. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  606. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  607. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  608. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  609. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  610. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  611. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  612. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  613. NotifyChangedAssociations();
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall LaunchAdvancedAssociationUI()
  617. {
  618. DebugAssert(IsWinVista());
  619. RegisterForDefaultPrograms();
  620. NotifyChangedAssociations();
  621. // sleep recommended by https://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  622. Sleep(1000);
  623. if (IsWin10())
  624. {
  625. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  626. // https://stackoverflow.com/q/32178986/850848
  627. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  628. IOpenControlPanel * OpenControlPanel;
  629. HRESULT Result =
  630. CoCreateInstance(CLSID_OpenControlPanel,
  631. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  632. if (SUCCEEDED(Result))
  633. {
  634. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  635. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  636. OpenControlPanel->Release();
  637. }
  638. }
  639. else
  640. {
  641. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  642. HRESULT Result =
  643. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  644. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  645. if (SUCCEEDED(Result))
  646. {
  647. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  648. AppAssocRegUI->Release();
  649. }
  650. }
  651. }
  652. //---------------------------------------------------------------------------
  653. void __fastcall TemporaryDirectoryCleanup()
  654. {
  655. bool Continue = true;
  656. TStrings * Folders = NULL;
  657. try
  658. {
  659. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  660. {
  661. Folders = WinConfiguration->FindTemporaryFolders();
  662. Continue = (Folders != NULL);
  663. if (Continue)
  664. {
  665. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  666. TQueryButtonAlias Aliases[1];
  667. Aliases[0].Button = qaRetry;
  668. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  669. TMessageParams Params(mpNeverAskAgainCheck);
  670. Params.Aliases = Aliases;
  671. Params.AliasesCount = LENOF(Aliases);
  672. unsigned int Answer = MoreMessageDialog(
  673. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  674. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  675. if (Answer == qaNeverAskAgain)
  676. {
  677. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  678. Answer = qaYes;
  679. }
  680. else if (Answer == qaRetry)
  681. {
  682. for (int Index = 0; Index < Folders->Count; Index++)
  683. {
  684. ShellExecute(Application->Handle, NULL,
  685. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  686. }
  687. }
  688. Continue = (Answer == qaYes);
  689. }
  690. }
  691. if (Continue)
  692. {
  693. try
  694. {
  695. WinConfiguration->CleanupTemporaryFolders(Folders);
  696. }
  697. catch (Exception &E)
  698. {
  699. ShowExtendedException(&E);
  700. }
  701. }
  702. }
  703. __finally
  704. {
  705. delete Folders;
  706. }
  707. }
  708. //-------------------------------------------- -------------------------------
  709. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  710. {
  711. int MajorVer = Version / (10000*100*100);
  712. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  713. int Release = (Version % (10000*100)) / (10000);
  714. UnicodeString Result;
  715. if (Release > 0)
  716. {
  717. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  718. }
  719. else
  720. {
  721. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  722. }
  723. return Result;
  724. }
  725. //---------------------------------------------------------------------------
  726. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  727. {
  728. int CurrentCompoundVer = Configuration->CompoundVersion;
  729. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  730. // Beware that these parameters may get truncated if URL is too long,
  731. // such as with ERROR_REPORT_URL2
  732. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  733. return AppendUrlParams(URL, Params);
  734. }
  735. //---------------------------------------------------------------------------
  736. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  737. {
  738. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  739. UnicodeString CurrentVersionStr =
  740. FORMAT(L"%d.%d.%d.%d",
  741. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  742. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  743. UnicodeString Params =
  744. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  745. (CurrentVersionStr,
  746. GUIConfiguration->AppliedLocaleHex,
  747. int(IsInstalled())));
  748. if (Configuration->IsUnofficial)
  749. {
  750. Params += L"&unofficial=1";
  751. }
  752. return AppendUrlParams(URL, Params);
  753. }
  754. //---------------------------------------------------------------------------
  755. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  756. {
  757. bool Beta;
  758. if (WinConfiguration->IsBeta)
  759. {
  760. Beta = true;
  761. }
  762. else
  763. {
  764. switch (WinConfiguration->Updates.BetaVersions)
  765. {
  766. case asAuto:
  767. Beta = WinConfiguration->AnyBetaInVersionHistory;
  768. break;
  769. case asOn:
  770. Beta = true;
  771. break;
  772. default:
  773. Beta = false;
  774. break;
  775. }
  776. }
  777. if (Beta || Force)
  778. {
  779. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  780. }
  781. return URL;
  782. }
  783. //---------------------------------------------------------------------------
  784. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  785. {
  786. std::unique_ptr<THttp> Http(new THttp());
  787. UnicodeString ProxyHost;
  788. int ProxyPort = 0;
  789. switch (Updates.ConnectionType)
  790. {
  791. case ctAuto:
  792. if (AutodetectProxy(ProxyHost, ProxyPort))
  793. {
  794. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  795. }
  796. break;
  797. case ctProxy:
  798. ProxyHost = Updates.ProxyHost;
  799. ProxyPort = Updates.ProxyPort;
  800. Configuration->Usage->Inc(L"UpdateProxyManual");
  801. break;
  802. }
  803. Http->ProxyHost = ProxyHost;
  804. Http->ProxyPort = ProxyPort;
  805. return Http.release();
  806. }
  807. //---------------------------------------------------------------------------
  808. THttp * __fastcall CreateHttp()
  809. {
  810. return CreateHttp(WinConfiguration->Updates);
  811. }
  812. //---------------------------------------------------------------------------
  813. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  814. {
  815. bool Complete = false;
  816. UnicodeString Response;
  817. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  818. try
  819. {
  820. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  821. URL = WantBetaUrl(URL, false);
  822. URL += L"&dotnet=" + Updates.DotNetVersion;
  823. URL += L"&console=" + Updates.ConsoleVersion;
  824. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  825. if (!LocaleVersion.IsEmpty())
  826. {
  827. URL += L"&localever=" + LocaleVersion;
  828. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  829. }
  830. if (!Updates.AuthenticationEmail.IsEmpty())
  831. {
  832. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  833. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  834. }
  835. CheckForUpdatesHTTP->URL = URL;
  836. // sanity check
  837. CheckForUpdatesHTTP->ResponseLimit = 102400;
  838. try
  839. {
  840. if (CollectUsage)
  841. {
  842. UnicodeString Usage = Configuration->Usage->Serialize();
  843. CheckForUpdatesHTTP->Post(Usage);
  844. }
  845. else
  846. {
  847. CheckForUpdatesHTTP->Get();
  848. }
  849. }
  850. catch (...)
  851. {
  852. if (CheckForUpdatesHTTP->IsCertificateError())
  853. {
  854. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  855. }
  856. throw;
  857. }
  858. Response = CheckForUpdatesHTTP->Response;
  859. }
  860. __finally
  861. {
  862. delete CheckForUpdatesHTTP;
  863. }
  864. int CurrentCompoundVer = Configuration->CompoundVersion;
  865. bool Changed = !Updates.HaveResults;
  866. Updates.LastCheck = Now();
  867. Updates.HaveResults = true;
  868. TUpdatesData PrevResults = Updates.Results;
  869. Updates.Results.Reset();
  870. Updates.Results.ForVersion = CurrentCompoundVer;
  871. while (!Response.IsEmpty())
  872. {
  873. UnicodeString Line = CutToChar(Response, L'\n', false);
  874. UnicodeString Name = CutToChar(Line, L'=', false);
  875. if (SameText(Name, "Version"))
  876. {
  877. int NewVersion = StrToCompoundVersion(Line);
  878. Changed |= (NewVersion != PrevResults.Version);
  879. if (NewVersion <= CurrentCompoundVer)
  880. {
  881. NewVersion = 0;
  882. }
  883. Updates.Results.Version = NewVersion;
  884. Complete = true;
  885. }
  886. else if (SameText(Name, L"Message"))
  887. {
  888. Changed |= (PrevResults.Message != Line);
  889. Updates.Results.Message = Line;
  890. }
  891. else if (SameText(Name, L"Critical"))
  892. {
  893. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  894. Changed |= (PrevResults.Critical != NewCritical);
  895. Updates.Results.Critical = NewCritical;
  896. }
  897. else if (SameText(Name, L"Release"))
  898. {
  899. Changed |= (PrevResults.Release != Line);
  900. Updates.Results.Release = Line;
  901. }
  902. else if (SameText(Name, L"Disabled"))
  903. {
  904. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  905. Changed |= (PrevResults.Disabled != NewDisabled);
  906. Updates.Results.Disabled = NewDisabled;
  907. Complete = true;
  908. }
  909. else if (SameText(Name, L"Url"))
  910. {
  911. Changed |= (PrevResults.Url != Line);
  912. Updates.Results.Url = Line;
  913. }
  914. else if (SameText(Name, L"UrlButton"))
  915. {
  916. Changed |= (PrevResults.UrlButton != Line);
  917. Updates.Results.UrlButton = Line;
  918. }
  919. else if (SameText(Name, L"NewsUrl"))
  920. {
  921. Changed |= (PrevResults.NewsUrl != Line);
  922. Updates.Results.NewsUrl = Line;
  923. }
  924. else if (SameText(Name, L"NewsSize"))
  925. {
  926. TSize NewsSize;
  927. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  928. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  929. Changed |= (PrevResults.NewsSize != NewsSize);
  930. Updates.Results.NewsSize = NewsSize;
  931. }
  932. else if (SameText(Name, L"DownloadUrl"))
  933. {
  934. Changed |= (PrevResults.DownloadUrl != Line);
  935. Updates.Results.DownloadUrl = Line;
  936. }
  937. else if (SameText(Name, L"DownloadSize"))
  938. {
  939. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  940. }
  941. else if (SameText(Name, L"DownloadSha256"))
  942. {
  943. Updates.Results.DownloadSha256 = Line;
  944. }
  945. else if (SameText(Name, L"AuthenticationError"))
  946. {
  947. Changed |= (PrevResults.AuthenticationError != Line);
  948. Updates.Results.AuthenticationError = Line;
  949. }
  950. else if (SameText(Name, L"OpenGettingStarted"))
  951. {
  952. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  953. }
  954. else if (SameText(Name, L"DownloadingUrl"))
  955. {
  956. Updates.Results.DownloadingUrl = Line;
  957. }
  958. else if (SameText(Name, L"TipsSize"))
  959. {
  960. TSize TipsSize;
  961. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  962. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  963. Updates.Results.TipsSize = TipsSize;
  964. }
  965. else if (SameText(Name, L"TipsUrl"))
  966. {
  967. Updates.Results.TipsUrl = Line;
  968. }
  969. else if (SameText(Name, L"Tips"))
  970. {
  971. Updates.Results.Tips = Line;
  972. }
  973. else if (SameText(Name, L"TipsIntervalDays"))
  974. {
  975. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  976. if (TipsIntervalDays < 0)
  977. {
  978. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  979. }
  980. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  981. }
  982. else if (SameText(Name, L"TipsIntervalRuns"))
  983. {
  984. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  985. if (TipsIntervalRuns < 0)
  986. {
  987. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  988. }
  989. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  990. }
  991. }
  992. if (Changed)
  993. {
  994. Updates.ShownResults = false;
  995. }
  996. return Complete;
  997. }
  998. //---------------------------------------------------------------------------
  999. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1000. {
  1001. return DoQueryUpdates(Updates, false);
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1005. {
  1006. try
  1007. {
  1008. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1009. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1010. WinConfiguration->Updates = Updates;
  1011. if (!Complete)
  1012. {
  1013. EXCEPTION;
  1014. }
  1015. Configuration->Usage->Reset();
  1016. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1017. }
  1018. catch(Exception & E)
  1019. {
  1020. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1021. UnicodeString Message;
  1022. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1023. {
  1024. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1025. }
  1026. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1027. }
  1028. }
  1029. //---------------------------------------------------------------------------
  1030. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  1031. {
  1032. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1033. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1034. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1035. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  1036. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1037. Message = ReplaceStr(Message, L"|", L"\n");
  1038. return Message;
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1042. TQueryType & Type, bool Force)
  1043. {
  1044. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1045. DebugAssert(Updates.HaveResults);
  1046. if (Updates.HaveResults)
  1047. {
  1048. if (Updates.Results.Disabled)
  1049. {
  1050. New = false;
  1051. if (Force)
  1052. {
  1053. Message = LoadStr(UPDATE_DISABLED);
  1054. }
  1055. }
  1056. else
  1057. {
  1058. New = (Updates.Results.Version > 0);
  1059. if (New)
  1060. {
  1061. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1062. if (!Updates.Results.Release.IsEmpty())
  1063. {
  1064. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1065. }
  1066. Message = FMTLOAD(NEW_VERSION4, (Version));
  1067. }
  1068. else
  1069. {
  1070. Message = LoadStr(NO_NEW_VERSION);
  1071. }
  1072. }
  1073. if (!Message.IsEmpty())
  1074. {
  1075. Message = MainInstructions(Message);
  1076. }
  1077. if (!Updates.Results.Message.IsEmpty())
  1078. {
  1079. Message +=
  1080. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1081. }
  1082. if (!Updates.Results.AuthenticationError.IsEmpty())
  1083. {
  1084. Message +=
  1085. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1086. }
  1087. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1088. }
  1089. else
  1090. {
  1091. New = false;
  1092. }
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1096. {
  1097. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall EnableAutomaticUpdates()
  1101. {
  1102. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  1106. {
  1107. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1108. OpenBrowser(LoadStr(HISTORY_URL));
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1112. {
  1113. return static_cast<int>(Size / 1024);
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. class TUpdateDownloadThread : public TCompThread
  1117. {
  1118. public:
  1119. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1120. virtual __fastcall ~TUpdateDownloadThread();
  1121. void __fastcall CancelClicked(TObject * Sender);
  1122. bool __fastcall CancelDownload();
  1123. __property bool Done = { read = FDone };
  1124. protected:
  1125. virtual void __fastcall Execute();
  1126. void __fastcall UpdateDownloaded();
  1127. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1128. void __fastcall UpdateProgress();
  1129. void __fastcall ShowException();
  1130. void __fastcall DownloadNotVerified();
  1131. void __fastcall CancelForm();
  1132. private:
  1133. TCustomForm * FForm;
  1134. TProgressBar * FProgressBar;
  1135. __int64 FDownloaded;
  1136. std::unique_ptr<Exception> FException;
  1137. std::unique_ptr<THttp> FHttp;
  1138. TUpdatesConfiguration FUpdates;
  1139. bool FDone;
  1140. };
  1141. //---------------------------------------------------------------------------
  1142. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1143. TCompThread(true)
  1144. {
  1145. // cache, as the progress bar miht be destroyed already when
  1146. // we need the form at the end of Execute()
  1147. FForm = GetParentForm(ProgressBar);
  1148. FProgressBar = ProgressBar;
  1149. // cache to prevent concurrency
  1150. FUpdates = WinConfiguration->Updates;
  1151. FDone = false;
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1155. {
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. void __fastcall TUpdateDownloadThread::Execute()
  1159. {
  1160. try
  1161. {
  1162. bool Retried = false;
  1163. bool Retry;
  1164. do
  1165. {
  1166. Retry = false;
  1167. try
  1168. {
  1169. FDownloaded = 0;
  1170. FHttp.reset(CreateHttp(FUpdates));
  1171. FHttp->URL = FUpdates.Results.DownloadUrl;
  1172. FHttp->OnDownload = HttpDownload;
  1173. FHttp->Get();
  1174. }
  1175. catch (EAbort &)
  1176. {
  1177. throw;
  1178. }
  1179. catch (Exception & E)
  1180. {
  1181. // The original URL failed, try to get a fresh one and retry
  1182. if (!Retried)
  1183. {
  1184. try
  1185. {
  1186. // Check if new update data (URL particlarly) is available
  1187. if (QueryUpdates(FUpdates) &&
  1188. !FUpdates.Results.DownloadUrl.IsEmpty())
  1189. {
  1190. Retry = true;
  1191. Retried = true;
  1192. }
  1193. }
  1194. catch (...)
  1195. {
  1196. }
  1197. }
  1198. if (!Retry)
  1199. {
  1200. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1201. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1202. }
  1203. }
  1204. }
  1205. while (Retry);
  1206. Synchronize(UpdateDownloaded);
  1207. }
  1208. catch (EAbort &)
  1209. {
  1210. // noop
  1211. }
  1212. catch (Exception & E)
  1213. {
  1214. Configuration->Usage->Inc(L"UpdateFailures");
  1215. FException.reset(CloneException(&E));
  1216. Synchronize(ShowException);
  1217. }
  1218. FDone = true;
  1219. Synchronize(CancelForm);
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. void __fastcall TUpdateDownloadThread::CancelForm()
  1223. {
  1224. FForm->ModalResult = mrCancel;
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1228. {
  1229. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1230. const char * Buffer = FHttp->ResponseRaw.c_str();
  1231. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1232. {
  1233. DownloadNotVerified();
  1234. }
  1235. UnicodeString Digest = Sha256(Buffer, Size);
  1236. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1237. {
  1238. DownloadNotVerified();
  1239. }
  1240. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1241. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1242. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1243. UnicodeString SetupPath = SetupPathBase;
  1244. int Index = 0;
  1245. while (FileExists(SetupPath))
  1246. {
  1247. Index++;
  1248. SetupPath =
  1249. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1250. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1251. }
  1252. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1253. FileStream->Write(Buffer, Size);
  1254. FileStream.reset(NULL);
  1255. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1256. if (FUpdates.Results.OpenGettingStarted)
  1257. {
  1258. Params += L" /OpenGettingStarted";
  1259. }
  1260. ExecuteShellChecked(SetupPath, Params);
  1261. Configuration->Usage->Inc(L"UpdateRuns");
  1262. TerminateApplication();
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1266. {
  1267. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1271. {
  1272. FDownloaded = Size;
  1273. Synchronize(UpdateProgress);
  1274. // Do not waste bandwidth, if something goes wrong
  1275. if (FDownloaded > FUpdates.Results.DownloadSize)
  1276. {
  1277. DownloadNotVerified();
  1278. }
  1279. if (Terminated)
  1280. {
  1281. Cancel = true;
  1282. }
  1283. }
  1284. //---------------------------------------------------------------------------
  1285. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1286. {
  1287. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TUpdateDownloadThread::ShowException()
  1291. {
  1292. DebugAssert(FException.get() != NULL);
  1293. ShowExtendedException(FException.get());
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1297. {
  1298. bool Result = !Terminated;
  1299. if (Result)
  1300. {
  1301. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1302. Terminate();
  1303. }
  1304. return Result;
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1308. {
  1309. if (CancelDownload())
  1310. {
  1311. WaitFor();
  1312. }
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. //---------------------------------------------------------------------------
  1316. class TUpdateDownloadData : public TComponent
  1317. {
  1318. public:
  1319. TUpdateDownloadThread * Thread;
  1320. __fastcall TUpdateDownloadData() :
  1321. TComponent(NULL)
  1322. {
  1323. }
  1324. virtual __fastcall ~TUpdateDownloadData()
  1325. {
  1326. // will stop the thread
  1327. delete Thread;
  1328. }
  1329. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1330. {
  1331. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1332. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1333. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1334. }
  1335. };
  1336. //---------------------------------------------------------------------------
  1337. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1338. {
  1339. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1340. // If the form was closed by CancelForm at the end of the thread, do nothing
  1341. if (!UpdateDownloadData->Thread->Done)
  1342. {
  1343. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1344. // May this should actually call CancelClicked?
  1345. if (UpdateDownloadData->Thread->CancelDownload())
  1346. {
  1347. Action = caNone;
  1348. }
  1349. }
  1350. }
  1351. //---------------------------------------------------------------------------
  1352. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender)
  1353. {
  1354. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1355. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1356. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1357. TPanel * Panel = CreateBlankPanel(Form);
  1358. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1359. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1360. ProgressBar->Top = 0;
  1361. ProgressBar->Left = 0;
  1362. ProgressBar->Width = Panel->Width;
  1363. ProgressBar->Parent = Panel;
  1364. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1365. Panel->Height = ProgressBar->Height;
  1366. InsertPanelToMessageDialog(Form, Panel);
  1367. Button->Enabled = false;
  1368. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1369. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1370. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1371. // The form becomes owner of the thread (via TUpdateDownloadData),
  1372. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1373. // But it gets done only after the form controls are gone, and the thread
  1374. // might try to access them meanwhile. So we stop the thread explicitly.
  1375. CancelButton->OnClick = Thread->CancelClicked;
  1376. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1377. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1378. Data->Thread = Thread;
  1379. Form->InsertComponent(Data);
  1380. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1381. if (!DownloadingUrl.IsEmpty())
  1382. {
  1383. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1384. }
  1385. DebugAssert(Form->OnClose == NULL);
  1386. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1387. Thread->Resume();
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1391. {
  1392. EnableAutomaticUpdates();
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1396. {
  1397. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1398. TPanel * Panel = CreateBlankPanel(Dialog);
  1399. TStaticText * StaticText = new TStaticText(Panel);
  1400. StaticText->Top = 0;
  1401. StaticText->Left = 0;
  1402. StaticText->AutoSize = true;
  1403. StaticText->Caption = LoadStr(UPDATES_DONATE_LINK);
  1404. StaticText->Parent = Panel;
  1405. StaticText->OnClick = MakeMethod<TNotifyEvent>(NULL, UpdatesDonateClick);
  1406. StaticText->TabStop = true;
  1407. LinkLabel(StaticText);
  1408. Panel->Height = StaticText->Height;
  1409. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1410. // (what should not happen)
  1411. InsertPanelToMessageDialog(Dialog, Panel);
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. bool __fastcall CheckForUpdates(bool CachedResults)
  1415. {
  1416. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1417. bool Result = false;
  1418. TOperationVisualizer Visualizer;
  1419. try
  1420. {
  1421. if (ActiveForm)
  1422. {
  1423. DebugAssert(ActiveForm->Enabled);
  1424. ActiveForm->Enabled = false;
  1425. }
  1426. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1427. bool Cached =
  1428. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1429. CachedResults;
  1430. if (!Cached)
  1431. {
  1432. DoQueryUpdates(WinConfiguration->CollectUsage);
  1433. // reread new data
  1434. Updates = WinConfiguration->Updates;
  1435. }
  1436. if (!Updates.ShownResults)
  1437. {
  1438. Updates.ShownResults = true;
  1439. WinConfiguration->Updates = Updates;
  1440. }
  1441. DebugAssert(Updates.HaveResults);
  1442. UnicodeString Message;
  1443. bool New;
  1444. TQueryType Type;
  1445. GetUpdatesMessage(Message, New, Type, true);
  1446. Configuration->Usage->Inc(L"UpdateDisplays");
  1447. if (New)
  1448. {
  1449. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1450. }
  1451. if (Updates.HaveResults &&
  1452. (double(Updates.Period) > 0) &&
  1453. // do not chow next check time, if we have new version info
  1454. !New)
  1455. {
  1456. Message += L"\n\n" +
  1457. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1458. }
  1459. int Answers = qaOK |
  1460. // show "what's new" button only when change list URL was not provided in results
  1461. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1462. FLAGMASK(New, qaCancel) |
  1463. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1464. TQueryButtonAlias Aliases[4];
  1465. Aliases[0].Button = qaYes;
  1466. if (Updates.Results.UrlButton.IsEmpty())
  1467. {
  1468. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1469. }
  1470. else
  1471. {
  1472. Aliases[0].Alias = Updates.Results.UrlButton;
  1473. }
  1474. Aliases[1].Button = qaAll;
  1475. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1476. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  1477. Aliases[2].Button = qaCancel;
  1478. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1479. // Used only when New == true, see AliasesCount below
  1480. Aliases[3].Button = qaOK;
  1481. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1482. if (!Updates.Results.DownloadUrl.IsEmpty())
  1483. {
  1484. Aliases[3].OnClick = MakeMethod<TNotifyEvent>(NULL, DownloadUpdate);
  1485. Aliases[3].ElevationRequired = true;
  1486. }
  1487. TMessageParams Params;
  1488. Params.Aliases = Aliases;
  1489. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1490. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1491. // alias "ok" button to "upgrade" only if we have new version
  1492. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1493. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1494. if (New)
  1495. {
  1496. Params.ImageName = L"Installer";
  1497. }
  1498. std::unique_ptr<TForm> Dialog(
  1499. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1500. if (New)
  1501. {
  1502. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1503. {
  1504. DebugAssert(Dialog->OnShow == NULL);
  1505. // InsertDonateLink need to be called only after MessageBrowser is created
  1506. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1507. }
  1508. }
  1509. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1510. switch (Answer)
  1511. {
  1512. case qaOK:
  1513. if (New)
  1514. {
  1515. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1516. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1517. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1518. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1519. OpenBrowser(UpgradeUrl);
  1520. Result = true;
  1521. }
  1522. break;
  1523. case qaYes:
  1524. OpenBrowser(Updates.Results.Url);
  1525. break;
  1526. case qaAll:
  1527. DebugFail();
  1528. break;
  1529. }
  1530. }
  1531. __finally
  1532. {
  1533. if (ActiveForm)
  1534. {
  1535. ActiveForm->Enabled = true;
  1536. }
  1537. }
  1538. return Result;
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. class TUpdateThread : public TCompThread
  1542. {
  1543. public:
  1544. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1545. protected:
  1546. virtual void __fastcall Execute();
  1547. TThreadMethod FOnUpdatesChecked;
  1548. };
  1549. //---------------------------------------------------------------------------
  1550. TUpdateThread * UpdateThread = NULL;
  1551. //---------------------------------------------------------------------------
  1552. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1553. TCompThread(false),
  1554. FOnUpdatesChecked(OnUpdatesChecked)
  1555. {
  1556. }
  1557. //---------------------------------------------------------------------------
  1558. void __fastcall TUpdateThread::Execute()
  1559. {
  1560. try
  1561. {
  1562. DoQueryUpdates(WinConfiguration->CollectUsage);
  1563. if (FOnUpdatesChecked != NULL)
  1564. {
  1565. Synchronize(FOnUpdatesChecked);
  1566. }
  1567. }
  1568. catch(...)
  1569. {
  1570. // ignore errors
  1571. }
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1575. {
  1576. DebugAssert(UpdateThread == NULL);
  1577. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1578. }
  1579. //---------------------------------------------------------------------------
  1580. void __fastcall StopUpdateThread()
  1581. {
  1582. if (UpdateThread != NULL)
  1583. {
  1584. SAFE_DESTROY(UpdateThread);
  1585. }
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. void __fastcall SetupInitialize()
  1589. {
  1590. WinConfiguration->UpdateJumpList();
  1591. }
  1592. //---------------------------------------------------------------------------
  1593. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1594. UnicodeString AdditionalParams, TStringList * Removed,
  1595. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1596. int IconIndex)
  1597. {
  1598. bool Result = false;
  1599. IObjectCollection * Collection = NULL;
  1600. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1601. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1602. {
  1603. try
  1604. {
  1605. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1606. int Count = 0;
  1607. for (int Index = 0; Index < Names->Count; Index++)
  1608. {
  1609. IShellLink * Link =
  1610. CreateDesktopSessionShortCut(
  1611. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1612. wchar_t Desc[2048];
  1613. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1614. {
  1615. if (Removed->IndexOf(Desc) < 0)
  1616. {
  1617. try
  1618. {
  1619. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1620. Count++;
  1621. }
  1622. __finally
  1623. {
  1624. Link->Release();
  1625. }
  1626. }
  1627. else
  1628. {
  1629. Names->Delete(Index);
  1630. Index--;
  1631. }
  1632. }
  1633. }
  1634. if (Count > 0)
  1635. {
  1636. IObjectArray * Array;
  1637. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1638. {
  1639. try
  1640. {
  1641. Result = SUCCEEDED(
  1642. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1643. }
  1644. __finally
  1645. {
  1646. Array->Release();
  1647. }
  1648. }
  1649. }
  1650. }
  1651. __finally
  1652. {
  1653. Collection->Release();
  1654. }
  1655. }
  1656. return Result;
  1657. }
  1658. //---------------------------------------------------------------------------
  1659. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1660. {
  1661. ICustomDestinationList * DestinationList = NULL;
  1662. IObjectArray * RemovedArray = NULL;
  1663. TStringList * Removed = NULL;
  1664. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1665. try
  1666. {
  1667. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1668. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1669. {
  1670. unsigned int MinSlots;
  1671. unsigned int * PMinSlots = &MinSlots;
  1672. void ** PRemovedArray = (void**)&RemovedArray;
  1673. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1674. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1675. {
  1676. Removed = new TStringList();
  1677. unsigned int RemovedCount;
  1678. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1679. {
  1680. RemovedCount = 0;
  1681. }
  1682. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1683. {
  1684. IShellLink * Link;
  1685. wchar_t Desc[2048];
  1686. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1687. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1688. {
  1689. Removed->Add(Desc);
  1690. }
  1691. }
  1692. AddJumpListCategory(
  1693. WorkspaceNames, L"", Removed, DestinationList,
  1694. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1695. AddJumpListCategory(
  1696. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1697. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1698. if (DestinationList != NULL)
  1699. {
  1700. DestinationList->CommitList();
  1701. }
  1702. }
  1703. }
  1704. }
  1705. __finally
  1706. {
  1707. SetErrorMode(OldErrMode);
  1708. if (RemovedArray != NULL)
  1709. {
  1710. RemovedArray->Release();
  1711. }
  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)
  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].OnClick = MakeMethod<TNotifyEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1893. Aliases[1].Button = qaNo;
  1894. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1895. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(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. }