Setup.cpp 70 KB

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