Setup.cpp 71 KB

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