Setup.cpp 98 KB

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