Setup.cpp 91 KB

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