Setup.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  1. //---------------------------------------------------------------------------
  2. // Part of this code is
  3. // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
  4. //---------------------------------------------------------------------------
  5. #include <vcl.h>
  6. #pragma hdrstop
  7. #include <stdio.h>
  8. #include <tchar.h>
  9. #include <shlobj.h>
  10. #include <tlhelp32.h>
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <Exceptions.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <HelpWin.h>
  17. #include <Http.h>
  18. #include <CompThread.hpp>
  19. #include <FileInfo.h>
  20. #include "WinConfiguration.h"
  21. #include "WinInterface.h"
  22. #include "Tools.h"
  23. #include "Setup.h"
  24. #include <StrUtils.hpp>
  25. #include "ProgParams.h"
  26. #include <Consts.hpp>
  27. #include <GUITools.h>
  28. #include <PuttyTools.h>
  29. #include <VCLCommon.h>
  30. #include <WebBrowserEx.hpp>
  31. #include <DateUtils.hpp>
  32. #include <OperationWithTimeout.hpp>
  33. //---------------------------------------------------------------------------
  34. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  35. _T("Session Manager\\Environment")
  36. // when the PATH registry key is over aprox 2048 characters,
  37. // PATH as well as WINDIR variables are actually not set, breaking the system
  38. #define MAX_PATH_LEN 2000
  39. /* Command line options. */
  40. UnicodeString LastPathError;
  41. //---------------------------------------------------------------------------
  42. UnicodeString NetVersionStr;
  43. UnicodeString PowerShellVersionStr;
  44. //---------------------------------------------------------------------------
  45. // Display the error "err_msg".
  46. void err_out(LPCTSTR err_msg)
  47. {
  48. LastPathError = err_msg;
  49. }
  50. //---------------------------------------------------------------------------
  51. // Display "base_err_msg" followed by the description of the system error
  52. // identified by "sys_err".
  53. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  54. {
  55. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  56. }
  57. //---------------------------------------------------------------------------
  58. // Works as "strcmp" but the comparison is not case sensitive.
  59. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  60. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  61. if (*str1 == L'\0')
  62. return 0;
  63. return tolower(*str1) - tolower(*str2);
  64. }
  65. //---------------------------------------------------------------------------
  66. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  67. // not present). The returned value must be freed with "free".
  68. LPTSTR unquote(LPCTSTR str){
  69. int last_pos;
  70. LPTSTR ret;
  71. size_t new_len;
  72. last_pos = _tcslen(str) - 1;
  73. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  74. new_len= (_tcslen(str) - 1);
  75. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  76. lstrcpyn(ret, &str[1], new_len);
  77. }
  78. else
  79. ret = _tcsdup(str);
  80. return ret;
  81. }
  82. //---------------------------------------------------------------------------
  83. // Find "what" in the ";" separated string "str" and returns a pointer to
  84. // the first letter of "what" in the string. If "next" is not "NULL" it
  85. // points to the first letter after "what" (excluding the trailing ";").
  86. // If "what" isn't find the functions returns "NULL".
  87. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  88. LPTSTR tok_buff;
  89. LPTSTR curr_tok;
  90. LPTSTR curr_tok_dup;
  91. BOOL path_eq;
  92. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  93. int pos = -1;
  94. LPTSTR ret;
  95. tok_buff = _tcsdup(str);
  96. curr_tok = _tcstok(tok_buff, _T(";"));
  97. while (pos == -1 && curr_tok){
  98. curr_tok_dup = unquote(curr_tok);
  99. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  100. GetShortPathName(curr_tok_dup, sh_path2,
  101. LENOF(sh_path2)) &&
  102. (tcharicmp(sh_path1, sh_path2) == 0);
  103. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  104. pos = curr_tok - tok_buff;
  105. }
  106. free(curr_tok_dup);
  107. curr_tok = _tcstok(NULL, _T(";"));
  108. if (pos != -1 && next){
  109. if (curr_tok)
  110. *next = str + (curr_tok - tok_buff);
  111. else
  112. *next = str + _tcslen(str);
  113. }
  114. }
  115. free(tok_buff);
  116. if (pos != -1)
  117. ret = str + pos;
  118. else
  119. ret = NULL;
  120. return ret;
  121. }
  122. //---------------------------------------------------------------------------
  123. void path_reg_propagate()
  124. {
  125. DWORD send_message_result;
  126. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  127. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  128. 5000, &send_message_result);
  129. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  130. {
  131. err_out_sys(_T("Cannot propagate the new enviroment to ")
  132. _T("other processes. The new value will be ")
  133. _T("avaible after a reboot."), GetLastError());
  134. SimpleErrorDialog(LastPathError);
  135. LastPathError = L"";
  136. }
  137. }
  138. //---------------------------------------------------------------------------
  139. // Add "path" to the registry. Return "TRUE" if the path has been added or
  140. // was already in the registry, "FALSE" otherwise.
  141. BOOL add_path_reg(LPCTSTR path){
  142. HKEY key;
  143. LONG ret;
  144. DWORD data_size;
  145. LPTSTR reg_str;
  146. BOOL func_ret = TRUE;
  147. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  148. KEY_WRITE | KEY_READ, &key);
  149. if (ret != ERROR_SUCCESS){
  150. err_out_sys(_T("Cannot open registry."), ret);
  151. return FALSE;
  152. }
  153. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  154. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  155. includes '\0'. */
  156. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  157. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  158. &data_size);
  159. if (ret != ERROR_SUCCESS){
  160. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  161. func_ret = FALSE;
  162. }
  163. else{
  164. if (!find_reg_str(reg_str, path, NULL)){
  165. _tcscat(reg_str, _T(";"));
  166. _tcscat(reg_str, path);
  167. size_t len = _tcslen(reg_str);
  168. if (len >= MAX_PATH_LEN)
  169. {
  170. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  171. func_ret = FALSE;
  172. }
  173. else
  174. {
  175. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  176. (LPBYTE)reg_str,
  177. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  178. if (ret != ERROR_SUCCESS){
  179. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  180. func_ret = FALSE;
  181. }
  182. /* Is this needed to make the new key avaible? */
  183. RegFlushKey(key);
  184. SetLastError(0);
  185. path_reg_propagate();
  186. }
  187. }
  188. }
  189. RegCloseKey(key);
  190. free(reg_str);
  191. return func_ret;
  192. }
  193. //---------------------------------------------------------------------------
  194. // Removes "path" from the registry. Return "TRUE" if the path has been
  195. // removed or it wasn't in the registry, "FALSE" otherwise.
  196. BOOL remove_path_reg(LPCTSTR path){
  197. HKEY key;
  198. LONG ret;
  199. DWORD data_size;
  200. LPTSTR reg_str;
  201. LPTSTR reg_str2;
  202. BOOL func_ret = TRUE;
  203. LPTSTR next;
  204. LPTSTR del_part;
  205. int last_pos;
  206. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  207. KEY_WRITE | KEY_READ, &key);
  208. if (ret != ERROR_SUCCESS){
  209. err_out_sys(_T("Cannot open registry."), ret);
  210. return FALSE;
  211. }
  212. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  213. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  214. includes '\0'. */
  215. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  216. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  217. (LPBYTE)reg_str, &data_size);
  218. if (ret != ERROR_SUCCESS){
  219. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  220. func_ret = FALSE;
  221. }
  222. else{
  223. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  224. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  225. *del_part = '\0';
  226. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  227. last_pos = _tcslen(reg_str2) - 1;
  228. if (last_pos != -1 && reg_str2[last_pos] == ';')
  229. reg_str2[last_pos] = '\0';
  230. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  231. (LPBYTE)reg_str2,
  232. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  233. if (ret != ERROR_SUCCESS){
  234. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  235. func_ret = FALSE;
  236. }
  237. free(reg_str2);
  238. /* Is this needed to make the new key avaible? */
  239. RegFlushKey(key);
  240. SetLastError(0);
  241. path_reg_propagate();
  242. }
  243. }
  244. RegCloseKey(key);
  245. free(reg_str);
  246. return func_ret;
  247. }
  248. //---------------------------------------------------------------------------
  249. //---------------------------------------------------------------------------
  250. void __fastcall AddSearchPath(const UnicodeString Path)
  251. {
  252. if (!add_path_reg(Path.c_str()))
  253. {
  254. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  255. }
  256. }
  257. //---------------------------------------------------------------------------
  258. void __fastcall RemoveSearchPath(const UnicodeString Path)
  259. {
  260. if (!remove_path_reg(Path.c_str()))
  261. {
  262. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  263. }
  264. }
  265. //---------------------------------------------------------------------------
  266. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  267. //---------------------------------------------------------------------------
  268. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  269. {
  270. if (Registry->OpenKey(Key, false))
  271. {
  272. std::unique_ptr<TStrings> List(new TStringList());
  273. Registry->GetValueNames(List.get());
  274. bool CanDelete = true;
  275. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  276. {
  277. UnicodeString ValueName = List->Strings[Index];
  278. if (!AllowRootValues)
  279. {
  280. CanDelete = false;
  281. }
  282. if ((ValueName != L"") &&
  283. (ValueName != L"URL Protocol") &&
  284. (ValueName != L"EditFlags") &&
  285. (ValueName != L"BrowserFlags"))
  286. {
  287. CanDelete = false;
  288. }
  289. }
  290. List->Clear();
  291. Registry->GetKeyNames(List.get());
  292. Registry->CloseKey();
  293. if (CanDelete)
  294. {
  295. for (int Index = 0; Index < List->Count; Index++)
  296. {
  297. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  298. }
  299. // will fail, if not all subkeys got removed
  300. Registry->DeleteKey(Key);
  301. }
  302. }
  303. }
  304. //---------------------------------------------------------------------------
  305. static void __fastcall RegisterProtocol(TRegistry * Registry,
  306. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  307. {
  308. if (Description.IsEmpty())
  309. {
  310. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  311. }
  312. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  313. if (Force || !Registry->KeyExists(ProtocolKey))
  314. {
  315. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  316. {
  317. Registry->WriteString(L"", Description);
  318. Registry->WriteString(L"URL Protocol", L"");
  319. Registry->WriteInteger(L"EditFlags", 0x02);
  320. Registry->WriteInteger(L"BrowserFlags", 0x08);
  321. if (Registry->OpenKey(L"DefaultIcon", true))
  322. {
  323. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  324. Registry->CloseKey();
  325. }
  326. else
  327. {
  328. Abort();
  329. }
  330. }
  331. else
  332. {
  333. Abort();
  334. }
  335. }
  336. }
  337. //---------------------------------------------------------------------------
  338. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  339. const UnicodeString & Protocol)
  340. {
  341. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  342. }
  343. //---------------------------------------------------------------------------
  344. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  345. {
  346. std::unique_ptr<TRegistry> Registry(new TRegistry());
  347. Registry->Access = KEY_WRITE | KEY_READ;
  348. Registry->RootKey = RootKey;
  349. return Registry.release();
  350. }
  351. //---------------------------------------------------------------------------
  352. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  353. const UnicodeString & Protocol, UnicodeString Description = L"")
  354. {
  355. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  356. RegisterProtocol(Registry.get(), Protocol, Description, true);
  357. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  358. Registry->OpenKey(L"shell", true) &&
  359. Registry->OpenKey(L"open", true) &&
  360. Registry->OpenKey(L"command", true))
  361. {
  362. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  363. Registry->CloseKey();
  364. }
  365. else
  366. {
  367. Abort();
  368. }
  369. }
  370. //---------------------------------------------------------------------------
  371. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  372. {
  373. try
  374. {
  375. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  376. // get rid of any HKCU registraction that would overrite the HKLM one
  377. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  378. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  379. {
  380. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  381. }
  382. }
  383. catch (Exception & E)
  384. {
  385. try
  386. {
  387. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  388. }
  389. catch(Exception & E)
  390. {
  391. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  392. }
  393. }
  394. }
  395. //---------------------------------------------------------------------------
  396. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  397. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  398. {
  399. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  400. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  401. if (Registry->OpenKey(DefaultIconKey, false))
  402. {
  403. UnicodeString Value = Registry->ReadString(L"");
  404. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  405. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  406. {
  407. Registry->DeleteValue(L"");
  408. }
  409. Registry->CloseKey();
  410. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  411. }
  412. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  413. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  414. {
  415. UnicodeString Value = Registry->ReadString(L"");
  416. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  417. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  418. {
  419. Registry->DeleteValue(L"");
  420. }
  421. Registry->CloseKey();
  422. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  423. }
  424. if (UnregisterProtocol)
  425. {
  426. ::UnregisterProtocol(Registry.get(), Protocol);
  427. }
  428. }
  429. //---------------------------------------------------------------------------
  430. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  431. {
  432. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  433. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  434. }
  435. //---------------------------------------------------------------------------
  436. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  437. {
  438. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  439. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  440. RegisterAsUrlHandler(Prefix + WebDAVProtocol.UpperCase());
  441. RegisterAsUrlHandler(Prefix + WebDAVSProtocol.UpperCase());
  442. RegisterAsUrlHandler(Prefix + S3Protocol.UpperCase());
  443. }
  444. //---------------------------------------------------------------------------
  445. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  446. {
  447. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  448. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  449. UnregisterAsUrlHandler(Prefix + WebDAVProtocol, UnregisterProtocol);
  450. UnregisterAsUrlHandler(Prefix + WebDAVSProtocol, UnregisterProtocol);
  451. UnregisterAsUrlHandler(Prefix + S3Protocol, UnregisterProtocol);
  452. }
  453. //---------------------------------------------------------------------------
  454. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  455. //---------------------------------------------------------------------------
  456. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  457. {
  458. // Register protocol, if it does not exist yet.
  459. // Prior to Windows 8, we need to register ourselves as legacy handler to
  460. // become the default handler. On Windows 8, it's automatic as long as no other
  461. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  462. RegisterAsUrlHandler(RootKey, Protocol);
  463. // see https://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
  464. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  465. // create capabilities record
  466. // this has to be a separate branch from WinSCP one, as by its presence we
  467. // enforce registry storage usage, and the capabilities branch may exist
  468. // even if we are using INI file
  469. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  470. if (!Registry->OpenKey(CapabilitiesKey, true))
  471. {
  472. Abort();
  473. }
  474. UnicodeString Description = LoadStr(REGISTERED_APP_DESC2);
  475. Registry->WriteString(L"ApplicationDescription", Description);
  476. if (!Registry->OpenKey(L"UrlAssociations", true))
  477. {
  478. Abort();
  479. }
  480. Registry->WriteString(Protocol, GenericUrlHandler);
  481. Registry->CloseKey();
  482. // register application
  483. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  484. {
  485. Abort();
  486. }
  487. Registry->WriteString(AppNameString(), CapabilitiesKey);
  488. Registry->CloseKey();
  489. }
  490. //---------------------------------------------------------------------------
  491. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  492. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  493. {
  494. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  495. // unregister the protocol
  496. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  497. // remove capabilities record
  498. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  499. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  500. if (Registry->OpenKey(UrlAssociationsKey, false))
  501. {
  502. Registry->DeleteValue(Protocol);
  503. Registry->CloseKey();
  504. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  505. }
  506. if (Registry->OpenKey(CapabilitiesKey, false))
  507. {
  508. if (!Registry->HasSubKeys())
  509. {
  510. Registry->DeleteValue(L"ApplicationDescription");
  511. }
  512. Registry->CloseKey();
  513. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  514. }
  515. if (!Registry->KeyExists(CapabilitiesKey))
  516. {
  517. // unregister application
  518. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  519. {
  520. Registry->DeleteValue(AppNameString());
  521. Registry->CloseKey();
  522. }
  523. }
  524. }
  525. //---------------------------------------------------------------------------
  526. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  527. {
  528. // register URL handler, if it does not exist yet
  529. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  530. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  531. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  532. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  533. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  534. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  535. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  536. RegisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol);
  537. RegisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol);
  538. RegisterProtocolForDefaultPrograms(RootKey, S3Protocol);
  539. // deliberately not including http,
  540. // it's unlikely that anyone would like to change http handler
  541. // to non-browser application
  542. }
  543. //---------------------------------------------------------------------------
  544. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  545. {
  546. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  547. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  548. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  549. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  550. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  551. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol, ForceHandlerUnregistration);
  552. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol, ForceHandlerUnregistration);
  553. UnregisterProtocolForDefaultPrograms(RootKey, S3Protocol, ForceHandlerUnregistration);
  554. // we should not really need the "force" flag here, but why not
  555. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  556. }
  557. //---------------------------------------------------------------------------
  558. static void __fastcall RegisterForDefaultPrograms()
  559. {
  560. try
  561. {
  562. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  563. // make sure we unregister any legacy protocol handler for CU,
  564. // this is needed for Windows Vista+7
  565. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  566. }
  567. catch (Exception & E)
  568. {
  569. try
  570. {
  571. // Maybe we should skip this if HKLM key existed already (we are running non-privileged)
  572. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  573. }
  574. catch (Exception & E)
  575. {
  576. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  577. }
  578. }
  579. }
  580. //---------------------------------------------------------------------------
  581. static void __fastcall NotifyChangedAssociations()
  582. {
  583. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  584. }
  585. //---------------------------------------------------------------------------
  586. void __fastcall RegisterForDefaultProtocols()
  587. {
  588. if (IsWinVista())
  589. {
  590. RegisterForDefaultPrograms();
  591. }
  592. else
  593. {
  594. RegisterAsNonBrowserUrlHandler(UnicodeString());
  595. }
  596. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  597. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  598. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  599. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  600. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  601. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  602. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  603. NotifyChangedAssociations();
  604. }
  605. //---------------------------------------------------------------------------
  606. void __fastcall UnregisterForProtocols()
  607. {
  608. UnregisterAsUrlHandlers(UnicodeString(), false);
  609. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  610. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  611. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  612. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  613. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  614. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  615. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  616. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  617. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  618. NotifyChangedAssociations();
  619. }
  620. //---------------------------------------------------------------------------
  621. void __fastcall LaunchAdvancedAssociationUI()
  622. {
  623. DebugAssert(IsWinVista());
  624. RegisterForDefaultPrograms();
  625. NotifyChangedAssociations();
  626. // sleep recommended by https://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  627. Sleep(1000);
  628. if (IsWin10())
  629. {
  630. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  631. // https://stackoverflow.com/q/32178986/850848
  632. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  633. IOpenControlPanel * OpenControlPanel;
  634. HRESULT Result =
  635. CoCreateInstance(CLSID_OpenControlPanel,
  636. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  637. if (SUCCEEDED(Result))
  638. {
  639. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  640. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  641. OpenControlPanel->Release();
  642. }
  643. }
  644. else
  645. {
  646. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  647. HRESULT Result =
  648. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  649. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  650. if (SUCCEEDED(Result))
  651. {
  652. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  653. AppAssocRegUI->Release();
  654. }
  655. }
  656. }
  657. //---------------------------------------------------------------------------
  658. void __fastcall TemporaryDirectoryCleanup()
  659. {
  660. bool Continue = true;
  661. TStrings * Folders = NULL;
  662. try
  663. {
  664. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  665. {
  666. Folders = WinConfiguration->FindTemporaryFolders();
  667. Continue = (Folders != NULL);
  668. if (Continue)
  669. {
  670. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  671. TQueryButtonAlias Aliases[1];
  672. Aliases[0].Button = qaRetry;
  673. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  674. TMessageParams Params(mpNeverAskAgainCheck);
  675. Params.Aliases = Aliases;
  676. Params.AliasesCount = LENOF(Aliases);
  677. unsigned int Answer = MoreMessageDialog(
  678. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  679. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  680. if (Answer == qaNeverAskAgain)
  681. {
  682. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  683. Answer = qaYes;
  684. }
  685. else if (Answer == qaRetry)
  686. {
  687. for (int Index = 0; Index < Folders->Count; Index++)
  688. {
  689. ShellExecute(Application->Handle, NULL,
  690. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  691. }
  692. }
  693. Continue = (Answer == qaYes);
  694. }
  695. }
  696. if (Continue)
  697. {
  698. try
  699. {
  700. WinConfiguration->CleanupTemporaryFolders(Folders);
  701. }
  702. catch (Exception &E)
  703. {
  704. ShowExtendedException(&E);
  705. }
  706. }
  707. }
  708. __finally
  709. {
  710. delete Folders;
  711. }
  712. }
  713. //-------------------------------------------- -------------------------------
  714. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  715. {
  716. int MajorVer = Version / (10000*100*100);
  717. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  718. int Release = (Version % (10000*100)) / (10000);
  719. UnicodeString Result;
  720. if (Release > 0)
  721. {
  722. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  723. }
  724. else
  725. {
  726. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  727. }
  728. return Result;
  729. }
  730. //---------------------------------------------------------------------------
  731. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  732. {
  733. int CurrentCompoundVer = Configuration->CompoundVersion;
  734. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  735. // 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=app&utm_campaign=%s", (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;
  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. HRESULT Result = DestinationListBeginList(DestinationList, MinSlots, IID_IObjectArray, reinterpret_cast<void *>(RemovedArray), 50000);
  1677. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1678. {
  1679. Removed = new TStringList();
  1680. unsigned int RemovedCount;
  1681. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1682. {
  1683. RemovedCount = 0;
  1684. }
  1685. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1686. {
  1687. IShellLink * Link;
  1688. wchar_t Desc[2048];
  1689. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1690. SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1691. {
  1692. Removed->Add(Desc);
  1693. }
  1694. }
  1695. AddJumpListCategory(
  1696. WorkspaceNames, L"", Removed, DestinationList,
  1697. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1698. AddJumpListCategory(
  1699. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1700. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1701. if (DestinationList != NULL)
  1702. {
  1703. DestinationList->CommitList();
  1704. }
  1705. }
  1706. }
  1707. }
  1708. __finally
  1709. {
  1710. SetErrorMode(OldErrMode);
  1711. if (DestinationList != NULL)
  1712. {
  1713. DestinationList->Release();
  1714. }
  1715. delete Removed;
  1716. }
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. bool __fastcall AnyOtherInstanceOfSelf()
  1720. {
  1721. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1722. bool Result = false;
  1723. try
  1724. {
  1725. unsigned int Process = GetCurrentProcessId();
  1726. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1727. PROCESSENTRY32 ProcessEntry;
  1728. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1729. if (Process32First(Snapshot, &ProcessEntry))
  1730. {
  1731. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1732. {
  1733. // we should check if the process is running in the same session,
  1734. // but for that we probably need some special privileges
  1735. if ((Process != ProcessEntry.th32ProcessID) &&
  1736. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1737. {
  1738. Result = true;
  1739. }
  1740. }
  1741. }
  1742. }
  1743. __finally
  1744. {
  1745. CloseHandle(Snapshot);
  1746. }
  1747. return Result;
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1751. {
  1752. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1753. Registry->RootKey = RootKey;
  1754. bool Result =
  1755. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1756. if (Result)
  1757. {
  1758. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1759. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1760. Result =
  1761. !InstallPath.IsEmpty() &&
  1762. IsPathToSameFile(ExePath, InstallPath);
  1763. }
  1764. return Result;
  1765. }
  1766. //---------------------------------------------------------------------------
  1767. bool __fastcall IsInstalled()
  1768. {
  1769. return
  1770. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1771. DoIsInstalled(HKEY_CURRENT_USER);
  1772. }
  1773. //---------------------------------------------------------------------------
  1774. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1775. {
  1776. std::unique_ptr<TStringList> List(new TStringList());
  1777. List->CommaText = Text;
  1778. return List.release();
  1779. }
  1780. //---------------------------------------------------------------------------
  1781. UnicodeString __fastcall FirstUnshownTip()
  1782. {
  1783. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1784. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1785. Tips->CaseSensitive = false;
  1786. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1787. TipsSeen->CaseSensitive = false;
  1788. int LastTipSeen = -1;
  1789. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1790. {
  1791. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1792. if (TipIndex >= 0)
  1793. {
  1794. LastTipSeen = TipIndex;
  1795. }
  1796. }
  1797. UnicodeString Result;
  1798. if (LastTipSeen < Tips->Count - 1)
  1799. {
  1800. Result = Tips->Strings[LastTipSeen + 1];
  1801. }
  1802. return Result;
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. class TTipsData : public TComponent
  1806. {
  1807. public:
  1808. __fastcall TTipsData() :
  1809. TComponent(NULL)
  1810. {
  1811. }
  1812. int Index;
  1813. TStringList * Tips;
  1814. static TTipsData * __fastcall Retrieve(TObject * Object)
  1815. {
  1816. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1817. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1818. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1819. }
  1820. };
  1821. //---------------------------------------------------------------------------
  1822. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1823. {
  1824. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1825. }
  1826. //---------------------------------------------------------------------------
  1827. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1828. {
  1829. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1830. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(YesButtonName)));
  1831. PrevButton->Enabled = (TipsData->Index > 0);
  1832. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1833. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1834. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(FindComponentRecursively(Form, MainMessageLabelName)));
  1835. MessageLabel->Caption = TipsMessage(TipsData);
  1836. }
  1837. //---------------------------------------------------------------------------
  1838. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1839. {
  1840. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1841. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1842. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1843. }
  1844. //---------------------------------------------------------------------------
  1845. static void __fastcall TipSeen(const UnicodeString & Tip)
  1846. {
  1847. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1848. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1849. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1850. WinConfiguration->TipsShown = Now();
  1851. WinConfiguration->RunsSinceLastTip = 0;
  1852. // prevent parallel app instances showing the same tip
  1853. WinConfiguration->Save();
  1854. }
  1855. //---------------------------------------------------------------------------
  1856. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender, unsigned int & /*Answer*/)
  1857. {
  1858. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1859. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1860. TipsData->Index += reinterpret_cast<int>(Data);
  1861. UpdateTipsForm(Form);
  1862. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1863. UnicodeString Url = TipUrl(TipsData);
  1864. NavigateMessageDialogToUrl(Form, Url);
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. static void __fastcall ShowTip(bool AutoShow)
  1868. {
  1869. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1870. UnicodeString Tip = FirstUnshownTip();
  1871. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1872. Tips->CaseSensitive = false;
  1873. int Index;
  1874. if (Tip.IsEmpty())
  1875. {
  1876. Index = Tips->Count - 1;
  1877. Tip = Tips->Strings[Index];
  1878. }
  1879. else
  1880. {
  1881. Index = Tips->IndexOf(Tip);
  1882. }
  1883. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1884. TipsData->Name = TTipsData::QualifiedClassName();
  1885. TipsData->Index = Index;
  1886. TipsData->Tips = Tips.get();
  1887. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1888. TQueryButtonAlias Aliases[3];
  1889. Aliases[0].Button = qaYes;
  1890. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1891. Aliases[0].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1892. Aliases[1].Button = qaNo;
  1893. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1894. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1895. Aliases[2].Button = qaCancel;
  1896. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1897. TMessageParams Params;
  1898. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1899. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1900. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1901. Params.Aliases = Aliases;
  1902. Params.AliasesCount = LENOF(Aliases);
  1903. Params.ImageName = L"Bulb On n p";
  1904. if (AutoShow)
  1905. {
  1906. // Won't be used automatically as we have more than the "OK" button
  1907. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1908. Params.NeverAskAgainAnswer = qaCancel;
  1909. Params.Params |= mpNeverAskAgainCheck;
  1910. }
  1911. int Answers = qaYes | qaNo | qaCancel;
  1912. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1913. Dialog->InsertComponent(TipsData.release());
  1914. UpdateTipsForm(Dialog.get());
  1915. TipSeen(Tip);
  1916. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1917. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1918. {
  1919. WinConfiguration->ShowTips = false;
  1920. }
  1921. WinConfiguration->Updates = Updates;
  1922. }
  1923. //---------------------------------------------------------------------------
  1924. void __fastcall AutoShowNewTip()
  1925. {
  1926. Configuration->Usage->Inc(L"TipsShownAuto");
  1927. ShowTip(true);
  1928. }
  1929. //---------------------------------------------------------------------------
  1930. void __fastcall ShowTips()
  1931. {
  1932. {
  1933. TOperationVisualizer Visualizer;
  1934. DoQueryUpdates(false);
  1935. }
  1936. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1937. {
  1938. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1939. }
  1940. Configuration->Usage->Inc(L"TipsShownCommand");
  1941. ShowTip(false);
  1942. }
  1943. //---------------------------------------------------------------------------
  1944. void __fastcall TipsUpdateStaticUsage()
  1945. {
  1946. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1947. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1948. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1949. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1950. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. static void ReadNetVersion(TRegistryStorage * Registry)
  1954. {
  1955. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  1956. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  1957. {
  1958. NetVersionStr = VersionStr;
  1959. }
  1960. }
  1961. //---------------------------------------------------------------------------
  1962. UnicodeString __fastcall GetNetVersionStr()
  1963. {
  1964. if (NetVersionStr.IsEmpty())
  1965. {
  1966. NetVersionStr = L"0"; // not to retry on failure
  1967. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  1968. if (Registry->OpenRootKey(false))
  1969. {
  1970. std::unique_ptr<TStringList> Keys(new TStringList());
  1971. Registry->GetSubKeyNames(Keys.get());
  1972. for (int Index = 0; Index < Keys->Count; Index++)
  1973. {
  1974. UnicodeString Key = Keys->Strings[Index];
  1975. if (Registry->OpenSubKey(Key, false))
  1976. {
  1977. ReadNetVersion(Registry.get());
  1978. if (Registry->OpenSubKey(L"Full", false))
  1979. {
  1980. ReadNetVersion(Registry.get());
  1981. Registry->CloseSubKey();
  1982. }
  1983. if (Registry->OpenSubKey(L"Client", false))
  1984. {
  1985. ReadNetVersion(Registry.get());
  1986. Registry->CloseSubKey();
  1987. }
  1988. Registry->CloseSubKey();
  1989. }
  1990. }
  1991. }
  1992. }
  1993. return NetVersionStr;
  1994. }
  1995. //---------------------------------------------------------------------------
  1996. UnicodeString __fastcall GetPowerShellVersionStr()
  1997. {
  1998. if (PowerShellVersionStr.IsEmpty())
  1999. {
  2000. PowerShellVersionStr = 0; // not to retry on failure
  2001. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2002. if (Registry->OpenRootKey(false))
  2003. {
  2004. std::unique_ptr<TStringList> Keys(new TStringList());
  2005. Registry->GetSubKeyNames(Keys.get());
  2006. for (int Index = 0; Index < Keys->Count; Index++)
  2007. {
  2008. UnicodeString Key = Keys->Strings[Index];
  2009. if (Registry->OpenSubKey(Key + L"\\PowerShellEngine", false, true))
  2010. {
  2011. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2012. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2013. {
  2014. PowerShellVersionStr = VersionStr;
  2015. }
  2016. Registry->CloseSubKey();
  2017. }
  2018. }
  2019. }
  2020. }
  2021. return PowerShellVersionStr;
  2022. }