Setup.cpp 94 KB

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