Setup.cpp 72 KB

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