Setup.cpp 90 KB

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