1
0

Setup.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716
  1. //---------------------------------------------------------------------------
  2. // Part of this code is
  3. // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
  4. //---------------------------------------------------------------------------
  5. #include <vcl.h>
  6. #pragma hdrstop
  7. #include <stdio.h>
  8. #include <tchar.h>
  9. #include <shlobj.h>
  10. #include <tlhelp32.h>
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <Exceptions.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <HelpWin.h>
  17. #include <Http.h>
  18. #include <CompThread.hpp>
  19. #include <FileInfo.h>
  20. #include "WinConfiguration.h"
  21. #include "WinInterface.h"
  22. #include "Tools.h"
  23. #include "Setup.h"
  24. #include <StrUtils.hpp>
  25. #include "ProgParams.h"
  26. #include <Consts.hpp>
  27. #include <GUITools.h>
  28. #include <PuttyTools.h>
  29. #include <VCLCommon.h>
  30. #include <WebBrowserEx.hpp>
  31. #include <DateUtils.hpp>
  32. #include <OperationWithTimeout.hpp>
  33. #include <Soap.HTTPUtil.hpp>
  34. #include <Web.HTTPApp.hpp>
  35. //---------------------------------------------------------------------------
  36. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  37. _T("Session Manager\\Environment")
  38. // when the PATH registry key is over aprox 2048 characters,
  39. // PATH as well as WINDIR variables are actually not set, breaking the system
  40. #define MAX_PATH_LEN 2000
  41. /* Command line options. */
  42. UnicodeString LastPathError;
  43. //---------------------------------------------------------------------------
  44. UnicodeString NetVersionStr;
  45. UnicodeString PowerShellVersionStr;
  46. //---------------------------------------------------------------------------
  47. // Display the error "err_msg".
  48. void err_out(LPCTSTR err_msg)
  49. {
  50. LastPathError = err_msg;
  51. }
  52. //---------------------------------------------------------------------------
  53. // Display "base_err_msg" followed by the description of the system error
  54. // identified by "sys_err".
  55. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  56. {
  57. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  58. }
  59. //---------------------------------------------------------------------------
  60. // Works as "strcmp" but the comparison is not case sensitive.
  61. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  62. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  63. if (*str1 == L'\0')
  64. return 0;
  65. return tolower(*str1) - tolower(*str2);
  66. }
  67. //---------------------------------------------------------------------------
  68. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  69. // not present). The returned value must be freed with "free".
  70. LPTSTR unquote(LPCTSTR str){
  71. int last_pos;
  72. LPTSTR ret;
  73. size_t new_len;
  74. last_pos = _tcslen(str) - 1;
  75. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  76. new_len= (_tcslen(str) - 1);
  77. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  78. lstrcpyn(ret, &str[1], new_len);
  79. }
  80. else
  81. ret = _tcsdup(str);
  82. return ret;
  83. }
  84. //---------------------------------------------------------------------------
  85. // Find "what" in the ";" separated string "str" and returns a pointer to
  86. // the first letter of "what" in the string. If "next" is not "NULL" it
  87. // points to the first letter after "what" (excluding the trailing ";").
  88. // If "what" isn't find the functions returns "NULL".
  89. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  90. LPTSTR tok_buff;
  91. LPTSTR curr_tok;
  92. LPTSTR curr_tok_dup;
  93. BOOL path_eq;
  94. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  95. int pos = -1;
  96. LPTSTR ret;
  97. tok_buff = _tcsdup(str);
  98. curr_tok = _tcstok(tok_buff, _T(";"));
  99. while (pos == -1 && curr_tok){
  100. curr_tok_dup = unquote(curr_tok);
  101. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  102. GetShortPathName(curr_tok_dup, sh_path2,
  103. LENOF(sh_path2)) &&
  104. (tcharicmp(sh_path1, sh_path2) == 0);
  105. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  106. pos = curr_tok - tok_buff;
  107. }
  108. free(curr_tok_dup);
  109. curr_tok = _tcstok(NULL, _T(";"));
  110. if (pos != -1 && next){
  111. if (curr_tok)
  112. *next = str + (curr_tok - tok_buff);
  113. else
  114. *next = str + _tcslen(str);
  115. }
  116. }
  117. free(tok_buff);
  118. if (pos != -1)
  119. ret = str + pos;
  120. else
  121. ret = NULL;
  122. return ret;
  123. }
  124. //---------------------------------------------------------------------------
  125. void path_reg_propagate()
  126. {
  127. DWORD send_message_result;
  128. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  129. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  130. 5000, &send_message_result);
  131. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  132. {
  133. err_out_sys(_T("Cannot propagate the new enviroment to ")
  134. _T("other processes. The new value will be ")
  135. _T("available after a reboot."), GetLastError());
  136. SimpleErrorDialog(LastPathError);
  137. LastPathError = L"";
  138. }
  139. }
  140. //---------------------------------------------------------------------------
  141. // Add "path" to the registry. Return "TRUE" if the path has been added or
  142. // was already in the registry, "FALSE" otherwise.
  143. BOOL add_path_reg(LPCTSTR path){
  144. HKEY key;
  145. LONG ret;
  146. DWORD data_size;
  147. LPTSTR reg_str;
  148. BOOL func_ret = TRUE;
  149. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  150. KEY_WRITE | KEY_READ, &key);
  151. if (ret != ERROR_SUCCESS){
  152. err_out_sys(_T("Cannot open registry."), ret);
  153. return FALSE;
  154. }
  155. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  156. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  157. includes '\0'. */
  158. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  159. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  160. &data_size);
  161. if (ret != ERROR_SUCCESS){
  162. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  163. func_ret = FALSE;
  164. }
  165. else{
  166. if (!find_reg_str(reg_str, path, NULL)){
  167. _tcscat(reg_str, _T(";"));
  168. _tcscat(reg_str, path);
  169. size_t len = _tcslen(reg_str);
  170. if (len >= MAX_PATH_LEN)
  171. {
  172. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  173. func_ret = FALSE;
  174. }
  175. else
  176. {
  177. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  178. (LPBYTE)reg_str,
  179. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  180. if (ret != ERROR_SUCCESS){
  181. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  182. func_ret = FALSE;
  183. }
  184. /* Is this needed to make the new key avaible? */
  185. RegFlushKey(key);
  186. SetLastError(0);
  187. path_reg_propagate();
  188. }
  189. }
  190. }
  191. RegCloseKey(key);
  192. free(reg_str);
  193. return func_ret;
  194. }
  195. //---------------------------------------------------------------------------
  196. // Removes "path" from the registry. Return "TRUE" if the path has been
  197. // removed or it wasn't in the registry, "FALSE" otherwise.
  198. BOOL remove_path_reg(LPCTSTR path){
  199. HKEY key;
  200. LONG ret;
  201. DWORD data_size;
  202. LPTSTR reg_str;
  203. LPTSTR reg_str2;
  204. BOOL func_ret = TRUE;
  205. LPTSTR next;
  206. LPTSTR del_part;
  207. int last_pos;
  208. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  209. KEY_WRITE | KEY_READ, &key);
  210. if (ret != ERROR_SUCCESS){
  211. err_out_sys(_T("Cannot open registry."), ret);
  212. return FALSE;
  213. }
  214. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  215. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  216. includes '\0'. */
  217. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  218. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  219. (LPBYTE)reg_str, &data_size);
  220. if (ret != ERROR_SUCCESS){
  221. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  222. func_ret = FALSE;
  223. }
  224. else{
  225. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  226. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  227. *del_part = '\0';
  228. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  229. last_pos = _tcslen(reg_str2) - 1;
  230. if (last_pos != -1 && reg_str2[last_pos] == ';')
  231. reg_str2[last_pos] = '\0';
  232. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  233. (LPBYTE)reg_str2,
  234. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  235. if (ret != ERROR_SUCCESS){
  236. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  237. func_ret = FALSE;
  238. }
  239. free(reg_str2);
  240. /* Is this needed to make the new key avaible? */
  241. RegFlushKey(key);
  242. SetLastError(0);
  243. path_reg_propagate();
  244. }
  245. }
  246. RegCloseKey(key);
  247. free(reg_str);
  248. return func_ret;
  249. }
  250. //---------------------------------------------------------------------------
  251. //---------------------------------------------------------------------------
  252. void __fastcall AddSearchPath(const UnicodeString Path)
  253. {
  254. if (!add_path_reg(Path.c_str()))
  255. {
  256. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  257. }
  258. }
  259. //---------------------------------------------------------------------------
  260. void __fastcall RemoveSearchPath(const UnicodeString Path)
  261. {
  262. if (!remove_path_reg(Path.c_str()))
  263. {
  264. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  265. }
  266. }
  267. //---------------------------------------------------------------------------
  268. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  269. //---------------------------------------------------------------------------
  270. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  271. {
  272. if (Registry->OpenKey(Key, false))
  273. {
  274. std::unique_ptr<TStrings> List(new TStringList());
  275. Registry->GetValueNames(List.get());
  276. bool CanDelete = true;
  277. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  278. {
  279. UnicodeString ValueName = List->Strings[Index];
  280. if (!AllowRootValues)
  281. {
  282. CanDelete = false;
  283. }
  284. if ((ValueName != L"") &&
  285. (ValueName != L"URL Protocol") &&
  286. (ValueName != L"EditFlags") &&
  287. (ValueName != L"BrowserFlags"))
  288. {
  289. CanDelete = false;
  290. }
  291. }
  292. List->Clear();
  293. Registry->GetKeyNames(List.get());
  294. Registry->CloseKey();
  295. if (CanDelete)
  296. {
  297. for (int Index = 0; Index < List->Count; Index++)
  298. {
  299. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  300. }
  301. // will fail, if not all subkeys got removed
  302. Registry->DeleteKey(Key);
  303. }
  304. }
  305. }
  306. //---------------------------------------------------------------------------
  307. static void __fastcall RegisterProtocol(TRegistry * Registry,
  308. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  309. {
  310. if (Description.IsEmpty())
  311. {
  312. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  313. }
  314. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  315. if (Force || !Registry->KeyExists(ProtocolKey))
  316. {
  317. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  318. {
  319. Registry->WriteString(L"", Description);
  320. Registry->WriteString(L"URL Protocol", L"");
  321. Registry->WriteInteger(L"EditFlags", 0x02);
  322. Registry->WriteInteger(L"BrowserFlags", 0x08);
  323. if (Registry->OpenKey(L"DefaultIcon", true))
  324. {
  325. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  326. Registry->CloseKey();
  327. }
  328. else
  329. {
  330. Abort();
  331. }
  332. }
  333. else
  334. {
  335. Abort();
  336. }
  337. }
  338. }
  339. //---------------------------------------------------------------------------
  340. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  341. const UnicodeString & Protocol)
  342. {
  343. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  344. }
  345. //---------------------------------------------------------------------------
  346. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  347. {
  348. std::unique_ptr<TRegistry> Registry(new TRegistry());
  349. Registry->Access = KEY_WRITE | KEY_READ;
  350. Registry->RootKey = RootKey;
  351. return Registry.release();
  352. }
  353. //---------------------------------------------------------------------------
  354. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  355. const UnicodeString & Protocol, UnicodeString Description = L"")
  356. {
  357. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  358. RegisterProtocol(Registry.get(), Protocol, Description, true);
  359. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  360. Registry->OpenKey(L"shell", true) &&
  361. Registry->OpenKey(L"open", true) &&
  362. Registry->OpenKey(L"command", true))
  363. {
  364. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  365. Registry->CloseKey();
  366. }
  367. else
  368. {
  369. Abort();
  370. }
  371. }
  372. //---------------------------------------------------------------------------
  373. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  374. {
  375. try
  376. {
  377. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  378. // get rid of any HKCU registraction that would overrite the HKLM one
  379. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  380. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  381. {
  382. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  383. }
  384. }
  385. catch (Exception & E)
  386. {
  387. try
  388. {
  389. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  390. }
  391. catch(Exception & E)
  392. {
  393. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  394. }
  395. }
  396. }
  397. //---------------------------------------------------------------------------
  398. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  399. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  400. {
  401. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  402. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  403. if (Registry->OpenKey(DefaultIconKey, false))
  404. {
  405. UnicodeString Value = Registry->ReadString(L"");
  406. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  407. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  408. {
  409. Registry->DeleteValue(L"");
  410. }
  411. Registry->CloseKey();
  412. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  413. }
  414. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  415. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  416. {
  417. UnicodeString Value = Registry->ReadString(L"");
  418. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  419. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  420. {
  421. Registry->DeleteValue(L"");
  422. }
  423. Registry->CloseKey();
  424. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  425. }
  426. if (UnregisterProtocol)
  427. {
  428. ::UnregisterProtocol(Registry.get(), Protocol);
  429. }
  430. }
  431. //---------------------------------------------------------------------------
  432. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  433. {
  434. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  435. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  436. }
  437. //---------------------------------------------------------------------------
  438. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  439. {
  440. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  441. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  442. RegisterAsUrlHandler(Prefix + WebDAVProtocol.UpperCase());
  443. RegisterAsUrlHandler(Prefix + WebDAVSProtocol.UpperCase());
  444. RegisterAsUrlHandler(Prefix + S3Protocol.UpperCase());
  445. }
  446. //---------------------------------------------------------------------------
  447. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  448. {
  449. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  450. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  451. UnregisterAsUrlHandler(Prefix + WebDAVProtocol, UnregisterProtocol);
  452. UnregisterAsUrlHandler(Prefix + WebDAVSProtocol, UnregisterProtocol);
  453. UnregisterAsUrlHandler(Prefix + S3Protocol, UnregisterProtocol);
  454. }
  455. //---------------------------------------------------------------------------
  456. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  457. //---------------------------------------------------------------------------
  458. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  459. {
  460. // Register protocol, if it does not exist yet.
  461. // Prior to Windows 8, we need to register ourselves as legacy handler to
  462. // become the default handler. On Windows 8, it's automatic as long as no other
  463. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  464. RegisterAsUrlHandler(RootKey, Protocol);
  465. // see https://docs.microsoft.com/en-us/windows/win32/shell/default-programs#registering-an-application-for-use-with-default-programs
  466. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  467. // create capabilities record
  468. // this has to be a separate branch from WinSCP one, as by its presence we
  469. // enforce registry storage usage, and the capabilities branch may exist
  470. // even if we are using INI file
  471. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  472. if (!Registry->OpenKey(CapabilitiesKey, true))
  473. {
  474. Abort();
  475. }
  476. UnicodeString Description = LoadStr(REGISTERED_APP_DESC3);
  477. Registry->WriteString(L"ApplicationDescription", Description);
  478. if (!Registry->OpenKey(L"UrlAssociations", true))
  479. {
  480. Abort();
  481. }
  482. Registry->WriteString(Protocol, GenericUrlHandler);
  483. Registry->CloseKey();
  484. // register application
  485. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  486. {
  487. Abort();
  488. }
  489. Registry->WriteString(AppNameString(), CapabilitiesKey);
  490. Registry->CloseKey();
  491. }
  492. //---------------------------------------------------------------------------
  493. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  494. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  495. {
  496. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  497. // unregister the protocol
  498. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  499. // remove capabilities record
  500. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  501. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  502. if (Registry->OpenKey(UrlAssociationsKey, false))
  503. {
  504. Registry->DeleteValue(Protocol);
  505. Registry->CloseKey();
  506. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  507. }
  508. if (Registry->OpenKey(CapabilitiesKey, false))
  509. {
  510. if (!Registry->HasSubKeys())
  511. {
  512. Registry->DeleteValue(L"ApplicationDescription");
  513. }
  514. Registry->CloseKey();
  515. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  516. }
  517. if (!Registry->KeyExists(CapabilitiesKey))
  518. {
  519. // unregister application
  520. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  521. {
  522. Registry->DeleteValue(AppNameString());
  523. Registry->CloseKey();
  524. }
  525. }
  526. }
  527. //---------------------------------------------------------------------------
  528. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  529. {
  530. // register URL handler, if it does not exist yet
  531. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  532. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  533. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  534. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  535. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  536. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  537. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  538. RegisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol);
  539. RegisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol);
  540. RegisterProtocolForDefaultPrograms(RootKey, S3Protocol);
  541. // deliberately not including http,
  542. // it's unlikely that anyone would like to change http handler
  543. // to non-browser application
  544. }
  545. //---------------------------------------------------------------------------
  546. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  547. {
  548. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  549. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  550. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  551. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  552. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  553. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol, ForceHandlerUnregistration);
  554. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol, ForceHandlerUnregistration);
  555. UnregisterProtocolForDefaultPrograms(RootKey, S3Protocol, ForceHandlerUnregistration);
  556. // we should not really need the "force" flag here, but why not
  557. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  558. }
  559. //---------------------------------------------------------------------------
  560. static void __fastcall RegisterForDefaultPrograms()
  561. {
  562. try
  563. {
  564. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  565. // make sure we unregister any legacy protocol handler for CU,
  566. // this is needed for Windows Vista+7
  567. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  568. }
  569. catch (Exception & E)
  570. {
  571. try
  572. {
  573. // Maybe we should skip this if HKLM key existed already (we are running non-privileged)
  574. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  575. }
  576. catch (Exception & E)
  577. {
  578. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  579. }
  580. }
  581. }
  582. //---------------------------------------------------------------------------
  583. static void __fastcall NotifyChangedAssociations()
  584. {
  585. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  586. }
  587. //---------------------------------------------------------------------------
  588. void __fastcall RegisterForDefaultProtocols()
  589. {
  590. if (IsWinVista())
  591. {
  592. RegisterForDefaultPrograms();
  593. }
  594. else
  595. {
  596. RegisterAsNonBrowserUrlHandler(UnicodeString());
  597. }
  598. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  599. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  600. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  601. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  602. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  603. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  604. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  605. NotifyChangedAssociations();
  606. }
  607. //---------------------------------------------------------------------------
  608. void __fastcall UnregisterForProtocols()
  609. {
  610. UnregisterAsUrlHandlers(UnicodeString(), false);
  611. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  612. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  613. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  614. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  615. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  616. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  617. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  618. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  619. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  620. NotifyChangedAssociations();
  621. }
  622. //---------------------------------------------------------------------------
  623. void __fastcall LaunchAdvancedAssociationUI()
  624. {
  625. DebugAssert(IsWinVista());
  626. RegisterForDefaultPrograms();
  627. NotifyChangedAssociations();
  628. // sleep recommended by https://docs.microsoft.com/en-us/windows/win32/shell/default-programs#becoming-the-default-browser
  629. Sleep(1000);
  630. if (IsWin10())
  631. {
  632. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  633. // https://stackoverflow.com/q/32178986/850848
  634. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  635. IOpenControlPanel * OpenControlPanel;
  636. HRESULT Result =
  637. CoCreateInstance(CLSID_OpenControlPanel,
  638. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  639. if (SUCCEEDED(Result))
  640. {
  641. // This does not work anymore since April 2018 Update, it now has the same effect as mere "pageDefaultProgram".
  642. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  643. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  644. OpenControlPanel->Release();
  645. }
  646. }
  647. else
  648. {
  649. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  650. HRESULT Result =
  651. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  652. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  653. if (SUCCEEDED(Result))
  654. {
  655. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  656. AppAssocRegUI->Release();
  657. }
  658. }
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TemporaryDirectoryCleanup()
  662. {
  663. std::unique_ptr<TStrings> Folders(WinConfiguration->FindTemporaryFolders());
  664. if (Folders.get() != NULL)
  665. {
  666. bool Continue = true;
  667. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  668. {
  669. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  670. TQueryButtonAlias Aliases[1];
  671. Aliases[0].Button = qaRetry;
  672. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  673. TMessageParams Params(mpNeverAskAgainCheck);
  674. Params.Aliases = Aliases;
  675. Params.AliasesCount = LENOF(Aliases);
  676. unsigned int Answer = MoreMessageDialog(
  677. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders.get(),
  678. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  679. if (Answer == qaNeverAskAgain)
  680. {
  681. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  682. Answer = qaYes;
  683. }
  684. else if (Answer == qaRetry)
  685. {
  686. for (int Index = 0; Index < Folders->Count; Index++)
  687. {
  688. ShellExecute(Application->Handle, NULL,
  689. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  690. }
  691. }
  692. Continue = (Answer == qaYes);
  693. }
  694. if (Continue)
  695. {
  696. try
  697. {
  698. WinConfiguration->CleanupTemporaryFolders(Folders.get());
  699. }
  700. catch (Exception &E)
  701. {
  702. ShowExtendedException(&E);
  703. }
  704. }
  705. }
  706. }
  707. //-------------------------------------------- -------------------------------
  708. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  709. {
  710. int MajorVer = Version / (10000*100*100);
  711. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  712. int Release = (Version % (10000*100)) / (10000);
  713. UnicodeString Result;
  714. if (Release > 0)
  715. {
  716. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  717. }
  718. else
  719. {
  720. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  721. }
  722. return Result;
  723. }
  724. //---------------------------------------------------------------------------
  725. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  726. {
  727. int CurrentCompoundVer = Configuration->CompoundVersion;
  728. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  729. UnicodeString Medium = IsUWP() ? L"uwp" : L"app";
  730. // Beware that these parameters may get truncated if URL is too long,
  731. // such as with ERROR_REPORT_URL2
  732. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=%s&utm_campaign=%s", (Medium, Version));
  733. return AppendUrlParams(URL, Params);
  734. }
  735. //---------------------------------------------------------------------------
  736. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  737. {
  738. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  739. UnicodeString CurrentVersionStr =
  740. FORMAT(L"%d.%d.%d.%d",
  741. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  742. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  743. UnicodeString Params =
  744. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  745. (CurrentVersionStr,
  746. GUIConfiguration->AppliedLocaleHex,
  747. int(IsInstalled())));
  748. if (Configuration->IsUnofficial)
  749. {
  750. Params += L"&unofficial=1";
  751. }
  752. return AppendUrlParams(URL, Params);
  753. }
  754. //---------------------------------------------------------------------------
  755. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  756. {
  757. bool Beta;
  758. if (WinConfiguration->IsBeta)
  759. {
  760. Beta = true;
  761. }
  762. else
  763. {
  764. switch (WinConfiguration->Updates.BetaVersions)
  765. {
  766. case asAuto:
  767. Beta = WinConfiguration->AnyBetaInVersionHistory;
  768. break;
  769. case asOn:
  770. Beta = true;
  771. break;
  772. default:
  773. Beta = false;
  774. break;
  775. }
  776. }
  777. if (Beta || Force)
  778. {
  779. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  780. }
  781. return URL;
  782. }
  783. //---------------------------------------------------------------------------
  784. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  785. {
  786. std::unique_ptr<THttp> Http(new THttp());
  787. UnicodeString ProxyHost;
  788. int ProxyPort = 0;
  789. switch (Updates.ConnectionType)
  790. {
  791. case ctAuto:
  792. if (AutodetectProxy(ProxyHost, ProxyPort))
  793. {
  794. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  795. }
  796. break;
  797. case ctProxy:
  798. ProxyHost = Updates.ProxyHost;
  799. ProxyPort = Updates.ProxyPort;
  800. Configuration->Usage->Inc(L"UpdateProxyManual");
  801. break;
  802. }
  803. Http->ProxyHost = ProxyHost;
  804. Http->ProxyPort = ProxyPort;
  805. return Http.release();
  806. }
  807. //---------------------------------------------------------------------------
  808. THttp * __fastcall CreateHttp()
  809. {
  810. return CreateHttp(WinConfiguration->Updates);
  811. }
  812. //---------------------------------------------------------------------------
  813. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  814. {
  815. bool Complete = false;
  816. UnicodeString Response;
  817. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  818. try
  819. {
  820. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  821. URL = WantBetaUrl(URL, false);
  822. URL += L"&dotnet=" + Updates.DotNetVersion;
  823. URL += L"&console=" + Updates.ConsoleVersion;
  824. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  825. if (!LocaleVersion.IsEmpty())
  826. {
  827. URL += L"&localever=" + LocaleVersion;
  828. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  829. }
  830. // Even if donor email is inherited from normal installation,
  831. // do not use it as this all is merely to report usage statistics, not to check for updates, in UWP.
  832. if (!Updates.AuthenticationEmail.IsEmpty() && !IsUWP())
  833. {
  834. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  835. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  836. }
  837. CheckForUpdatesHTTP->URL = URL;
  838. // sanity check
  839. CheckForUpdatesHTTP->ResponseLimit = 102400;
  840. try
  841. {
  842. if (CollectUsage)
  843. {
  844. UnicodeString Usage = Configuration->Usage->Serialize();
  845. CheckForUpdatesHTTP->Post(Usage);
  846. }
  847. else
  848. {
  849. CheckForUpdatesHTTP->Get();
  850. }
  851. }
  852. catch (...)
  853. {
  854. if (CheckForUpdatesHTTP->IsCertificateError())
  855. {
  856. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  857. }
  858. throw;
  859. }
  860. Response = CheckForUpdatesHTTP->Response;
  861. }
  862. __finally
  863. {
  864. delete CheckForUpdatesHTTP;
  865. }
  866. int CurrentCompoundVer = Configuration->CompoundVersion;
  867. bool Changed = !Updates.HaveResults;
  868. Updates.LastCheck = Now();
  869. Updates.HaveResults = true;
  870. TUpdatesData PrevResults = Updates.Results;
  871. Updates.Results.Reset();
  872. Updates.Results.ForVersion = CurrentCompoundVer;
  873. while (!Response.IsEmpty())
  874. {
  875. UnicodeString Line = CutToChar(Response, L'\n', false);
  876. UnicodeString Name = CutToChar(Line, L'=', false);
  877. if (SameText(Name, "Version"))
  878. {
  879. int NewVersion = StrToCompoundVersion(Line);
  880. Changed |= (NewVersion != PrevResults.Version);
  881. if (NewVersion <= CurrentCompoundVer)
  882. {
  883. NewVersion = 0;
  884. }
  885. Updates.Results.Version = NewVersion;
  886. Complete = true;
  887. }
  888. else if (SameText(Name, L"Message"))
  889. {
  890. Changed |= (PrevResults.Message != Line);
  891. Updates.Results.Message = Line;
  892. }
  893. else if (SameText(Name, L"Critical"))
  894. {
  895. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  896. Changed |= (PrevResults.Critical != NewCritical);
  897. Updates.Results.Critical = NewCritical;
  898. }
  899. else if (SameText(Name, L"Release"))
  900. {
  901. Changed |= (PrevResults.Release != Line);
  902. Updates.Results.Release = Line;
  903. }
  904. else if (SameText(Name, L"Disabled"))
  905. {
  906. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  907. Changed |= (PrevResults.Disabled != NewDisabled);
  908. Updates.Results.Disabled = NewDisabled;
  909. Complete = true;
  910. }
  911. else if (SameText(Name, L"Url"))
  912. {
  913. Changed |= (PrevResults.Url != Line);
  914. Updates.Results.Url = Line;
  915. }
  916. else if (SameText(Name, L"UrlButton"))
  917. {
  918. Changed |= (PrevResults.UrlButton != Line);
  919. Updates.Results.UrlButton = Line;
  920. }
  921. else if (SameText(Name, L"NewsUrl"))
  922. {
  923. Changed |= (PrevResults.NewsUrl != Line);
  924. Updates.Results.NewsUrl = Line;
  925. }
  926. else if (SameText(Name, L"NewsSize"))
  927. {
  928. TSize NewsSize;
  929. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  930. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  931. Changed |= (PrevResults.NewsSize != NewsSize);
  932. Updates.Results.NewsSize = NewsSize;
  933. }
  934. else if (SameText(Name, L"DownloadUrl"))
  935. {
  936. Changed |= (PrevResults.DownloadUrl != Line);
  937. Updates.Results.DownloadUrl = Line;
  938. }
  939. else if (SameText(Name, L"DownloadSize"))
  940. {
  941. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  942. }
  943. else if (SameText(Name, L"DownloadSha256"))
  944. {
  945. Updates.Results.DownloadSha256 = Line;
  946. }
  947. else if (SameText(Name, L"AuthenticationError"))
  948. {
  949. Changed |= (PrevResults.AuthenticationError != Line);
  950. Updates.Results.AuthenticationError = Line;
  951. }
  952. else if (SameText(Name, L"OpenGettingStarted"))
  953. {
  954. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  955. }
  956. else if (SameText(Name, L"DownloadingUrl"))
  957. {
  958. Updates.Results.DownloadingUrl = Line;
  959. }
  960. else if (SameText(Name, L"TipsSize"))
  961. {
  962. TSize TipsSize;
  963. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  964. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  965. Updates.Results.TipsSize = TipsSize;
  966. }
  967. else if (SameText(Name, L"TipsUrl"))
  968. {
  969. Updates.Results.TipsUrl = Line;
  970. }
  971. else if (SameText(Name, L"Tips"))
  972. {
  973. Updates.Results.Tips = Line;
  974. }
  975. else if (SameText(Name, L"TipsIntervalDays"))
  976. {
  977. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  978. if (TipsIntervalDays < 0)
  979. {
  980. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  981. }
  982. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  983. }
  984. else if (SameText(Name, L"TipsIntervalRuns"))
  985. {
  986. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  987. if (TipsIntervalRuns < 0)
  988. {
  989. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  990. }
  991. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  992. }
  993. }
  994. if (Changed)
  995. {
  996. Updates.ShownResults = false;
  997. }
  998. return Complete;
  999. }
  1000. //---------------------------------------------------------------------------
  1001. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1002. {
  1003. return DoQueryUpdates(Updates, false);
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1007. {
  1008. try
  1009. {
  1010. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1011. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1012. WinConfiguration->Updates = Updates;
  1013. if (!Complete)
  1014. {
  1015. EXCEPTION;
  1016. }
  1017. Configuration->Usage->Reset();
  1018. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1019. }
  1020. catch(Exception & E)
  1021. {
  1022. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1023. UnicodeString Message;
  1024. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1025. {
  1026. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1027. }
  1028. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1029. }
  1030. }
  1031. //---------------------------------------------------------------------------
  1032. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  1033. {
  1034. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1035. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1036. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1037. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS2));
  1038. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1039. Message = ReplaceStr(Message, L"|", L"\n");
  1040. return Message;
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1044. TQueryType & Type, bool Force)
  1045. {
  1046. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1047. DebugAssert(Updates.HaveResults);
  1048. if (Updates.HaveResults)
  1049. {
  1050. if (Updates.Results.Disabled)
  1051. {
  1052. New = false;
  1053. if (Force)
  1054. {
  1055. Message = LoadStr(UPDATE_DISABLED);
  1056. }
  1057. }
  1058. else
  1059. {
  1060. New = (Updates.Results.Version > 0);
  1061. if (New)
  1062. {
  1063. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1064. if (!Updates.Results.Release.IsEmpty())
  1065. {
  1066. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1067. }
  1068. Message = FMTLOAD(NEW_VERSION4, (Version));
  1069. }
  1070. else
  1071. {
  1072. Message = LoadStr(NO_NEW_VERSION);
  1073. }
  1074. }
  1075. if (!Message.IsEmpty())
  1076. {
  1077. Message = MainInstructions(Message);
  1078. }
  1079. if (!Updates.Results.Message.IsEmpty())
  1080. {
  1081. Message +=
  1082. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1083. }
  1084. if (!Updates.Results.AuthenticationError.IsEmpty())
  1085. {
  1086. Message +=
  1087. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1088. }
  1089. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1090. }
  1091. else
  1092. {
  1093. New = false;
  1094. }
  1095. }
  1096. //---------------------------------------------------------------------------
  1097. void __fastcall EnableAutomaticUpdates()
  1098. {
  1099. ShowHelp(HELP_AUTOMATIC_UPDATE);
  1100. }
  1101. //---------------------------------------------------------------------------
  1102. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/, unsigned int & /*Answer*/)
  1103. {
  1104. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1105. OpenBrowser(LoadStr(HISTORY_URL));
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1109. {
  1110. return static_cast<int>(Size / 1024);
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. class TUpdateDownloadThread : public TCompThread
  1114. {
  1115. public:
  1116. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1117. virtual __fastcall ~TUpdateDownloadThread();
  1118. void __fastcall CancelClicked(TObject * Sender);
  1119. bool __fastcall CancelDownload();
  1120. __property bool Done = { read = FDone };
  1121. protected:
  1122. virtual void __fastcall Execute();
  1123. void __fastcall UpdateDownloaded();
  1124. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1125. void __fastcall UpdateProgress();
  1126. void __fastcall ShowException();
  1127. void __fastcall DownloadNotVerified();
  1128. void __fastcall CancelForm();
  1129. private:
  1130. TCustomForm * FForm;
  1131. TProgressBar * FProgressBar;
  1132. __int64 FDownloaded;
  1133. std::unique_ptr<Exception> FException;
  1134. std::unique_ptr<THttp> FHttp;
  1135. TUpdatesConfiguration FUpdates;
  1136. bool FDone;
  1137. };
  1138. //---------------------------------------------------------------------------
  1139. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1140. TCompThread(true)
  1141. {
  1142. // cache, as the progress bar miht be destroyed already when
  1143. // we need the form at the end of Execute()
  1144. FForm = GetParentForm(ProgressBar);
  1145. FProgressBar = ProgressBar;
  1146. // cache to prevent concurrency
  1147. FUpdates = WinConfiguration->Updates;
  1148. FDone = false;
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1152. {
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. void __fastcall TUpdateDownloadThread::Execute()
  1156. {
  1157. try
  1158. {
  1159. bool Retried = false;
  1160. bool Retry;
  1161. do
  1162. {
  1163. Retry = false;
  1164. try
  1165. {
  1166. FDownloaded = 0;
  1167. FHttp.reset(CreateHttp(FUpdates));
  1168. FHttp->URL = FUpdates.Results.DownloadUrl;
  1169. FHttp->OnDownload = HttpDownload;
  1170. FHttp->Get();
  1171. }
  1172. catch (EAbort &)
  1173. {
  1174. throw;
  1175. }
  1176. catch (Exception & E)
  1177. {
  1178. // The original URL failed, try to get a fresh one and retry
  1179. if (!Retried)
  1180. {
  1181. try
  1182. {
  1183. // Check if new update data (URL particlarly) is available
  1184. if (QueryUpdates(FUpdates) &&
  1185. !FUpdates.Results.DownloadUrl.IsEmpty())
  1186. {
  1187. Retry = true;
  1188. Retried = true;
  1189. }
  1190. }
  1191. catch (...)
  1192. {
  1193. }
  1194. }
  1195. if (!Retry)
  1196. {
  1197. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1198. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1199. }
  1200. }
  1201. }
  1202. while (Retry);
  1203. Synchronize(UpdateDownloaded);
  1204. }
  1205. catch (EAbort &)
  1206. {
  1207. // noop
  1208. }
  1209. catch (Exception & E)
  1210. {
  1211. Configuration->Usage->Inc(L"UpdateFailures");
  1212. FException.reset(CloneException(&E));
  1213. Synchronize(ShowException);
  1214. }
  1215. FDone = true;
  1216. Synchronize(CancelForm);
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. void __fastcall TUpdateDownloadThread::CancelForm()
  1220. {
  1221. FForm->ModalResult = mrCancel;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1225. {
  1226. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1227. const char * Buffer = FHttp->ResponseRaw.c_str();
  1228. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1229. {
  1230. DownloadNotVerified();
  1231. }
  1232. UnicodeString Digest = Sha256(Buffer, Size);
  1233. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1234. {
  1235. DownloadNotVerified();
  1236. }
  1237. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1238. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1239. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1240. UnicodeString SetupPath = SetupPathBase;
  1241. int Index = 0;
  1242. while (FileExists(SetupPath))
  1243. {
  1244. Index++;
  1245. SetupPath =
  1246. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1247. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1248. }
  1249. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1250. FileStream->Write(Buffer, Size);
  1251. FileStream.reset(NULL);
  1252. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1253. if (FUpdates.Results.OpenGettingStarted)
  1254. {
  1255. Params += L" /OpenGettingStarted";
  1256. }
  1257. ExecuteShellChecked(SetupPath, Params);
  1258. Configuration->Usage->Inc(L"UpdateRuns");
  1259. TerminateApplication();
  1260. }
  1261. //---------------------------------------------------------------------------
  1262. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1263. {
  1264. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1268. {
  1269. FDownloaded = Size;
  1270. Synchronize(UpdateProgress);
  1271. // Do not waste bandwidth, if something goes wrong
  1272. if (FDownloaded > FUpdates.Results.DownloadSize)
  1273. {
  1274. DownloadNotVerified();
  1275. }
  1276. if (Terminated)
  1277. {
  1278. Cancel = true;
  1279. }
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1283. {
  1284. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1285. }
  1286. //---------------------------------------------------------------------------
  1287. void __fastcall TUpdateDownloadThread::ShowException()
  1288. {
  1289. DebugAssert(FException.get() != NULL);
  1290. ShowExtendedException(FException.get());
  1291. }
  1292. //---------------------------------------------------------------------------
  1293. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1294. {
  1295. bool Result = !Terminated;
  1296. if (Result)
  1297. {
  1298. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1299. Terminate();
  1300. }
  1301. return Result;
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1305. {
  1306. if (CancelDownload())
  1307. {
  1308. WaitFor();
  1309. }
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. //---------------------------------------------------------------------------
  1313. class TUpdateDownloadData : public TComponent
  1314. {
  1315. public:
  1316. TUpdateDownloadThread * Thread;
  1317. __fastcall TUpdateDownloadData() :
  1318. TComponent(NULL)
  1319. {
  1320. }
  1321. virtual __fastcall ~TUpdateDownloadData()
  1322. {
  1323. // will stop the thread
  1324. delete Thread;
  1325. }
  1326. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1327. {
  1328. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1329. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1330. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1331. }
  1332. };
  1333. //---------------------------------------------------------------------------
  1334. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1335. {
  1336. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1337. // If the form was closed by CancelForm at the end of the thread, do nothing
  1338. if (!UpdateDownloadData->Thread->Done)
  1339. {
  1340. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1341. // May this should actually call CancelClicked?
  1342. if (UpdateDownloadData->Thread->CancelDownload())
  1343. {
  1344. Action = caNone;
  1345. }
  1346. }
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender, unsigned int & /*Answer*/)
  1350. {
  1351. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1352. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1353. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1354. TPanel * Panel = CreateBlankPanel(Form);
  1355. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1356. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1357. ProgressBar->Top = 0;
  1358. ProgressBar->Left = 0;
  1359. ProgressBar->Width = Panel->Width;
  1360. ProgressBar->Parent = Panel;
  1361. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1362. Panel->Height = ProgressBar->Height;
  1363. InsertPanelToMessageDialog(Form, Panel);
  1364. Button->Enabled = false;
  1365. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1366. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1367. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1368. // The form becomes owner of the thread (via TUpdateDownloadData),
  1369. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1370. // But it gets done only after the form controls are gone, and the thread
  1371. // might try to access them meanwhile. So we stop the thread explicitly.
  1372. CancelButton->OnClick = Thread->CancelClicked;
  1373. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1374. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1375. Data->Thread = Thread;
  1376. Form->InsertComponent(Data);
  1377. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1378. if (!DownloadingUrl.IsEmpty())
  1379. {
  1380. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1381. }
  1382. DebugAssert(Form->OnClose == NULL);
  1383. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1384. Thread->Resume();
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1388. {
  1389. EnableAutomaticUpdates();
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1393. {
  1394. const UnicodeString DonatePanelName = L"DonatePanel";
  1395. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1396. // OnShow can happen multiple times, for example when showing dialog on start up (being main window)
  1397. if (FindComponentRecursively(Dialog, DonatePanelName) == NULL)
  1398. {
  1399. UnicodeString DocumentBody = LoadStr(UPDATES_DONATE_HTML);
  1400. DocumentBody = ReplaceStr(DocumentBody, L"%DONATE_URL%", AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1"));
  1401. UnicodeString AboutStoreUrl = LoadStr(ABOUT_STORE_URL);
  1402. DocumentBody = ReplaceStr(DocumentBody, L"%STORE_URL%", AboutStoreUrl);
  1403. UnicodeString StoreButtonUrl = ProgramUrl(LoadStr(STORE_GET_IMG_URL));
  1404. StoreButtonUrl = HTMLEscape(StoreButtonUrl);
  1405. UnicodeString StoreButton =
  1406. FORMAT(L"<img src=\"%s\" style=\"height: 1.8em; vertical-align: -0.4em; padding-top: 0.2em; border: 0;\">", (StoreButtonUrl));
  1407. UnicodeString StoreUrl = FMTLOAD(STORE_URL, (L"update"));
  1408. UnicodeString StoreLink = FORMAT(L"<a href=\"%s\">%s</a>", (StoreUrl, StoreButton));
  1409. UnicodeString PlainBody = HTMLDecode(DocumentBody);
  1410. int P1, P2;
  1411. while (((P1 = PlainBody.Pos(L"<")) > 0) && ((P2 = PlainBody.Pos(L">")) > 0) && (P1 < P2))
  1412. {
  1413. PlainBody.Delete(P1, P2 - P1 + 1);
  1414. }
  1415. while ((P1 = PlainBody.Pos(L" ")) > 0)
  1416. {
  1417. PlainBody.Delete(P1, 1);
  1418. }
  1419. DocumentBody = ReplaceStr(DocumentBody, L"%GET_IMG% ", FORMAT(L"%s&nbsp;", (StoreLink)));
  1420. DocumentBody = FORMAT(L"<p>%s</p>", (DocumentBody));
  1421. TPanel * Panel = CreateBlankPanel(Dialog);
  1422. Panel->Name = DonatePanelName;
  1423. Panel->Caption = UnicodeString(); // override default use of Name
  1424. TWebBrowserEx * DonateBrowser = CreateBrowserViewer(Panel, UnicodeString());
  1425. ReadyBrowserForStreaming(DonateBrowser);
  1426. WaitBrowserToIdle(DonateBrowser);
  1427. int Height = 36;
  1428. int TextWidth = Dialog->Canvas->TextWidth(PlainBody);
  1429. int ContentLimit = (GetMessageDialogContentWidth(Dialog) * 5 / 3);
  1430. if (TextWidth > ContentLimit)
  1431. {
  1432. Height = Height * 3 / 2;
  1433. }
  1434. DonateBrowser->Height = ScaleByTextHeight(Dialog, Height);
  1435. DonateBrowser->Top = 0;
  1436. DonateBrowser->Left = 0;
  1437. Panel->Height = DonateBrowser->Height;
  1438. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1439. // (what should not happen)
  1440. InsertPanelToMessageDialog(Dialog, Panel);
  1441. UnicodeString Document = GenerateAppHtmlPage(Dialog->Font, Panel, DocumentBody, true);
  1442. LoadBrowserDocument(DonateBrowser, Document);
  1443. HideBrowserScrollbars(DonateBrowser);
  1444. }
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. bool __fastcall CheckForUpdates(bool CachedResults)
  1448. {
  1449. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1450. bool Result = false;
  1451. TOperationVisualizer Visualizer;
  1452. try
  1453. {
  1454. if (ActiveForm)
  1455. {
  1456. DebugAssert(ActiveForm->Enabled);
  1457. ActiveForm->Enabled = false;
  1458. }
  1459. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1460. bool Cached =
  1461. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1462. CachedResults;
  1463. if (!Cached)
  1464. {
  1465. DoQueryUpdates(WinConfiguration->CollectUsage);
  1466. // reread new data
  1467. Updates = WinConfiguration->Updates;
  1468. }
  1469. if (!Updates.ShownResults)
  1470. {
  1471. Updates.ShownResults = true;
  1472. WinConfiguration->Updates = Updates;
  1473. }
  1474. DebugAssert(Updates.HaveResults);
  1475. UnicodeString Message;
  1476. bool New;
  1477. TQueryType Type;
  1478. GetUpdatesMessage(Message, New, Type, true);
  1479. Configuration->Usage->Inc(L"UpdateDisplays");
  1480. if (New)
  1481. {
  1482. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1483. }
  1484. if (Updates.HaveResults &&
  1485. (double(Updates.Period) > 0) &&
  1486. // do not show next check time, if we have new version info
  1487. !New)
  1488. {
  1489. Message += L"\n\n" +
  1490. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1491. }
  1492. int Answers = qaOK |
  1493. // show "what's new" button only when change list URL was not provided in results
  1494. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1495. FLAGMASK(New, qaCancel) |
  1496. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1497. TQueryButtonAlias Aliases[4];
  1498. Aliases[0].Button = qaYes;
  1499. if (Updates.Results.UrlButton.IsEmpty())
  1500. {
  1501. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1502. }
  1503. else
  1504. {
  1505. Aliases[0].Alias = Updates.Results.UrlButton;
  1506. }
  1507. Aliases[1].Button = qaAll;
  1508. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1509. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, OpenHistory);
  1510. Aliases[2].Button = qaCancel;
  1511. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1512. // Used only when New == true, see AliasesCount below
  1513. Aliases[3].Button = qaOK;
  1514. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1515. if (!Updates.Results.DownloadUrl.IsEmpty())
  1516. {
  1517. Aliases[3].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, DownloadUpdate);
  1518. Aliases[3].ElevationRequired = true;
  1519. }
  1520. TMessageParams Params;
  1521. Params.Aliases = Aliases;
  1522. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1523. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1524. // alias "ok" button to "upgrade" only if we have new version
  1525. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1526. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1527. if (New)
  1528. {
  1529. Params.ImageName = L"Installer";
  1530. }
  1531. std::unique_ptr<TForm> Dialog(
  1532. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1533. if (New)
  1534. {
  1535. // Internet Explorer on Windows XP cannot talk to CDN77, where we host Store Get button.
  1536. // As a simple solution, we just do not display the donation panel on Windows XP.
  1537. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled() && IsWinVista())
  1538. {
  1539. DebugAssert(Dialog->OnShow == NULL);
  1540. // InsertDonateLink need to be called only after MessageBrowser is created
  1541. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1542. }
  1543. }
  1544. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1545. switch (Answer)
  1546. {
  1547. case qaOK:
  1548. if (New)
  1549. {
  1550. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1551. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1552. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1553. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1554. OpenBrowser(UpgradeUrl);
  1555. Result = true;
  1556. }
  1557. break;
  1558. case qaYes:
  1559. OpenBrowser(Updates.Results.Url);
  1560. break;
  1561. case qaAll:
  1562. DebugFail();
  1563. break;
  1564. }
  1565. }
  1566. __finally
  1567. {
  1568. if (ActiveForm)
  1569. {
  1570. ActiveForm->Enabled = true;
  1571. }
  1572. }
  1573. return Result;
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. class TUpdateThread : public TCompThread
  1577. {
  1578. public:
  1579. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1580. protected:
  1581. virtual void __fastcall Execute();
  1582. TThreadMethod FOnUpdatesChecked;
  1583. };
  1584. //---------------------------------------------------------------------------
  1585. TUpdateThread * UpdateThread = NULL;
  1586. //---------------------------------------------------------------------------
  1587. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1588. TCompThread(false),
  1589. FOnUpdatesChecked(OnUpdatesChecked)
  1590. {
  1591. }
  1592. //---------------------------------------------------------------------------
  1593. void __fastcall TUpdateThread::Execute()
  1594. {
  1595. try
  1596. {
  1597. DoQueryUpdates(WinConfiguration->CollectUsage);
  1598. if (FOnUpdatesChecked != NULL)
  1599. {
  1600. Synchronize(FOnUpdatesChecked);
  1601. }
  1602. }
  1603. catch(...)
  1604. {
  1605. // ignore errors
  1606. }
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1610. {
  1611. DebugAssert(UpdateThread == NULL);
  1612. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. void __fastcall StopUpdateThread()
  1616. {
  1617. if (UpdateThread != NULL)
  1618. {
  1619. SAFE_DESTROY(UpdateThread);
  1620. }
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. void __fastcall SetupInitialize()
  1624. {
  1625. try
  1626. {
  1627. WinConfiguration->UpdateJumpList();
  1628. }
  1629. catch (Exception & E)
  1630. {
  1631. ShowExtendedException(&E);
  1632. }
  1633. }
  1634. //---------------------------------------------------------------------------
  1635. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1636. UnicodeString AdditionalParams, TStringList * Removed,
  1637. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1638. int IconIndex)
  1639. {
  1640. bool Result = false;
  1641. IObjectCollection * Collection = NULL;
  1642. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1643. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1644. {
  1645. try
  1646. {
  1647. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1648. int Count = 0;
  1649. for (int Index = 0; Index < Names->Count; Index++)
  1650. {
  1651. IShellLink * Link =
  1652. CreateDesktopSessionShortCut(
  1653. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1654. wchar_t Desc[2048];
  1655. if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1656. {
  1657. if (Removed->IndexOf(Desc) < 0)
  1658. {
  1659. try
  1660. {
  1661. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1662. Count++;
  1663. }
  1664. __finally
  1665. {
  1666. Link->Release();
  1667. }
  1668. }
  1669. else
  1670. {
  1671. Names->Delete(Index);
  1672. Index--;
  1673. }
  1674. }
  1675. }
  1676. if (Count > 0)
  1677. {
  1678. IObjectArray * Array;
  1679. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1680. {
  1681. try
  1682. {
  1683. Result = SUCCEEDED(
  1684. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1685. }
  1686. __finally
  1687. {
  1688. Array->Release();
  1689. }
  1690. }
  1691. }
  1692. }
  1693. __finally
  1694. {
  1695. Collection->Release();
  1696. }
  1697. }
  1698. return Result;
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1702. {
  1703. ICustomDestinationList * DestinationList = NULL;
  1704. IObjectArray * RemovedArray;
  1705. TStringList * Removed = NULL;
  1706. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1707. try
  1708. {
  1709. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1710. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1711. {
  1712. unsigned int MinSlots;
  1713. HRESULT Result = DestinationListBeginList(DestinationList, MinSlots, IID_IObjectArray, reinterpret_cast<void *>(RemovedArray), 50000);
  1714. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1715. {
  1716. Removed = new TStringList();
  1717. unsigned int RemovedCount;
  1718. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1719. {
  1720. RemovedCount = 0;
  1721. }
  1722. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1723. {
  1724. IShellLink * Link;
  1725. wchar_t Desc[2048];
  1726. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1727. SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1728. {
  1729. Removed->Add(Desc);
  1730. }
  1731. }
  1732. AddJumpListCategory(
  1733. WorkspaceNames, L"", Removed, DestinationList,
  1734. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1735. AddJumpListCategory(
  1736. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1737. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1738. if (DestinationList != NULL)
  1739. {
  1740. DestinationList->CommitList();
  1741. }
  1742. }
  1743. }
  1744. }
  1745. __finally
  1746. {
  1747. SetErrorMode(OldErrMode);
  1748. if (DestinationList != NULL)
  1749. {
  1750. DestinationList->Release();
  1751. }
  1752. delete Removed;
  1753. }
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. bool __fastcall AnyOtherInstanceOfSelf()
  1757. {
  1758. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1759. bool Result = false;
  1760. try
  1761. {
  1762. unsigned int Process = GetCurrentProcessId();
  1763. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1764. PROCESSENTRY32 ProcessEntry;
  1765. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1766. if (Process32First(Snapshot, &ProcessEntry))
  1767. {
  1768. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1769. {
  1770. // we should check if the process is running in the same session,
  1771. // but for that we probably need some special privileges
  1772. if ((Process != ProcessEntry.th32ProcessID) &&
  1773. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1774. {
  1775. Result = true;
  1776. }
  1777. }
  1778. }
  1779. }
  1780. __finally
  1781. {
  1782. CloseHandle(Snapshot);
  1783. }
  1784. return Result;
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1788. {
  1789. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1790. Registry->RootKey = RootKey;
  1791. bool Result =
  1792. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1793. if (Result)
  1794. {
  1795. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1796. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1797. Result =
  1798. !InstallPath.IsEmpty() &&
  1799. IsPathToSameFile(ExePath, InstallPath);
  1800. }
  1801. return Result;
  1802. }
  1803. //---------------------------------------------------------------------------
  1804. bool __fastcall IsInstalled()
  1805. {
  1806. return
  1807. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1808. DoIsInstalled(HKEY_CURRENT_USER);
  1809. }
  1810. //---------------------------------------------------------------------------
  1811. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1812. {
  1813. std::unique_ptr<TStringList> List(new TStringList());
  1814. List->CommaText = Text;
  1815. return List.release();
  1816. }
  1817. //---------------------------------------------------------------------------
  1818. UnicodeString __fastcall FirstUnshownTip()
  1819. {
  1820. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1821. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1822. Tips->CaseSensitive = false;
  1823. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1824. TipsSeen->CaseSensitive = false;
  1825. int LastTipSeen = -1;
  1826. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1827. {
  1828. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1829. if (TipIndex >= 0)
  1830. {
  1831. LastTipSeen = TipIndex;
  1832. }
  1833. }
  1834. UnicodeString Result;
  1835. if (LastTipSeen < Tips->Count - 1)
  1836. {
  1837. Result = Tips->Strings[LastTipSeen + 1];
  1838. }
  1839. return Result;
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. class TTipsData : public TComponent
  1843. {
  1844. public:
  1845. __fastcall TTipsData() :
  1846. TComponent(NULL)
  1847. {
  1848. }
  1849. int Index;
  1850. TStringList * Tips;
  1851. static TTipsData * __fastcall Retrieve(TObject * Object)
  1852. {
  1853. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1854. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1855. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1856. }
  1857. };
  1858. //---------------------------------------------------------------------------
  1859. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1860. {
  1861. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1862. }
  1863. //---------------------------------------------------------------------------
  1864. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1865. {
  1866. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1867. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(YesButtonName)));
  1868. PrevButton->Enabled = (TipsData->Index > 0);
  1869. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1870. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1871. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(FindComponentRecursively(Form, MainMessageLabelName)));
  1872. MessageLabel->Caption = TipsMessage(TipsData);
  1873. }
  1874. //---------------------------------------------------------------------------
  1875. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1876. {
  1877. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1878. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1879. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1880. }
  1881. //---------------------------------------------------------------------------
  1882. static void __fastcall TipSeen(const UnicodeString & Tip)
  1883. {
  1884. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1885. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1886. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1887. WinConfiguration->TipsShown = Now();
  1888. WinConfiguration->RunsSinceLastTip = 0;
  1889. // prevent parallel app instances showing the same tip
  1890. WinConfiguration->Save();
  1891. }
  1892. //---------------------------------------------------------------------------
  1893. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender, unsigned int & /*Answer*/)
  1894. {
  1895. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1896. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1897. TipsData->Index += reinterpret_cast<int>(Data);
  1898. UpdateTipsForm(Form);
  1899. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1900. UnicodeString Url = TipUrl(TipsData);
  1901. NavigateMessageDialogToUrl(Form, Url);
  1902. }
  1903. //---------------------------------------------------------------------------
  1904. static void __fastcall ShowTip(bool AutoShow)
  1905. {
  1906. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1907. UnicodeString Tip = FirstUnshownTip();
  1908. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1909. Tips->CaseSensitive = false;
  1910. int Index;
  1911. if (Tip.IsEmpty())
  1912. {
  1913. Index = Tips->Count - 1;
  1914. Tip = Tips->Strings[Index];
  1915. }
  1916. else
  1917. {
  1918. Index = Tips->IndexOf(Tip);
  1919. }
  1920. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1921. TipsData->Name = TTipsData::QualifiedClassName();
  1922. TipsData->Index = Index;
  1923. TipsData->Tips = Tips.get();
  1924. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1925. TQueryButtonAlias Aliases[3];
  1926. Aliases[0].Button = qaYes;
  1927. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1928. Aliases[0].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1929. Aliases[1].Button = qaNo;
  1930. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1931. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1932. Aliases[2].Button = qaCancel;
  1933. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1934. TMessageParams Params;
  1935. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1936. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1937. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1938. Params.Aliases = Aliases;
  1939. Params.AliasesCount = LENOF(Aliases);
  1940. Params.ImageName = L"Bulb On n p";
  1941. if (AutoShow)
  1942. {
  1943. // Won't be used automatically as we have more than the "OK" button
  1944. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1945. Params.NeverAskAgainAnswer = qaCancel;
  1946. Params.Params |= mpNeverAskAgainCheck;
  1947. }
  1948. int Answers = qaYes | qaNo | qaCancel;
  1949. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1950. Dialog->InsertComponent(TipsData.release());
  1951. UpdateTipsForm(Dialog.get());
  1952. TipSeen(Tip);
  1953. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1954. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1955. {
  1956. WinConfiguration->ShowTips = false;
  1957. }
  1958. WinConfiguration->Updates = Updates;
  1959. }
  1960. //---------------------------------------------------------------------------
  1961. void __fastcall AutoShowNewTip()
  1962. {
  1963. Configuration->Usage->Inc(L"TipsShownAuto");
  1964. ShowTip(true);
  1965. }
  1966. //---------------------------------------------------------------------------
  1967. bool __fastcall AnyTips()
  1968. {
  1969. return !WinConfiguration->Updates.Results.Tips.IsEmpty();
  1970. }
  1971. //---------------------------------------------------------------------------
  1972. void __fastcall ShowTips()
  1973. {
  1974. {
  1975. TOperationVisualizer Visualizer;
  1976. DoQueryUpdates(false);
  1977. }
  1978. if (!AnyTips())
  1979. {
  1980. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1981. }
  1982. Configuration->Usage->Inc(L"TipsShownCommand");
  1983. ShowTip(false);
  1984. }
  1985. //---------------------------------------------------------------------------
  1986. void __fastcall TipsUpdateStaticUsage()
  1987. {
  1988. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1989. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1990. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1991. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1992. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. static void ReadNetVersion(TRegistryStorage * Registry)
  1996. {
  1997. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  1998. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  1999. {
  2000. NetVersionStr = VersionStr;
  2001. }
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. UnicodeString __fastcall GetNetVersionStr()
  2005. {
  2006. if (NetVersionStr.IsEmpty())
  2007. {
  2008. NetVersionStr = L"0"; // not to retry on failure
  2009. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  2010. if (Registry->OpenRootKey(false))
  2011. {
  2012. std::unique_ptr<TStringList> Keys(new TStringList());
  2013. Registry->GetSubKeyNames(Keys.get());
  2014. for (int Index = 0; Index < Keys->Count; Index++)
  2015. {
  2016. UnicodeString Key = Keys->Strings[Index];
  2017. if (Registry->OpenSubKey(Key, false))
  2018. {
  2019. ReadNetVersion(Registry.get());
  2020. if (Registry->OpenSubKey(L"Full", false))
  2021. {
  2022. ReadNetVersion(Registry.get());
  2023. Registry->CloseSubKey();
  2024. }
  2025. if (Registry->OpenSubKey(L"Client", false))
  2026. {
  2027. ReadNetVersion(Registry.get());
  2028. Registry->CloseSubKey();
  2029. }
  2030. Registry->CloseSubKey();
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return NetVersionStr;
  2036. }
  2037. //---------------------------------------------------------------------------
  2038. UnicodeString __fastcall GetPowerShellVersionStr()
  2039. {
  2040. if (PowerShellVersionStr.IsEmpty())
  2041. {
  2042. PowerShellVersionStr = 0; // not to retry on failure
  2043. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2044. if (Registry->OpenRootKey(false))
  2045. {
  2046. std::unique_ptr<TStringList> Keys(new TStringList());
  2047. Registry->GetSubKeyNames(Keys.get());
  2048. for (int Index = 0; Index < Keys->Count; Index++)
  2049. {
  2050. UnicodeString Key = Keys->Strings[Index];
  2051. if (Registry->OpenSubKeyPath(Key + L"\\PowerShellEngine", false))
  2052. {
  2053. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2054. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2055. {
  2056. PowerShellVersionStr = VersionStr;
  2057. }
  2058. Registry->CloseSubKeyPath();
  2059. }
  2060. }
  2061. }
  2062. }
  2063. return PowerShellVersionStr;
  2064. }
  2065. //---------------------------------------------------------------------------
  2066. //---------------------------------------------------------------------------
  2067. static void CollectCLSIDKey(
  2068. TConsole * Console, TStrings * Keys, int PlatformSet, TRegistryStorage * Storage, const UnicodeString & CLSID,
  2069. UnicodeString & CommonCodeBase, const UnicodeString & Platform, UnicodeString & Platforms)
  2070. {
  2071. UnicodeString CLSIDKey = FORMAT(L"CLSID\\%s", (CLSID));
  2072. if (Storage->OpenSubKeyPath(CLSIDKey, false))
  2073. {
  2074. int Index = Keys->IndexOf(CLSIDKey);
  2075. if (Index >= 0)
  2076. {
  2077. Keys->Objects[Index] = reinterpret_cast<TObject *>(PlatformSet | reinterpret_cast<int>(Keys->Objects[Index]));
  2078. }
  2079. else
  2080. {
  2081. Keys->AddObject(CLSIDKey, reinterpret_cast<TObject *>(PlatformSet));
  2082. }
  2083. UnicodeString CodeBase;
  2084. if (Storage->OpenSubKey(L"InprocServer32", false))
  2085. {
  2086. CodeBase = Storage->ReadString(L"CodeBase", UnicodeString());
  2087. UnicodeString Assembly = Storage->ReadString(L"Assembly", UnicodeString());
  2088. UnicodeString Version;
  2089. if (!Assembly.IsEmpty())
  2090. {
  2091. UnicodeString VersionPrefix = L"Version=";
  2092. int P = Assembly.UpperCase().Pos(VersionPrefix.UpperCase());
  2093. if (P > 0)
  2094. {
  2095. Assembly.Delete(1, P + VersionPrefix.Length() - 1);
  2096. Version = CutToChar(Assembly, L',', true);
  2097. }
  2098. }
  2099. if (CodeBase.IsEmpty() || Version.IsEmpty())
  2100. {
  2101. Console->PrintLine(FORMAT(L"Warning: Could not find codebase and version for %s.", (CLSID)));
  2102. CodeBase = UnicodeString();
  2103. }
  2104. else
  2105. {
  2106. CodeBase = FORMAT(L"%s (%s)", (CodeBase, Version));
  2107. if (CommonCodeBase.IsEmpty())
  2108. {
  2109. Console->PrintLine(FORMAT(L"Codebase %s, unless stated otherwise", (CodeBase)));
  2110. CommonCodeBase = CodeBase;
  2111. }
  2112. if (SameText(CommonCodeBase, CodeBase))
  2113. {
  2114. CodeBase = L"";
  2115. }
  2116. }
  2117. Storage->CloseSubKey();
  2118. }
  2119. Storage->CloseSubKeyPath();
  2120. UnicodeString Buf = Platform;
  2121. AddToList(Buf, CodeBase, L" - ");
  2122. AddToList(Platforms, Buf, ", ");
  2123. }
  2124. }
  2125. //---------------------------------------------------------------------------
  2126. static UnicodeString PlatformStr(int PlatformSet)
  2127. {
  2128. UnicodeString Result;
  2129. if (PlatformSet == 0)
  2130. {
  2131. Result = L"shared";
  2132. }
  2133. else
  2134. {
  2135. if (FLAGSET(PlatformSet, 32))
  2136. {
  2137. Result = L"32-bit";
  2138. }
  2139. if (FLAGSET(PlatformSet, 64))
  2140. {
  2141. AddToList(Result, L"64-bit", L", ");
  2142. }
  2143. }
  2144. return Result;
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. static void DoCollectComRegistration(TConsole * Console, TStrings * Keys)
  2148. {
  2149. UnicodeString TypeLib = L"{A0B93468-D98A-4845-A234-8076229AD93F}"; // Duplicated in AssemblyInfo.cs
  2150. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT));
  2151. Storage->MungeStringValues = false;
  2152. Storage->AccessMode = smRead;
  2153. std::unique_ptr<TRegistryStorage> Storage64;
  2154. if (IsWin64())
  2155. {
  2156. Storage64.reset(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT, KEY_WOW64_64KEY));
  2157. Storage64->MungeStringValues = false;
  2158. Storage64->AccessMode = smRead;
  2159. }
  2160. // Classes, TypeLib and Record are shared between 32-bit and 64-bit registry view.
  2161. // 32-bit and 64-bit version of regasm adds CLSID keys to its respective view.
  2162. // Both 32-bit and 64-bit version of regasm seem to add Interface keys to both 32-bit and 64-bit views.
  2163. // On Vista, Interface keys are reflected (so when 32-bit keys is deleted, it's also deleted from 64-bit key,
  2164. // and we show an error, trying to delete the 64-bit key).
  2165. if (Storage->OpenRootKey(false))
  2166. {
  2167. Console->PrintLine(FORMAT(L"Versions of type library %s:", (TypeLib)));
  2168. UnicodeString TypeLibKey = FORMAT(L"TypeLib\\%s", (TypeLib));
  2169. if (Storage->OpenSubKeyPath(TypeLibKey, false))
  2170. {
  2171. Keys->Add(TypeLibKey);
  2172. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2173. Storage->GetSubKeyNames(KeyNames.get());
  2174. if (KeyNames->Count == 0)
  2175. {
  2176. Console->PrintLine(L"Warning: The type library key exists, but no type libraries are present.");
  2177. }
  2178. else
  2179. {
  2180. for (int Index = 0; Index < KeyNames->Count; Index++)
  2181. {
  2182. UnicodeString Version = KeyNames->Strings[Index];
  2183. if (!Storage->OpenSubKeyPath(FORMAT(L"%s\\0", (Version)), false))
  2184. {
  2185. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" cannot be opened.", (Version)));
  2186. }
  2187. else
  2188. {
  2189. std::unique_ptr<TStringList> Platforms(new TStringList());
  2190. Storage->GetSubKeyNames(Platforms.get());
  2191. if (Platforms->Count == 0)
  2192. {
  2193. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" exists, but platforms are present.", (Version)));
  2194. }
  2195. else
  2196. {
  2197. for (int Index2 = 0; Index2 < Platforms->Count; Index2++)
  2198. {
  2199. UnicodeString Platform = Platforms->Strings[Index2];
  2200. if (!Storage->OpenSubKey(Platform, false))
  2201. {
  2202. Console->PrintLine(FORMAT(L"Warning: Platform \"%s\" for type library \"%s\" cannot be opened.", (Platform, Version)));
  2203. }
  2204. else
  2205. {
  2206. UnicodeString TypeLibraryPath = Storage->ReadString(UnicodeString(), UnicodeString());
  2207. UnicodeString Exists = FileExists(TypeLibraryPath) ? L"exists" : L"does not exist";
  2208. Console->PrintLine(FORMAT(L"%s (%s): %s (%s)", (Version, Platform, TypeLibraryPath, Exists)));
  2209. Storage->CloseSubKey();
  2210. }
  2211. }
  2212. }
  2213. Storage->CloseSubKeyPath();
  2214. }
  2215. }
  2216. }
  2217. Storage->CloseSubKeyPath();
  2218. }
  2219. else
  2220. {
  2221. Console->PrintLine(L"Type library not registered.");
  2222. }
  2223. Console->PrintLine();
  2224. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2225. Storage->GetSubKeyNames(KeyNames.get());
  2226. UnicodeString NamespacePrefix = L"WinSCP.";
  2227. Console->PrintLine(L"Classes:");
  2228. UnicodeString CommonCodeBase;
  2229. int Found = 0;
  2230. for (int Index = 0; Index < KeyNames->Count; Index++)
  2231. {
  2232. UnicodeString KeyName = KeyNames->Strings[Index];
  2233. if (StartsText(NamespacePrefix, KeyName))
  2234. {
  2235. if (Storage->OpenSubKeyPath(FORMAT(L"%s\\%s", (KeyName, L"CLSID")), false))
  2236. {
  2237. UnicodeString Class = KeyName;
  2238. UnicodeString CLSID = Trim(Storage->ReadString(UnicodeString(), UnicodeString()));
  2239. Storage->CloseSubKeyPath();
  2240. if (!CLSID.IsEmpty())
  2241. {
  2242. Keys->Add(KeyName);
  2243. UnicodeString Platforms;
  2244. CollectCLSIDKey(Console, Keys, 32, Storage.get(), CLSID, CommonCodeBase, L"32-bit", Platforms);
  2245. if (Storage64.get() != NULL)
  2246. {
  2247. CollectCLSIDKey(Console, Keys, 64, Storage64.get(), CLSID, CommonCodeBase, L"64-bit", Platforms);
  2248. }
  2249. UnicodeString Line = FORMAT(L"%s - %s", (Class, CLSID));
  2250. if (Platforms.IsEmpty())
  2251. {
  2252. Console->PrintLine(FORMAT(L"Warning: Could not find CLSID %s for class %s.", (CLSID, Class)));
  2253. }
  2254. else
  2255. {
  2256. Line += FORMAT(L" [%s]", (Platforms));
  2257. }
  2258. Console->PrintLine(Line);
  2259. Found++;
  2260. }
  2261. }
  2262. }
  2263. }
  2264. if (Found == 0)
  2265. {
  2266. Console->PrintLine(L"No classes found.");
  2267. }
  2268. Console->PrintLine();
  2269. UnicodeString InterfaceKey = L"Interface";
  2270. if (Storage->OpenSubKey(InterfaceKey, false) &&
  2271. ((Storage64.get() == NULL) || Storage64->OpenSubKey(InterfaceKey, false)))
  2272. {
  2273. Console->PrintLine(L"Interfaces:");
  2274. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2275. Storage->GetSubKeyNames(KeyNames.get());
  2276. KeyNames->Sorted = true;
  2277. for (int Index = 0; Index < KeyNames->Count; Index++)
  2278. {
  2279. KeyNames->Objects[Index] = reinterpret_cast<TObject *>(32);
  2280. }
  2281. if (Storage64.get() != NULL)
  2282. {
  2283. std::unique_ptr<TStringList> KeyNames64(new TStringList());
  2284. Storage64->GetSubKeyNames(KeyNames64.get());
  2285. for (int Index = 0; Index < KeyNames64->Count; Index++)
  2286. {
  2287. UnicodeString Key64 = KeyNames64->Strings[Index];
  2288. int Index32 = KeyNames->IndexOf(Key64);
  2289. if (Index32 >= 0)
  2290. {
  2291. KeyNames->Objects[Index32] = reinterpret_cast<TObject *>(32 | 64);
  2292. }
  2293. else
  2294. {
  2295. KeyNames->AddObject(Key64, reinterpret_cast<TObject *>(64));
  2296. }
  2297. }
  2298. }
  2299. int Found = 0;
  2300. for (int Index = 0; Index < KeyNames->Count; Index++)
  2301. {
  2302. UnicodeString KeyName = KeyNames->Strings[Index];
  2303. // Open sub key first, to check if we are interested in the interface, as an optimization
  2304. int PlatformSet = reinterpret_cast<int>(KeyNames->Objects[Index]);
  2305. THierarchicalStorage * KeyStorage = FLAGSET(PlatformSet, 32) ? Storage.get() : Storage64.get();
  2306. if (KeyStorage->OpenSubKeyPath(FORMAT(L"%s\\TypeLib", (KeyName)), false))
  2307. {
  2308. UnicodeString InterfaceTypeLib = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2309. UnicodeString Version = KeyStorage->ReadString(L"Version", UnicodeString());
  2310. KeyStorage->CloseSubKeyPath();
  2311. if (SameText(InterfaceTypeLib, TypeLib))
  2312. {
  2313. if (KeyStorage->OpenSubKey(KeyName, false))
  2314. {
  2315. UnicodeString Key = ExcludeTrailingBackslash(KeyStorage->CurrentSubKey);
  2316. UnicodeString Interface = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2317. KeyStorage->CloseSubKey();
  2318. Keys->AddObject(Key, reinterpret_cast<TObject *>(PlatformSet));
  2319. Console->PrintLine(FORMAT(L"%s - %s (%s) [%s]", (Interface, KeyName, Version, PlatformStr(PlatformSet))));
  2320. Found++;
  2321. }
  2322. }
  2323. }
  2324. }
  2325. if (Found == 0)
  2326. {
  2327. Console->PrintLine(L"No interfaces found.");
  2328. }
  2329. Storage->CloseSubKey();
  2330. Console->PrintLine();
  2331. }
  2332. if (Storage->OpenSubKey(L"Record", false))
  2333. {
  2334. Console->PrintLine(L"Value types:");
  2335. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2336. Storage->GetSubKeyNames(KeyNames.get());
  2337. int Found = 0;
  2338. for (int Index = 0; Index < KeyNames->Count; Index++)
  2339. {
  2340. UnicodeString KeyName = KeyNames->Strings[Index];
  2341. if (Storage->OpenSubKey(KeyName, false))
  2342. {
  2343. std::unique_ptr<TStringList> Versions(new TStringList());
  2344. Storage->GetSubKeyNames(Versions.get());
  2345. UnicodeString VersionsStr;
  2346. std::unique_ptr<TStringList> Classes(CreateSortedStringList());
  2347. for (int Index2 = 0; Index2 < Versions->Count; Index2++)
  2348. {
  2349. UnicodeString Version = Versions->Strings[Index2];
  2350. if (Storage->OpenSubKey(Version, false))
  2351. {
  2352. UnicodeString Class = Storage->ReadString(L"Class", UnicodeString());
  2353. Classes->Add(Class);
  2354. if (StartsStr(NamespacePrefix, Class))
  2355. {
  2356. AddToList(VersionsStr, Version, L", ");
  2357. }
  2358. Storage->CloseSubKey();
  2359. }
  2360. }
  2361. if (!VersionsStr.IsEmpty())
  2362. {
  2363. if (Classes->Count != 1)
  2364. {
  2365. Console->PrintLine(FORMAT(L"Warning: Different class names for the same value type %s: %s", (KeyName, Classes->CommaText)));
  2366. }
  2367. else
  2368. {
  2369. Keys->Add(ExcludeTrailingBackslash(Storage->CurrentSubKey));
  2370. Console->PrintLine(FORMAT(L"%s - %s (%s)", (Classes->Strings[0], KeyName, VersionsStr)));
  2371. Found++;
  2372. }
  2373. }
  2374. Storage->CloseSubKey();
  2375. }
  2376. }
  2377. if (Found == 0)
  2378. {
  2379. Console->PrintLine(L"No value types found.");
  2380. }
  2381. Storage->CloseSubKey();
  2382. Console->PrintLine();
  2383. }
  2384. }
  2385. }
  2386. //---------------------------------------------------------------------------
  2387. bool DoUnregisterChoice(TConsole * Console)
  2388. {
  2389. return (Console->Choice(L"U", -1, -1, -1, 0, 0, 0, UnicodeString()) == 1);
  2390. }
  2391. //---------------------------------------------------------------------------
  2392. typedef HRESULT WINAPI (* RegDeleteTreeProc)(HKEY Key, LPCWSTR SubKey);
  2393. static RegDeleteTreeProc ARegDeleteTree = NULL;
  2394. //---------------------------------------------------------------------------
  2395. void DoDeleteKey(TConsole * Console, TRegistry * Registry, const UnicodeString & Key, int Platform, bool & AnyDeleted, bool & AllDeleted)
  2396. {
  2397. UnicodeString ParentKey = ExtractFileDir(Key);
  2398. UnicodeString ChildKey = ExtractFileName(Key);
  2399. bool Result = Registry->OpenKey(ParentKey, false);
  2400. if (Result)
  2401. {
  2402. if (DebugAlwaysFalse(ARegDeleteTree == NULL))
  2403. {
  2404. Result = false;
  2405. }
  2406. else
  2407. {
  2408. Result = (ARegDeleteTree(Registry->CurrentKey, ChildKey.c_str()) == 0);
  2409. }
  2410. Registry->CloseKey();
  2411. }
  2412. UnicodeString Status;
  2413. if (Result)
  2414. {
  2415. Status = L"removed";
  2416. AnyDeleted = true;
  2417. }
  2418. else
  2419. {
  2420. AllDeleted = false;
  2421. Status = L"NOT removed";
  2422. }
  2423. Console->PrintLine(FORMAT(L"%s [%s] - %s", (Key, PlatformStr(Platform), Status)));
  2424. }
  2425. //---------------------------------------------------------------------------
  2426. int ComRegistration(TConsole * Console)
  2427. {
  2428. int Result = RESULT_SUCCESS;
  2429. try
  2430. {
  2431. if (ARegDeleteTree == NULL)
  2432. {
  2433. HINSTANCE AdvapiLibrary = LoadLibrary(L"advapi32.dll");
  2434. if (DebugAlwaysTrue(AdvapiLibrary != NULL))
  2435. {
  2436. ARegDeleteTree = reinterpret_cast<RegDeleteTreeProc>(GetProcAddress(AdvapiLibrary, "RegDeleteTreeW"));
  2437. }
  2438. }
  2439. if (ARegDeleteTree == NULL)
  2440. {
  2441. throw Exception(FORMAT(L"Not supported on %s", (GetOSInfo())));
  2442. }
  2443. Console->PrintLine(GetEnvironmentInfo());
  2444. Console->PrintLine();
  2445. std::unique_ptr<TStrings> Keys(new TStringList());
  2446. DoCollectComRegistration(Console, Keys.get());
  2447. if (Keys->Count == 0)
  2448. {
  2449. Console->PrintLine(L"No registration found.");
  2450. Console->WaitBeforeExit();
  2451. }
  2452. else
  2453. {
  2454. Console->PrintLine(L"Press (U) to unregister or Esc to exit...");
  2455. if (DoUnregisterChoice(Console))
  2456. {
  2457. Console->PrintLine();
  2458. Console->PrintLine(L"The following registry keys will be removed from HKCR registry hive:");
  2459. for (int Index = 0; Index < Keys->Count; Index++)
  2460. {
  2461. Console->PrintLine(FORMAT(L"%s [%s]", (Keys->Strings[Index], PlatformStr(reinterpret_cast<int>(Keys->Objects[Index])))));
  2462. }
  2463. Console->PrintLine();
  2464. Console->PrintLine(L"You need Administrator privileges to remove the keys.");
  2465. Console->PrintLine(L"Press (U) again to proceed with unregistration or Esc to abort...");
  2466. if (DoUnregisterChoice(Console))
  2467. {
  2468. std::unique_ptr<TRegistry> Registry64(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_64KEY));
  2469. Registry64->RootKey = HKEY_CLASSES_ROOT;
  2470. std::unique_ptr<TRegistry> Registry32(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_32KEY));
  2471. Registry32->RootKey = HKEY_CLASSES_ROOT;
  2472. bool AnyDeleted = false;
  2473. bool AllDeleted = true;
  2474. for (int Index = 0; Index < Keys->Count; Index++)
  2475. {
  2476. UnicodeString Key = Keys->Strings[Index];
  2477. int PlatformSet = reinterpret_cast<int>(Keys->Objects[Index]);
  2478. if (PlatformSet == 0)
  2479. {
  2480. DoDeleteKey(Console, Registry32.get(), Key, 0, AnyDeleted, AllDeleted);
  2481. }
  2482. else
  2483. {
  2484. if (FLAGSET(PlatformSet, 32))
  2485. {
  2486. DoDeleteKey(Console, Registry32.get(), Key, 32, AnyDeleted, AllDeleted);
  2487. }
  2488. if (FLAGSET(PlatformSet, 64))
  2489. {
  2490. DoDeleteKey(Console, Registry64.get(), Key, 64, AnyDeleted, AllDeleted);
  2491. }
  2492. }
  2493. }
  2494. Console->PrintLine();
  2495. if (!AnyDeleted)
  2496. {
  2497. Console->PrintLine(L"No keys were removed. Make sure you have Administrator privileges.");
  2498. }
  2499. else if (!AllDeleted)
  2500. {
  2501. Console->PrintLine(L"Some keys were not removed. Make sure you have Administrator privileges.");
  2502. }
  2503. else
  2504. {
  2505. Console->PrintLine(L"All keys were removed. Unregistration succeeded.");
  2506. }
  2507. Console->WaitBeforeExit();
  2508. }
  2509. }
  2510. }
  2511. }
  2512. catch (Exception & E)
  2513. {
  2514. Result = HandleException(Console, E);
  2515. Console->WaitBeforeExit();
  2516. }
  2517. return Result;
  2518. }