Setup.cpp 71 KB

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