Setup.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712
  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("avaible 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/desktop/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. bool Continue = true;
  664. TStrings * Folders = NULL;
  665. try
  666. {
  667. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  668. {
  669. Folders = WinConfiguration->FindTemporaryFolders();
  670. Continue = (Folders != NULL);
  671. if (Continue)
  672. {
  673. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  674. TQueryButtonAlias Aliases[1];
  675. Aliases[0].Button = qaRetry;
  676. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  677. TMessageParams Params(mpNeverAskAgainCheck);
  678. Params.Aliases = Aliases;
  679. Params.AliasesCount = LENOF(Aliases);
  680. unsigned int Answer = MoreMessageDialog(
  681. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  682. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  683. if (Answer == qaNeverAskAgain)
  684. {
  685. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  686. Answer = qaYes;
  687. }
  688. else if (Answer == qaRetry)
  689. {
  690. for (int Index = 0; Index < Folders->Count; Index++)
  691. {
  692. ShellExecute(Application->Handle, NULL,
  693. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  694. }
  695. }
  696. Continue = (Answer == qaYes);
  697. }
  698. }
  699. if (Continue)
  700. {
  701. try
  702. {
  703. WinConfiguration->CleanupTemporaryFolders(Folders);
  704. }
  705. catch (Exception &E)
  706. {
  707. ShowExtendedException(&E);
  708. }
  709. }
  710. }
  711. __finally
  712. {
  713. delete Folders;
  714. }
  715. }
  716. //-------------------------------------------- -------------------------------
  717. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  718. {
  719. int MajorVer = Version / (10000*100*100);
  720. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  721. int Release = (Version % (10000*100)) / (10000);
  722. UnicodeString Result;
  723. if (Release > 0)
  724. {
  725. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  726. }
  727. else
  728. {
  729. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  730. }
  731. return Result;
  732. }
  733. //---------------------------------------------------------------------------
  734. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  735. {
  736. int CurrentCompoundVer = Configuration->CompoundVersion;
  737. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  738. UnicodeString Medium = IsUWP() ? L"uwp" : L"app";
  739. // Beware that these parameters may get truncated if URL is too long,
  740. // such as with ERROR_REPORT_URL2
  741. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=%s&utm_campaign=%s", (Medium, Version));
  742. return AppendUrlParams(URL, Params);
  743. }
  744. //---------------------------------------------------------------------------
  745. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  746. {
  747. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  748. UnicodeString CurrentVersionStr =
  749. FORMAT(L"%d.%d.%d.%d",
  750. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  751. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  752. UnicodeString Params =
  753. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  754. (CurrentVersionStr,
  755. GUIConfiguration->AppliedLocaleHex,
  756. int(IsInstalled())));
  757. if (Configuration->IsUnofficial)
  758. {
  759. Params += L"&unofficial=1";
  760. }
  761. return AppendUrlParams(URL, Params);
  762. }
  763. //---------------------------------------------------------------------------
  764. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  765. {
  766. bool Beta;
  767. if (WinConfiguration->IsBeta)
  768. {
  769. Beta = true;
  770. }
  771. else
  772. {
  773. switch (WinConfiguration->Updates.BetaVersions)
  774. {
  775. case asAuto:
  776. Beta = WinConfiguration->AnyBetaInVersionHistory;
  777. break;
  778. case asOn:
  779. Beta = true;
  780. break;
  781. default:
  782. Beta = false;
  783. break;
  784. }
  785. }
  786. if (Beta || Force)
  787. {
  788. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  789. }
  790. return URL;
  791. }
  792. //---------------------------------------------------------------------------
  793. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  794. {
  795. std::unique_ptr<THttp> Http(new THttp());
  796. UnicodeString ProxyHost;
  797. int ProxyPort = 0;
  798. switch (Updates.ConnectionType)
  799. {
  800. case ctAuto:
  801. if (AutodetectProxy(ProxyHost, ProxyPort))
  802. {
  803. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  804. }
  805. break;
  806. case ctProxy:
  807. ProxyHost = Updates.ProxyHost;
  808. ProxyPort = Updates.ProxyPort;
  809. Configuration->Usage->Inc(L"UpdateProxyManual");
  810. break;
  811. }
  812. Http->ProxyHost = ProxyHost;
  813. Http->ProxyPort = ProxyPort;
  814. return Http.release();
  815. }
  816. //---------------------------------------------------------------------------
  817. THttp * __fastcall CreateHttp()
  818. {
  819. return CreateHttp(WinConfiguration->Updates);
  820. }
  821. //---------------------------------------------------------------------------
  822. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  823. {
  824. bool Complete = false;
  825. UnicodeString Response;
  826. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  827. try
  828. {
  829. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  830. URL = WantBetaUrl(URL, false);
  831. URL += L"&dotnet=" + Updates.DotNetVersion;
  832. URL += L"&console=" + Updates.ConsoleVersion;
  833. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  834. if (!LocaleVersion.IsEmpty())
  835. {
  836. URL += L"&localever=" + LocaleVersion;
  837. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  838. }
  839. if (!Updates.AuthenticationEmail.IsEmpty())
  840. {
  841. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  842. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  843. }
  844. CheckForUpdatesHTTP->URL = URL;
  845. // sanity check
  846. CheckForUpdatesHTTP->ResponseLimit = 102400;
  847. try
  848. {
  849. if (CollectUsage)
  850. {
  851. UnicodeString Usage = Configuration->Usage->Serialize();
  852. CheckForUpdatesHTTP->Post(Usage);
  853. }
  854. else
  855. {
  856. CheckForUpdatesHTTP->Get();
  857. }
  858. }
  859. catch (...)
  860. {
  861. if (CheckForUpdatesHTTP->IsCertificateError())
  862. {
  863. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  864. }
  865. throw;
  866. }
  867. Response = CheckForUpdatesHTTP->Response;
  868. }
  869. __finally
  870. {
  871. delete CheckForUpdatesHTTP;
  872. }
  873. int CurrentCompoundVer = Configuration->CompoundVersion;
  874. bool Changed = !Updates.HaveResults;
  875. Updates.LastCheck = Now();
  876. Updates.HaveResults = true;
  877. TUpdatesData PrevResults = Updates.Results;
  878. Updates.Results.Reset();
  879. Updates.Results.ForVersion = CurrentCompoundVer;
  880. while (!Response.IsEmpty())
  881. {
  882. UnicodeString Line = CutToChar(Response, L'\n', false);
  883. UnicodeString Name = CutToChar(Line, L'=', false);
  884. if (SameText(Name, "Version"))
  885. {
  886. int NewVersion = StrToCompoundVersion(Line);
  887. Changed |= (NewVersion != PrevResults.Version);
  888. if (NewVersion <= CurrentCompoundVer)
  889. {
  890. NewVersion = 0;
  891. }
  892. Updates.Results.Version = NewVersion;
  893. Complete = true;
  894. }
  895. else if (SameText(Name, L"Message"))
  896. {
  897. Changed |= (PrevResults.Message != Line);
  898. Updates.Results.Message = Line;
  899. }
  900. else if (SameText(Name, L"Critical"))
  901. {
  902. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  903. Changed |= (PrevResults.Critical != NewCritical);
  904. Updates.Results.Critical = NewCritical;
  905. }
  906. else if (SameText(Name, L"Release"))
  907. {
  908. Changed |= (PrevResults.Release != Line);
  909. Updates.Results.Release = Line;
  910. }
  911. else if (SameText(Name, L"Disabled"))
  912. {
  913. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  914. Changed |= (PrevResults.Disabled != NewDisabled);
  915. Updates.Results.Disabled = NewDisabled;
  916. Complete = true;
  917. }
  918. else if (SameText(Name, L"Url"))
  919. {
  920. Changed |= (PrevResults.Url != Line);
  921. Updates.Results.Url = Line;
  922. }
  923. else if (SameText(Name, L"UrlButton"))
  924. {
  925. Changed |= (PrevResults.UrlButton != Line);
  926. Updates.Results.UrlButton = Line;
  927. }
  928. else if (SameText(Name, L"NewsUrl"))
  929. {
  930. Changed |= (PrevResults.NewsUrl != Line);
  931. Updates.Results.NewsUrl = Line;
  932. }
  933. else if (SameText(Name, L"NewsSize"))
  934. {
  935. TSize NewsSize;
  936. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  937. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  938. Changed |= (PrevResults.NewsSize != NewsSize);
  939. Updates.Results.NewsSize = NewsSize;
  940. }
  941. else if (SameText(Name, L"DownloadUrl"))
  942. {
  943. Changed |= (PrevResults.DownloadUrl != Line);
  944. Updates.Results.DownloadUrl = Line;
  945. }
  946. else if (SameText(Name, L"DownloadSize"))
  947. {
  948. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  949. }
  950. else if (SameText(Name, L"DownloadSha256"))
  951. {
  952. Updates.Results.DownloadSha256 = Line;
  953. }
  954. else if (SameText(Name, L"AuthenticationError"))
  955. {
  956. Changed |= (PrevResults.AuthenticationError != Line);
  957. Updates.Results.AuthenticationError = Line;
  958. }
  959. else if (SameText(Name, L"OpenGettingStarted"))
  960. {
  961. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  962. }
  963. else if (SameText(Name, L"DownloadingUrl"))
  964. {
  965. Updates.Results.DownloadingUrl = Line;
  966. }
  967. else if (SameText(Name, L"TipsSize"))
  968. {
  969. TSize TipsSize;
  970. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  971. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  972. Updates.Results.TipsSize = TipsSize;
  973. }
  974. else if (SameText(Name, L"TipsUrl"))
  975. {
  976. Updates.Results.TipsUrl = Line;
  977. }
  978. else if (SameText(Name, L"Tips"))
  979. {
  980. Updates.Results.Tips = Line;
  981. }
  982. else if (SameText(Name, L"TipsIntervalDays"))
  983. {
  984. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  985. if (TipsIntervalDays < 0)
  986. {
  987. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  988. }
  989. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  990. }
  991. else if (SameText(Name, L"TipsIntervalRuns"))
  992. {
  993. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  994. if (TipsIntervalRuns < 0)
  995. {
  996. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  997. }
  998. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  999. }
  1000. }
  1001. if (Changed)
  1002. {
  1003. Updates.ShownResults = false;
  1004. }
  1005. return Complete;
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1009. {
  1010. return DoQueryUpdates(Updates, false);
  1011. }
  1012. //---------------------------------------------------------------------------
  1013. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1014. {
  1015. try
  1016. {
  1017. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1018. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1019. WinConfiguration->Updates = Updates;
  1020. if (!Complete)
  1021. {
  1022. EXCEPTION;
  1023. }
  1024. Configuration->Usage->Reset();
  1025. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1026. }
  1027. catch(Exception & E)
  1028. {
  1029. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1030. UnicodeString Message;
  1031. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1032. {
  1033. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1034. }
  1035. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1036. }
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  1040. {
  1041. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1042. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1043. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1044. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS2));
  1045. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1046. Message = ReplaceStr(Message, L"|", L"\n");
  1047. return Message;
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1051. TQueryType & Type, bool Force)
  1052. {
  1053. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1054. DebugAssert(Updates.HaveResults);
  1055. if (Updates.HaveResults)
  1056. {
  1057. if (Updates.Results.Disabled)
  1058. {
  1059. New = false;
  1060. if (Force)
  1061. {
  1062. Message = LoadStr(UPDATE_DISABLED);
  1063. }
  1064. }
  1065. else
  1066. {
  1067. New = (Updates.Results.Version > 0);
  1068. if (New)
  1069. {
  1070. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1071. if (!Updates.Results.Release.IsEmpty())
  1072. {
  1073. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1074. }
  1075. Message = FMTLOAD(NEW_VERSION4, (Version));
  1076. }
  1077. else
  1078. {
  1079. Message = LoadStr(NO_NEW_VERSION);
  1080. }
  1081. }
  1082. if (!Message.IsEmpty())
  1083. {
  1084. Message = MainInstructions(Message);
  1085. }
  1086. if (!Updates.Results.Message.IsEmpty())
  1087. {
  1088. Message +=
  1089. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1090. }
  1091. if (!Updates.Results.AuthenticationError.IsEmpty())
  1092. {
  1093. Message +=
  1094. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1095. }
  1096. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1097. }
  1098. else
  1099. {
  1100. New = false;
  1101. }
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall EnableAutomaticUpdates()
  1105. {
  1106. ShowHelp(HELP_AUTOMATIC_UPDATE);
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/, unsigned int & /*Answer*/)
  1110. {
  1111. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1112. OpenBrowser(LoadStr(HISTORY_URL));
  1113. }
  1114. //---------------------------------------------------------------------------
  1115. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1116. {
  1117. return static_cast<int>(Size / 1024);
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. class TUpdateDownloadThread : public TCompThread
  1121. {
  1122. public:
  1123. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1124. virtual __fastcall ~TUpdateDownloadThread();
  1125. void __fastcall CancelClicked(TObject * Sender);
  1126. bool __fastcall CancelDownload();
  1127. __property bool Done = { read = FDone };
  1128. protected:
  1129. virtual void __fastcall Execute();
  1130. void __fastcall UpdateDownloaded();
  1131. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1132. void __fastcall UpdateProgress();
  1133. void __fastcall ShowException();
  1134. void __fastcall DownloadNotVerified();
  1135. void __fastcall CancelForm();
  1136. private:
  1137. TCustomForm * FForm;
  1138. TProgressBar * FProgressBar;
  1139. __int64 FDownloaded;
  1140. std::unique_ptr<Exception> FException;
  1141. std::unique_ptr<THttp> FHttp;
  1142. TUpdatesConfiguration FUpdates;
  1143. bool FDone;
  1144. };
  1145. //---------------------------------------------------------------------------
  1146. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1147. TCompThread(true)
  1148. {
  1149. // cache, as the progress bar miht be destroyed already when
  1150. // we need the form at the end of Execute()
  1151. FForm = GetParentForm(ProgressBar);
  1152. FProgressBar = ProgressBar;
  1153. // cache to prevent concurrency
  1154. FUpdates = WinConfiguration->Updates;
  1155. FDone = false;
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1159. {
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TUpdateDownloadThread::Execute()
  1163. {
  1164. try
  1165. {
  1166. bool Retried = false;
  1167. bool Retry;
  1168. do
  1169. {
  1170. Retry = false;
  1171. try
  1172. {
  1173. FDownloaded = 0;
  1174. FHttp.reset(CreateHttp(FUpdates));
  1175. FHttp->URL = FUpdates.Results.DownloadUrl;
  1176. FHttp->OnDownload = HttpDownload;
  1177. FHttp->Get();
  1178. }
  1179. catch (EAbort &)
  1180. {
  1181. throw;
  1182. }
  1183. catch (Exception & E)
  1184. {
  1185. // The original URL failed, try to get a fresh one and retry
  1186. if (!Retried)
  1187. {
  1188. try
  1189. {
  1190. // Check if new update data (URL particlarly) is available
  1191. if (QueryUpdates(FUpdates) &&
  1192. !FUpdates.Results.DownloadUrl.IsEmpty())
  1193. {
  1194. Retry = true;
  1195. Retried = true;
  1196. }
  1197. }
  1198. catch (...)
  1199. {
  1200. }
  1201. }
  1202. if (!Retry)
  1203. {
  1204. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1205. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1206. }
  1207. }
  1208. }
  1209. while (Retry);
  1210. Synchronize(UpdateDownloaded);
  1211. }
  1212. catch (EAbort &)
  1213. {
  1214. // noop
  1215. }
  1216. catch (Exception & E)
  1217. {
  1218. Configuration->Usage->Inc(L"UpdateFailures");
  1219. FException.reset(CloneException(&E));
  1220. Synchronize(ShowException);
  1221. }
  1222. FDone = true;
  1223. Synchronize(CancelForm);
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. void __fastcall TUpdateDownloadThread::CancelForm()
  1227. {
  1228. FForm->ModalResult = mrCancel;
  1229. }
  1230. //---------------------------------------------------------------------------
  1231. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1232. {
  1233. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1234. const char * Buffer = FHttp->ResponseRaw.c_str();
  1235. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1236. {
  1237. DownloadNotVerified();
  1238. }
  1239. UnicodeString Digest = Sha256(Buffer, Size);
  1240. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1241. {
  1242. DownloadNotVerified();
  1243. }
  1244. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1245. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1246. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1247. UnicodeString SetupPath = SetupPathBase;
  1248. int Index = 0;
  1249. while (FileExists(SetupPath))
  1250. {
  1251. Index++;
  1252. SetupPath =
  1253. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1254. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1255. }
  1256. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1257. FileStream->Write(Buffer, Size);
  1258. FileStream.reset(NULL);
  1259. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1260. if (FUpdates.Results.OpenGettingStarted)
  1261. {
  1262. Params += L" /OpenGettingStarted";
  1263. }
  1264. ExecuteShellChecked(SetupPath, Params);
  1265. Configuration->Usage->Inc(L"UpdateRuns");
  1266. TerminateApplication();
  1267. }
  1268. //---------------------------------------------------------------------------
  1269. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1270. {
  1271. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1272. }
  1273. //---------------------------------------------------------------------------
  1274. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1275. {
  1276. FDownloaded = Size;
  1277. Synchronize(UpdateProgress);
  1278. // Do not waste bandwidth, if something goes wrong
  1279. if (FDownloaded > FUpdates.Results.DownloadSize)
  1280. {
  1281. DownloadNotVerified();
  1282. }
  1283. if (Terminated)
  1284. {
  1285. Cancel = true;
  1286. }
  1287. }
  1288. //---------------------------------------------------------------------------
  1289. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1290. {
  1291. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1292. }
  1293. //---------------------------------------------------------------------------
  1294. void __fastcall TUpdateDownloadThread::ShowException()
  1295. {
  1296. DebugAssert(FException.get() != NULL);
  1297. ShowExtendedException(FException.get());
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1301. {
  1302. bool Result = !Terminated;
  1303. if (Result)
  1304. {
  1305. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1306. Terminate();
  1307. }
  1308. return Result;
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1312. {
  1313. if (CancelDownload())
  1314. {
  1315. WaitFor();
  1316. }
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. //---------------------------------------------------------------------------
  1320. class TUpdateDownloadData : public TComponent
  1321. {
  1322. public:
  1323. TUpdateDownloadThread * Thread;
  1324. __fastcall TUpdateDownloadData() :
  1325. TComponent(NULL)
  1326. {
  1327. }
  1328. virtual __fastcall ~TUpdateDownloadData()
  1329. {
  1330. // will stop the thread
  1331. delete Thread;
  1332. }
  1333. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1334. {
  1335. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1336. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1337. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1338. }
  1339. };
  1340. //---------------------------------------------------------------------------
  1341. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1342. {
  1343. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1344. // If the form was closed by CancelForm at the end of the thread, do nothing
  1345. if (!UpdateDownloadData->Thread->Done)
  1346. {
  1347. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1348. // May this should actually call CancelClicked?
  1349. if (UpdateDownloadData->Thread->CancelDownload())
  1350. {
  1351. Action = caNone;
  1352. }
  1353. }
  1354. }
  1355. //---------------------------------------------------------------------------
  1356. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender, unsigned int & /*Answer*/)
  1357. {
  1358. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1359. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1360. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1361. TPanel * Panel = CreateBlankPanel(Form);
  1362. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1363. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1364. ProgressBar->Top = 0;
  1365. ProgressBar->Left = 0;
  1366. ProgressBar->Width = Panel->Width;
  1367. ProgressBar->Parent = Panel;
  1368. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1369. Panel->Height = ProgressBar->Height;
  1370. InsertPanelToMessageDialog(Form, Panel);
  1371. Button->Enabled = false;
  1372. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1373. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1374. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1375. // The form becomes owner of the thread (via TUpdateDownloadData),
  1376. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1377. // But it gets done only after the form controls are gone, and the thread
  1378. // might try to access them meanwhile. So we stop the thread explicitly.
  1379. CancelButton->OnClick = Thread->CancelClicked;
  1380. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1381. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1382. Data->Thread = Thread;
  1383. Form->InsertComponent(Data);
  1384. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1385. if (!DownloadingUrl.IsEmpty())
  1386. {
  1387. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1388. }
  1389. DebugAssert(Form->OnClose == NULL);
  1390. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1391. Thread->Resume();
  1392. }
  1393. //---------------------------------------------------------------------------
  1394. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1395. {
  1396. EnableAutomaticUpdates();
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1400. {
  1401. const UnicodeString DonatePanelName = L"DonatePanel";
  1402. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1403. // OnShow can happen multiple times, for example when showing dialog on start up (being main window)
  1404. if (FindComponentRecursively(Dialog, DonatePanelName) == NULL)
  1405. {
  1406. UnicodeString DocumentBody = LoadStr(UPDATES_DONATE_HTML);
  1407. DocumentBody = ReplaceStr(DocumentBody, L"%DONATE_URL%", AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1"));
  1408. UnicodeString AboutStoreUrl = LoadStr(ABOUT_STORE_URL);
  1409. DocumentBody = ReplaceStr(DocumentBody, L"%STORE_URL%", AboutStoreUrl);
  1410. UnicodeString StoreButtonUrl = ProgramUrl(LoadStr(STORE_GET_IMG_URL));
  1411. StoreButtonUrl = HTMLEscape(StoreButtonUrl);
  1412. UnicodeString StoreButton =
  1413. FORMAT(L"<img src=\"%s\" style=\"height: 1.8em; vertical-align: -0.4em; padding-top: 0.2em; border: 0;\">", (StoreButtonUrl));
  1414. UnicodeString StoreUrl = FMTLOAD(STORE_URL, (L"update"));
  1415. UnicodeString StoreLink = FORMAT(L"<a href=\"%s\">%s</a>", (StoreUrl, StoreButton));
  1416. UnicodeString PlainBody = HTMLDecode(DocumentBody);
  1417. int P1, P2;
  1418. while (((P1 = PlainBody.Pos(L"<")) > 0) && ((P2 = PlainBody.Pos(L">")) > 0) && (P1 < P2))
  1419. {
  1420. PlainBody.Delete(P1, P2 - P1 + 1);
  1421. }
  1422. while ((P1 = PlainBody.Pos(L" ")) > 0)
  1423. {
  1424. PlainBody.Delete(P1, 1);
  1425. }
  1426. DocumentBody = ReplaceStr(DocumentBody, L"%GET_IMG% ", FORMAT(L"%s&nbsp;", (StoreLink)));
  1427. DocumentBody = FORMAT(L"<p>%s</p>", (DocumentBody));
  1428. TPanel * Panel = CreateBlankPanel(Dialog);
  1429. Panel->Name = DonatePanelName;
  1430. Panel->Caption = UnicodeString(); // override default use of Name
  1431. TWebBrowserEx * DonateBrowser = CreateBrowserViewer(Panel, UnicodeString());
  1432. ReadyBrowserForStreaming(DonateBrowser);
  1433. WaitBrowserToIdle(DonateBrowser);
  1434. int Height = 36;
  1435. int TextWidth = Dialog->Canvas->TextWidth(PlainBody);
  1436. int ContentLimit = (GetMessageDialogContentWidth(Dialog) * 5 / 3);
  1437. if (TextWidth > ContentLimit)
  1438. {
  1439. Height = Height * 3 / 2;
  1440. }
  1441. DonateBrowser->Height = ScaleByTextHeight(Dialog, Height);
  1442. DonateBrowser->Top = 0;
  1443. DonateBrowser->Left = 0;
  1444. Panel->Height = DonateBrowser->Height;
  1445. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1446. // (what should not happen)
  1447. InsertPanelToMessageDialog(Dialog, Panel);
  1448. UnicodeString Document = GenerateAppHtmlPage(Dialog->Font, Panel, DocumentBody, true);
  1449. LoadBrowserDocument(DonateBrowser, Document);
  1450. HideBrowserScrollbars(DonateBrowser);
  1451. }
  1452. }
  1453. //---------------------------------------------------------------------------
  1454. bool __fastcall CheckForUpdates(bool CachedResults)
  1455. {
  1456. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1457. bool Result = false;
  1458. TOperationVisualizer Visualizer;
  1459. try
  1460. {
  1461. if (ActiveForm)
  1462. {
  1463. DebugAssert(ActiveForm->Enabled);
  1464. ActiveForm->Enabled = false;
  1465. }
  1466. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1467. bool Cached =
  1468. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1469. CachedResults;
  1470. if (!Cached)
  1471. {
  1472. DoQueryUpdates(WinConfiguration->CollectUsage);
  1473. // reread new data
  1474. Updates = WinConfiguration->Updates;
  1475. }
  1476. if (!Updates.ShownResults)
  1477. {
  1478. Updates.ShownResults = true;
  1479. WinConfiguration->Updates = Updates;
  1480. }
  1481. DebugAssert(Updates.HaveResults);
  1482. UnicodeString Message;
  1483. bool New;
  1484. TQueryType Type;
  1485. GetUpdatesMessage(Message, New, Type, true);
  1486. Configuration->Usage->Inc(L"UpdateDisplays");
  1487. if (New)
  1488. {
  1489. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1490. }
  1491. if (Updates.HaveResults &&
  1492. (double(Updates.Period) > 0) &&
  1493. // do not show next check time, if we have new version info
  1494. !New)
  1495. {
  1496. Message += L"\n\n" +
  1497. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1498. }
  1499. int Answers = qaOK |
  1500. // show "what's new" button only when change list URL was not provided in results
  1501. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1502. FLAGMASK(New, qaCancel) |
  1503. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1504. TQueryButtonAlias Aliases[4];
  1505. Aliases[0].Button = qaYes;
  1506. if (Updates.Results.UrlButton.IsEmpty())
  1507. {
  1508. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1509. }
  1510. else
  1511. {
  1512. Aliases[0].Alias = Updates.Results.UrlButton;
  1513. }
  1514. Aliases[1].Button = qaAll;
  1515. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1516. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, OpenHistory);
  1517. Aliases[2].Button = qaCancel;
  1518. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1519. // Used only when New == true, see AliasesCount below
  1520. Aliases[3].Button = qaOK;
  1521. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1522. if (!Updates.Results.DownloadUrl.IsEmpty())
  1523. {
  1524. Aliases[3].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, DownloadUpdate);
  1525. Aliases[3].ElevationRequired = true;
  1526. }
  1527. TMessageParams Params;
  1528. Params.Aliases = Aliases;
  1529. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1530. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1531. // alias "ok" button to "upgrade" only if we have new version
  1532. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1533. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1534. if (New)
  1535. {
  1536. Params.ImageName = L"Installer";
  1537. }
  1538. std::unique_ptr<TForm> Dialog(
  1539. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1540. if (New)
  1541. {
  1542. // Internet Explorer on Windows XP cannot talk to CDN77, where we host Store Get button.
  1543. // As a simple solution, we just do not display the donation panel on Windows XP.
  1544. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled() && IsWinVista())
  1545. {
  1546. DebugAssert(Dialog->OnShow == NULL);
  1547. // InsertDonateLink need to be called only after MessageBrowser is created
  1548. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1549. }
  1550. }
  1551. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1552. switch (Answer)
  1553. {
  1554. case qaOK:
  1555. if (New)
  1556. {
  1557. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1558. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1559. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1560. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1561. OpenBrowser(UpgradeUrl);
  1562. Result = true;
  1563. }
  1564. break;
  1565. case qaYes:
  1566. OpenBrowser(Updates.Results.Url);
  1567. break;
  1568. case qaAll:
  1569. DebugFail();
  1570. break;
  1571. }
  1572. }
  1573. __finally
  1574. {
  1575. if (ActiveForm)
  1576. {
  1577. ActiveForm->Enabled = true;
  1578. }
  1579. }
  1580. return Result;
  1581. }
  1582. //---------------------------------------------------------------------------
  1583. class TUpdateThread : public TCompThread
  1584. {
  1585. public:
  1586. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1587. protected:
  1588. virtual void __fastcall Execute();
  1589. TThreadMethod FOnUpdatesChecked;
  1590. };
  1591. //---------------------------------------------------------------------------
  1592. TUpdateThread * UpdateThread = NULL;
  1593. //---------------------------------------------------------------------------
  1594. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1595. TCompThread(false),
  1596. FOnUpdatesChecked(OnUpdatesChecked)
  1597. {
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. void __fastcall TUpdateThread::Execute()
  1601. {
  1602. try
  1603. {
  1604. DoQueryUpdates(WinConfiguration->CollectUsage);
  1605. if (FOnUpdatesChecked != NULL)
  1606. {
  1607. Synchronize(FOnUpdatesChecked);
  1608. }
  1609. }
  1610. catch(...)
  1611. {
  1612. // ignore errors
  1613. }
  1614. }
  1615. //---------------------------------------------------------------------------
  1616. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1617. {
  1618. DebugAssert(UpdateThread == NULL);
  1619. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1620. }
  1621. //---------------------------------------------------------------------------
  1622. void __fastcall StopUpdateThread()
  1623. {
  1624. if (UpdateThread != NULL)
  1625. {
  1626. SAFE_DESTROY(UpdateThread);
  1627. }
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. void __fastcall SetupInitialize()
  1631. {
  1632. WinConfiguration->UpdateJumpList();
  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. void __fastcall ShowTips()
  1968. {
  1969. {
  1970. TOperationVisualizer Visualizer;
  1971. DoQueryUpdates(false);
  1972. }
  1973. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1974. {
  1975. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1976. }
  1977. Configuration->Usage->Inc(L"TipsShownCommand");
  1978. ShowTip(false);
  1979. }
  1980. //---------------------------------------------------------------------------
  1981. void __fastcall TipsUpdateStaticUsage()
  1982. {
  1983. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1984. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1985. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1986. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1987. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1988. }
  1989. //---------------------------------------------------------------------------
  1990. static void ReadNetVersion(TRegistryStorage * Registry)
  1991. {
  1992. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  1993. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  1994. {
  1995. NetVersionStr = VersionStr;
  1996. }
  1997. }
  1998. //---------------------------------------------------------------------------
  1999. UnicodeString __fastcall GetNetVersionStr()
  2000. {
  2001. if (NetVersionStr.IsEmpty())
  2002. {
  2003. NetVersionStr = L"0"; // not to retry on failure
  2004. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  2005. if (Registry->OpenRootKey(false))
  2006. {
  2007. std::unique_ptr<TStringList> Keys(new TStringList());
  2008. Registry->GetSubKeyNames(Keys.get());
  2009. for (int Index = 0; Index < Keys->Count; Index++)
  2010. {
  2011. UnicodeString Key = Keys->Strings[Index];
  2012. if (Registry->OpenSubKey(Key, false))
  2013. {
  2014. ReadNetVersion(Registry.get());
  2015. if (Registry->OpenSubKey(L"Full", false))
  2016. {
  2017. ReadNetVersion(Registry.get());
  2018. Registry->CloseSubKey();
  2019. }
  2020. if (Registry->OpenSubKey(L"Client", false))
  2021. {
  2022. ReadNetVersion(Registry.get());
  2023. Registry->CloseSubKey();
  2024. }
  2025. Registry->CloseSubKey();
  2026. }
  2027. }
  2028. }
  2029. }
  2030. return NetVersionStr;
  2031. }
  2032. //---------------------------------------------------------------------------
  2033. UnicodeString __fastcall GetPowerShellVersionStr()
  2034. {
  2035. if (PowerShellVersionStr.IsEmpty())
  2036. {
  2037. PowerShellVersionStr = 0; // not to retry on failure
  2038. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2039. if (Registry->OpenRootKey(false))
  2040. {
  2041. std::unique_ptr<TStringList> Keys(new TStringList());
  2042. Registry->GetSubKeyNames(Keys.get());
  2043. for (int Index = 0; Index < Keys->Count; Index++)
  2044. {
  2045. UnicodeString Key = Keys->Strings[Index];
  2046. if (Registry->OpenSubKeyPath(Key + L"\\PowerShellEngine", false))
  2047. {
  2048. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2049. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2050. {
  2051. PowerShellVersionStr = VersionStr;
  2052. }
  2053. Registry->CloseSubKeyPath();
  2054. }
  2055. }
  2056. }
  2057. }
  2058. return PowerShellVersionStr;
  2059. }
  2060. //---------------------------------------------------------------------------
  2061. //---------------------------------------------------------------------------
  2062. static void CollectCLSIDKey(
  2063. TConsole * Console, TStrings * Keys, int PlatformSet, TRegistryStorage * Storage, const UnicodeString & CLSID,
  2064. UnicodeString & CommonCodeBase, const UnicodeString & Platform, UnicodeString & Platforms)
  2065. {
  2066. UnicodeString CLSIDKey = FORMAT(L"CLSID\\%s", (CLSID));
  2067. if (Storage->OpenSubKeyPath(CLSIDKey, false))
  2068. {
  2069. int Index = Keys->IndexOf(CLSIDKey);
  2070. if (Index >= 0)
  2071. {
  2072. Keys->Objects[Index] = reinterpret_cast<TObject *>(PlatformSet | reinterpret_cast<int>(Keys->Objects[Index]));
  2073. }
  2074. else
  2075. {
  2076. Keys->AddObject(CLSIDKey, reinterpret_cast<TObject *>(PlatformSet));
  2077. }
  2078. UnicodeString CodeBase;
  2079. if (Storage->OpenSubKey(L"InprocServer32", false))
  2080. {
  2081. CodeBase = Storage->ReadString(L"CodeBase", UnicodeString());
  2082. UnicodeString Assembly = Storage->ReadString(L"Assembly", UnicodeString());
  2083. UnicodeString Version;
  2084. if (!Assembly.IsEmpty())
  2085. {
  2086. UnicodeString VersionPrefix = L"Version=";
  2087. int P = Assembly.UpperCase().Pos(VersionPrefix.UpperCase());
  2088. if (P > 0)
  2089. {
  2090. Assembly.Delete(1, P + VersionPrefix.Length() - 1);
  2091. Version = CutToChar(Assembly, L',', true);
  2092. }
  2093. }
  2094. if (CodeBase.IsEmpty() || Version.IsEmpty())
  2095. {
  2096. Console->PrintLine(FORMAT(L"Warning: Could not find codebase and version for %s.", (CLSID)));
  2097. CodeBase = UnicodeString();
  2098. }
  2099. else
  2100. {
  2101. CodeBase = FORMAT(L"%s (%s)", (CodeBase, Version));
  2102. if (CommonCodeBase.IsEmpty())
  2103. {
  2104. Console->PrintLine(FORMAT(L"Codebase %s, unless stated otherwise", (CodeBase)));
  2105. CommonCodeBase = CodeBase;
  2106. }
  2107. if (SameText(CommonCodeBase, CodeBase))
  2108. {
  2109. CodeBase = L"";
  2110. }
  2111. }
  2112. Storage->CloseSubKey();
  2113. }
  2114. Storage->CloseSubKeyPath();
  2115. UnicodeString Buf = Platform;
  2116. AddToList(Buf, CodeBase, L" - ");
  2117. AddToList(Platforms, Buf, ", ");
  2118. }
  2119. }
  2120. //---------------------------------------------------------------------------
  2121. static UnicodeString PlatformStr(int PlatformSet)
  2122. {
  2123. UnicodeString Result;
  2124. if (PlatformSet == 0)
  2125. {
  2126. Result = L"shared";
  2127. }
  2128. else
  2129. {
  2130. if (FLAGSET(PlatformSet, 32))
  2131. {
  2132. Result = L"32-bit";
  2133. }
  2134. if (FLAGSET(PlatformSet, 64))
  2135. {
  2136. AddToList(Result, L"64-bit", L", ");
  2137. }
  2138. }
  2139. return Result;
  2140. }
  2141. //---------------------------------------------------------------------------
  2142. static void DoCollectComRegistration(TConsole * Console, TStrings * Keys)
  2143. {
  2144. UnicodeString TypeLib = L"{A0B93468-D98A-4845-A234-8076229AD93F}"; // Duplicated in AssemblyInfo.cs
  2145. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT));
  2146. Storage->MungeStringValues = false;
  2147. Storage->AccessMode = smRead;
  2148. std::unique_ptr<TRegistryStorage> Storage64;
  2149. if (IsWin64())
  2150. {
  2151. Storage64.reset(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT, KEY_WOW64_64KEY));
  2152. Storage64->MungeStringValues = false;
  2153. Storage64->AccessMode = smRead;
  2154. }
  2155. // Classes, TypeLib and Record are shared between 32-bit and 64-bit registry view.
  2156. // 32-bit and 64-bit version of regasm adds CLSID keys to its respective view.
  2157. // Both 32-bit and 64-bit version of regasm seem to add Interface keys to both 32-bit and 64-bit views.
  2158. // On Vista, Interface keys are reflected (so when 32-bit keys is deleted, it's also deleted from 64-bit key,
  2159. // and we show an error, trying to delete the 64-bit key).
  2160. if (Storage->OpenRootKey(false))
  2161. {
  2162. Console->PrintLine(FORMAT(L"Versions of type library %s:", (TypeLib)));
  2163. UnicodeString TypeLibKey = FORMAT(L"TypeLib\\%s", (TypeLib));
  2164. if (Storage->OpenSubKeyPath(TypeLibKey, false))
  2165. {
  2166. Keys->Add(TypeLibKey);
  2167. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2168. Storage->GetSubKeyNames(KeyNames.get());
  2169. if (KeyNames->Count == 0)
  2170. {
  2171. Console->PrintLine(L"Warning: The type library key exists, but no type libraries are present.");
  2172. }
  2173. else
  2174. {
  2175. for (int Index = 0; Index < KeyNames->Count; Index++)
  2176. {
  2177. UnicodeString Version = KeyNames->Strings[Index];
  2178. if (!Storage->OpenSubKeyPath(FORMAT(L"%s\\0", (Version)), false))
  2179. {
  2180. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" cannot be opened.", (Version)));
  2181. }
  2182. else
  2183. {
  2184. std::unique_ptr<TStringList> Platforms(new TStringList());
  2185. Storage->GetSubKeyNames(Platforms.get());
  2186. if (Platforms->Count == 0)
  2187. {
  2188. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" exists, but platforms are present.", (Version)));
  2189. }
  2190. else
  2191. {
  2192. for (int Index2 = 0; Index2 < Platforms->Count; Index2++)
  2193. {
  2194. UnicodeString Platform = Platforms->Strings[Index2];
  2195. if (!Storage->OpenSubKey(Platform, false))
  2196. {
  2197. Console->PrintLine(FORMAT(L"Warning: Platform \"%s\" for type library \"%s\" cannot be opened.", (Platform, Version)));
  2198. }
  2199. else
  2200. {
  2201. UnicodeString TypeLibraryPath = Storage->ReadString(UnicodeString(), UnicodeString());
  2202. UnicodeString Exists = FileExists(TypeLibraryPath) ? L"exists" : L"does not exist";
  2203. Console->PrintLine(FORMAT(L"%s (%s): %s (%s)", (Version, Platform, TypeLibraryPath, Exists)));
  2204. Storage->CloseSubKey();
  2205. }
  2206. }
  2207. }
  2208. Storage->CloseSubKeyPath();
  2209. }
  2210. }
  2211. }
  2212. Storage->CloseSubKeyPath();
  2213. }
  2214. else
  2215. {
  2216. Console->PrintLine(L"Type library not registered.");
  2217. }
  2218. Console->PrintLine();
  2219. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2220. Storage->GetSubKeyNames(KeyNames.get());
  2221. UnicodeString NamespacePrefix = L"WinSCP.";
  2222. Console->PrintLine(L"Classes:");
  2223. UnicodeString CommonCodeBase;
  2224. int Found = 0;
  2225. for (int Index = 0; Index < KeyNames->Count; Index++)
  2226. {
  2227. UnicodeString KeyName = KeyNames->Strings[Index];
  2228. if (StartsText(NamespacePrefix, KeyName))
  2229. {
  2230. if (Storage->OpenSubKeyPath(FORMAT(L"%s\\%s", (KeyName, L"CLSID")), false))
  2231. {
  2232. UnicodeString Class = KeyName;
  2233. UnicodeString CLSID = Trim(Storage->ReadString(UnicodeString(), UnicodeString()));
  2234. Storage->CloseSubKeyPath();
  2235. if (!CLSID.IsEmpty())
  2236. {
  2237. Keys->Add(KeyName);
  2238. UnicodeString Platforms;
  2239. CollectCLSIDKey(Console, Keys, 32, Storage.get(), CLSID, CommonCodeBase, L"32-bit", Platforms);
  2240. if (Storage64.get() != NULL)
  2241. {
  2242. CollectCLSIDKey(Console, Keys, 64, Storage64.get(), CLSID, CommonCodeBase, L"64-bit", Platforms);
  2243. }
  2244. UnicodeString Line = FORMAT(L"%s - %s", (Class, CLSID));
  2245. if (Platforms.IsEmpty())
  2246. {
  2247. Console->PrintLine(FORMAT(L"Warning: Could not find CLSID %s for class %s.", (CLSID, Class)));
  2248. }
  2249. else
  2250. {
  2251. Line += FORMAT(L" [%s]", (Platforms));
  2252. }
  2253. Console->PrintLine(Line);
  2254. Found++;
  2255. }
  2256. }
  2257. }
  2258. }
  2259. if (Found == 0)
  2260. {
  2261. Console->PrintLine(L"No classes found.");
  2262. }
  2263. Console->PrintLine();
  2264. UnicodeString InterfaceKey = L"Interface";
  2265. if (Storage->OpenSubKey(InterfaceKey, false) &&
  2266. ((Storage64.get() == NULL) || Storage64->OpenSubKey(InterfaceKey, false)))
  2267. {
  2268. Console->PrintLine(L"Interfaces:");
  2269. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2270. Storage->GetSubKeyNames(KeyNames.get());
  2271. KeyNames->Sorted = true;
  2272. for (int Index = 0; Index < KeyNames->Count; Index++)
  2273. {
  2274. KeyNames->Objects[Index] = reinterpret_cast<TObject *>(32);
  2275. }
  2276. if (Storage64.get() != NULL)
  2277. {
  2278. std::unique_ptr<TStringList> KeyNames64(new TStringList());
  2279. Storage64->GetSubKeyNames(KeyNames64.get());
  2280. for (int Index = 0; Index < KeyNames64->Count; Index++)
  2281. {
  2282. UnicodeString Key64 = KeyNames64->Strings[Index];
  2283. int Index32 = KeyNames->IndexOf(Key64);
  2284. if (Index32 >= 0)
  2285. {
  2286. KeyNames->Objects[Index32] = reinterpret_cast<TObject *>(32 | 64);
  2287. }
  2288. else
  2289. {
  2290. KeyNames->AddObject(Key64, reinterpret_cast<TObject *>(64));
  2291. }
  2292. }
  2293. }
  2294. int Found = 0;
  2295. for (int Index = 0; Index < KeyNames->Count; Index++)
  2296. {
  2297. UnicodeString KeyName = KeyNames->Strings[Index];
  2298. // Open sub key first, to check if we are interested in the interface, as an optimization
  2299. int PlatformSet = reinterpret_cast<int>(KeyNames->Objects[Index]);
  2300. THierarchicalStorage * KeyStorage = FLAGSET(PlatformSet, 32) ? Storage.get() : Storage64.get();
  2301. if (KeyStorage->OpenSubKeyPath(FORMAT(L"%s\\TypeLib", (KeyName)), false))
  2302. {
  2303. UnicodeString InterfaceTypeLib = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2304. UnicodeString Version = KeyStorage->ReadString(L"Version", UnicodeString());
  2305. KeyStorage->CloseSubKeyPath();
  2306. if (SameText(InterfaceTypeLib, TypeLib))
  2307. {
  2308. if (KeyStorage->OpenSubKey(KeyName, false))
  2309. {
  2310. UnicodeString Key = ExcludeTrailingBackslash(KeyStorage->CurrentSubKey);
  2311. UnicodeString Interface = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2312. KeyStorage->CloseSubKey();
  2313. Keys->AddObject(Key, reinterpret_cast<TObject *>(PlatformSet));
  2314. Console->PrintLine(FORMAT(L"%s - %s (%s) [%s]", (Interface, KeyName, Version, PlatformStr(PlatformSet))));
  2315. Found++;
  2316. }
  2317. }
  2318. }
  2319. }
  2320. if (Found == 0)
  2321. {
  2322. Console->PrintLine(L"No interfaces found.");
  2323. }
  2324. Storage->CloseSubKey();
  2325. Console->PrintLine();
  2326. }
  2327. if (Storage->OpenSubKey(L"Record", false))
  2328. {
  2329. Console->PrintLine(L"Value types:");
  2330. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2331. Storage->GetSubKeyNames(KeyNames.get());
  2332. int Found = 0;
  2333. for (int Index = 0; Index < KeyNames->Count; Index++)
  2334. {
  2335. UnicodeString KeyName = KeyNames->Strings[Index];
  2336. if (Storage->OpenSubKey(KeyName, false))
  2337. {
  2338. std::unique_ptr<TStringList> Versions(new TStringList());
  2339. Storage->GetSubKeyNames(Versions.get());
  2340. UnicodeString VersionsStr;
  2341. std::unique_ptr<TStringList> Classes(CreateSortedStringList());
  2342. for (int Index2 = 0; Index2 < Versions->Count; Index2++)
  2343. {
  2344. UnicodeString Version = Versions->Strings[Index2];
  2345. if (Storage->OpenSubKey(Version, false))
  2346. {
  2347. UnicodeString Class = Storage->ReadString(L"Class", UnicodeString());
  2348. Classes->Add(Class);
  2349. if (StartsStr(NamespacePrefix, Class))
  2350. {
  2351. AddToList(VersionsStr, Version, L", ");
  2352. }
  2353. Storage->CloseSubKey();
  2354. }
  2355. }
  2356. if (!VersionsStr.IsEmpty())
  2357. {
  2358. if (Classes->Count != 1)
  2359. {
  2360. Console->PrintLine(FORMAT(L"Warning: Different class names for the same value type %s: %s", (KeyName, Classes->CommaText)));
  2361. }
  2362. else
  2363. {
  2364. Keys->Add(ExcludeTrailingBackslash(Storage->CurrentSubKey));
  2365. Console->PrintLine(FORMAT(L"%s - %s (%s)", (Classes->Strings[0], KeyName, VersionsStr)));
  2366. Found++;
  2367. }
  2368. }
  2369. Storage->CloseSubKey();
  2370. }
  2371. }
  2372. if (Found == 0)
  2373. {
  2374. Console->PrintLine(L"No value types found.");
  2375. }
  2376. Storage->CloseSubKey();
  2377. Console->PrintLine();
  2378. }
  2379. }
  2380. }
  2381. //---------------------------------------------------------------------------
  2382. bool DoUnregisterChoice(TConsole * Console)
  2383. {
  2384. return (Console->Choice(L"U", -1, -1, -1, 0, 0, 0, UnicodeString()) == 1);
  2385. }
  2386. //---------------------------------------------------------------------------
  2387. typedef HRESULT WINAPI (* RegDeleteTreeProc)(HKEY Key, LPCWSTR SubKey);
  2388. static RegDeleteTreeProc ARegDeleteTree = NULL;
  2389. //---------------------------------------------------------------------------
  2390. void DoDeleteKey(TConsole * Console, TRegistry * Registry, const UnicodeString & Key, int Platform, bool & AnyDeleted, bool & AllDeleted)
  2391. {
  2392. UnicodeString ParentKey = ExtractFileDir(Key);
  2393. UnicodeString ChildKey = ExtractFileName(Key);
  2394. bool Result = Registry->OpenKey(ParentKey, false);
  2395. if (Result)
  2396. {
  2397. if (DebugAlwaysFalse(ARegDeleteTree == NULL))
  2398. {
  2399. Result = false;
  2400. }
  2401. else
  2402. {
  2403. Result = (ARegDeleteTree(Registry->CurrentKey, ChildKey.c_str()) == 0);
  2404. }
  2405. Registry->CloseKey();
  2406. }
  2407. UnicodeString Status;
  2408. if (Result)
  2409. {
  2410. Status = L"removed";
  2411. AnyDeleted = true;
  2412. }
  2413. else
  2414. {
  2415. AllDeleted = false;
  2416. Status = L"NOT removed";
  2417. }
  2418. Console->PrintLine(FORMAT(L"%s [%s] - %s", (Key, PlatformStr(Platform), Status)));
  2419. }
  2420. //---------------------------------------------------------------------------
  2421. int ComRegistration(TConsole * Console)
  2422. {
  2423. int Result = RESULT_SUCCESS;
  2424. try
  2425. {
  2426. if (ARegDeleteTree == NULL)
  2427. {
  2428. HINSTANCE AdvapiLibrary = LoadLibrary(L"advapi32.dll");
  2429. if (DebugAlwaysTrue(AdvapiLibrary != NULL))
  2430. {
  2431. ARegDeleteTree = reinterpret_cast<RegDeleteTreeProc>(GetProcAddress(AdvapiLibrary, "RegDeleteTreeW"));
  2432. }
  2433. }
  2434. if (ARegDeleteTree == NULL)
  2435. {
  2436. throw Exception(FORMAT(L"Not supported on %s", (GetOSInfo())));
  2437. }
  2438. Console->PrintLine(GetEnvironmentInfo());
  2439. Console->PrintLine();
  2440. std::unique_ptr<TStrings> Keys(new TStringList());
  2441. DoCollectComRegistration(Console, Keys.get());
  2442. if (Keys->Count == 0)
  2443. {
  2444. Console->PrintLine(L"No registration found.");
  2445. Console->WaitBeforeExit();
  2446. }
  2447. else
  2448. {
  2449. Console->PrintLine(L"Press (U) to unregister or Esc to exit...");
  2450. if (DoUnregisterChoice(Console))
  2451. {
  2452. Console->PrintLine();
  2453. Console->PrintLine(L"The following registry keys will be removed from HKCR registry hive:");
  2454. for (int Index = 0; Index < Keys->Count; Index++)
  2455. {
  2456. Console->PrintLine(FORMAT(L"%s [%s]", (Keys->Strings[Index], PlatformStr(reinterpret_cast<int>(Keys->Objects[Index])))));
  2457. }
  2458. Console->PrintLine();
  2459. Console->PrintLine(L"You need Administrator privileges to remove the keys.");
  2460. Console->PrintLine(L"Press (U) again to proceed with unregistration or Esc to abort...");
  2461. if (DoUnregisterChoice(Console))
  2462. {
  2463. std::unique_ptr<TRegistry> Registry64(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_64KEY));
  2464. Registry64->RootKey = HKEY_CLASSES_ROOT;
  2465. std::unique_ptr<TRegistry> Registry32(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_32KEY));
  2466. Registry32->RootKey = HKEY_CLASSES_ROOT;
  2467. bool AnyDeleted = false;
  2468. bool AllDeleted = true;
  2469. for (int Index = 0; Index < Keys->Count; Index++)
  2470. {
  2471. UnicodeString Key = Keys->Strings[Index];
  2472. int PlatformSet = reinterpret_cast<int>(Keys->Objects[Index]);
  2473. if (PlatformSet == 0)
  2474. {
  2475. DoDeleteKey(Console, Registry32.get(), Key, 0, AnyDeleted, AllDeleted);
  2476. }
  2477. else
  2478. {
  2479. if (FLAGSET(PlatformSet, 32))
  2480. {
  2481. DoDeleteKey(Console, Registry32.get(), Key, 32, AnyDeleted, AllDeleted);
  2482. }
  2483. if (FLAGSET(PlatformSet, 64))
  2484. {
  2485. DoDeleteKey(Console, Registry64.get(), Key, 64, AnyDeleted, AllDeleted);
  2486. }
  2487. }
  2488. }
  2489. Console->PrintLine();
  2490. if (!AnyDeleted)
  2491. {
  2492. Console->PrintLine(L"No keys were removed. Make sure you have Administrator privileges.");
  2493. }
  2494. else if (!AllDeleted)
  2495. {
  2496. Console->PrintLine(L"Some keys were not removed. Make sure you have Administrator privileges.");
  2497. }
  2498. else
  2499. {
  2500. Console->PrintLine(L"All keys were removed. Unregistration succeeded.");
  2501. }
  2502. Console->WaitBeforeExit();
  2503. }
  2504. }
  2505. }
  2506. }
  2507. catch (Exception & E)
  2508. {
  2509. Result = HandleException(Console, E);
  2510. Console->WaitBeforeExit();
  2511. }
  2512. return Result;
  2513. }