Setup.cpp 91 KB

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