Setup.cpp 69 KB

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