Setup.cpp 97 KB

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