Setup.cpp 100 KB

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