Setup.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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 <HelpWin.h>
  16. #include <TcpIp.hpp>
  17. #include <CompThread.hpp>
  18. #include <FileInfo.h>
  19. #include "WinConfiguration.h"
  20. #include "WinInterface.h"
  21. #include "Tools.h"
  22. #include "Setup.h"
  23. #include <StrUtils.hpp>
  24. #include "ProgParams.h"
  25. #include <Consts.hpp>
  26. //---------------------------------------------------------------------------
  27. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  28. _T("Session Manager\\Environment")
  29. // when the PATH registry key is over aprox 2048 characters,
  30. // PATH as well as WINDIR variables are actually not set, breaking the system
  31. #define MAX_PATH_LEN 2000
  32. /* Command line options. */
  33. UnicodeString LastPathError;
  34. //---------------------------------------------------------------------------
  35. // Display the error "err_msg".
  36. void err_out(LPCTSTR err_msg)
  37. {
  38. LastPathError = err_msg;
  39. }
  40. //---------------------------------------------------------------------------
  41. // Display "base_err_msg" followed by the description of the system error
  42. // identified by "sys_err".
  43. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  44. {
  45. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  46. }
  47. //---------------------------------------------------------------------------
  48. // Works as "strcmp" but the comparison is not case sensitive.
  49. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  50. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  51. if (*str1 == L'\0')
  52. return 0;
  53. return tolower(*str1) - tolower(*str2);
  54. }
  55. //---------------------------------------------------------------------------
  56. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  57. // not present). The returned value must be freed with "free".
  58. LPTSTR unquote(LPCTSTR str){
  59. int last_pos;
  60. LPTSTR ret;
  61. size_t new_len;
  62. last_pos = _tcslen(str) - 1;
  63. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  64. new_len= (_tcslen(str) - 1);
  65. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  66. lstrcpyn(ret, &str[1], new_len);
  67. }
  68. else
  69. ret = _tcsdup(str);
  70. return ret;
  71. }
  72. //---------------------------------------------------------------------------
  73. // Find "what" in the ";" separated string "str" and returns a pointer to
  74. // the first letter of "what" in the string. If "next" is not "NULL" it
  75. // points to the first letter after "what" (excluding the trailing ";").
  76. // If "what" isn't find the functions returns "NULL".
  77. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  78. LPTSTR tok_buff;
  79. LPTSTR curr_tok;
  80. LPTSTR curr_tok_dup;
  81. BOOL path_eq;
  82. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  83. int pos = -1;
  84. LPTSTR ret;
  85. tok_buff = _tcsdup(str);
  86. curr_tok = _tcstok(tok_buff, _T(";"));
  87. while (pos == -1 && curr_tok){
  88. curr_tok_dup = unquote(curr_tok);
  89. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  90. GetShortPathName(curr_tok_dup, sh_path2,
  91. LENOF(sh_path2)) &&
  92. (tcharicmp(sh_path1, sh_path2) == 0);
  93. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  94. pos = curr_tok - tok_buff;
  95. }
  96. free(curr_tok_dup);
  97. curr_tok = _tcstok(NULL, _T(";"));
  98. if (pos != -1 && next){
  99. if (curr_tok)
  100. *next = str + (curr_tok - tok_buff);
  101. else
  102. *next = str + _tcslen(str);
  103. }
  104. }
  105. free(tok_buff);
  106. if (pos != -1)
  107. ret = str + pos;
  108. else
  109. ret = NULL;
  110. return ret;
  111. }
  112. //---------------------------------------------------------------------------
  113. void path_reg_propagate()
  114. {
  115. DWORD send_message_result;
  116. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  117. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  118. 5000, &send_message_result);
  119. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  120. {
  121. err_out_sys(_T("Cannot propagate the new enviroment to ")
  122. _T("other processes. The new value will be ")
  123. _T("avaible after a reboot."), GetLastError());
  124. SimpleErrorDialog(LastPathError);
  125. LastPathError = L"";
  126. }
  127. }
  128. //---------------------------------------------------------------------------
  129. // Add "path" to the registry. Return "TRUE" if the path has been added or
  130. // was already in the registry, "FALSE" otherwise.
  131. BOOL add_path_reg(LPCTSTR path){
  132. HKEY key;
  133. LONG ret;
  134. DWORD data_size;
  135. LPTSTR reg_str;
  136. BOOL func_ret = TRUE;
  137. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  138. KEY_WRITE | KEY_READ, &key);
  139. if (ret != ERROR_SUCCESS){
  140. err_out_sys(_T("Cannot open registry."), ret);
  141. return FALSE;
  142. }
  143. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  144. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  145. includes '\0'. */
  146. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  147. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  148. &data_size);
  149. if (ret != ERROR_SUCCESS){
  150. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  151. func_ret = FALSE;
  152. }
  153. else{
  154. if (!find_reg_str(reg_str, path, NULL)){
  155. _tcscat(reg_str, _T(";"));
  156. _tcscat(reg_str, path);
  157. size_t len = _tcslen(reg_str);
  158. if (len >= MAX_PATH_LEN)
  159. {
  160. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  161. func_ret = FALSE;
  162. }
  163. else
  164. {
  165. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  166. (LPBYTE)reg_str,
  167. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  168. if (ret != ERROR_SUCCESS){
  169. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  170. func_ret = FALSE;
  171. }
  172. /* Is this needed to make the new key avaible? */
  173. RegFlushKey(key);
  174. SetLastError(0);
  175. path_reg_propagate();
  176. }
  177. }
  178. }
  179. RegCloseKey(key);
  180. free(reg_str);
  181. return func_ret;
  182. }
  183. //---------------------------------------------------------------------------
  184. // Removes "path" from the registry. Return "TRUE" if the path has been
  185. // removed or it wasn't in the registry, "FALSE" otherwise.
  186. BOOL remove_path_reg(LPCTSTR path){
  187. HKEY key;
  188. LONG ret;
  189. DWORD data_size;
  190. LPTSTR reg_str;
  191. LPTSTR reg_str2;
  192. BOOL func_ret = TRUE;
  193. LPTSTR next;
  194. LPTSTR del_part;
  195. int last_pos;
  196. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  197. KEY_WRITE | KEY_READ, &key);
  198. if (ret != ERROR_SUCCESS){
  199. err_out_sys(_T("Cannot open registry."), ret);
  200. return FALSE;
  201. }
  202. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  203. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  204. includes '\0'. */
  205. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  206. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  207. (LPBYTE)reg_str, &data_size);
  208. if (ret != ERROR_SUCCESS){
  209. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  210. func_ret = FALSE;
  211. }
  212. else{
  213. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  214. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  215. *del_part = '\0';
  216. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  217. last_pos = _tcslen(reg_str2) - 1;
  218. if (last_pos != -1 && reg_str2[last_pos] == ';')
  219. reg_str2[last_pos] = '\0';
  220. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  221. (LPBYTE)reg_str2,
  222. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  223. if (ret != ERROR_SUCCESS){
  224. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  225. func_ret = FALSE;
  226. }
  227. free(reg_str2);
  228. /* Is this needed to make the new key avaible? */
  229. RegFlushKey(key);
  230. SetLastError(0);
  231. path_reg_propagate();
  232. }
  233. }
  234. RegCloseKey(key);
  235. free(reg_str);
  236. return func_ret;
  237. }
  238. //---------------------------------------------------------------------------
  239. //---------------------------------------------------------------------------
  240. void __fastcall AddSearchPath(const UnicodeString Path)
  241. {
  242. if (!add_path_reg(Path.c_str()))
  243. {
  244. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  245. }
  246. }
  247. //---------------------------------------------------------------------------
  248. void __fastcall RemoveSearchPath(const UnicodeString Path)
  249. {
  250. if (!remove_path_reg(Path.c_str()))
  251. {
  252. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  253. }
  254. }
  255. //---------------------------------------------------------------------------
  256. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  257. //---------------------------------------------------------------------------
  258. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  259. {
  260. if (Registry->OpenKey(Key, false))
  261. {
  262. std::unique_ptr<TStrings> List(new TStringList());
  263. Registry->GetValueNames(List.get());
  264. bool CanDelete = true;
  265. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  266. {
  267. UnicodeString ValueName = List->Strings[Index];
  268. if (!AllowRootValues)
  269. {
  270. CanDelete = false;
  271. }
  272. if ((ValueName != L"") &&
  273. (ValueName != L"URL Protocol") &&
  274. (ValueName != L"EditFlags") &&
  275. (ValueName != L"BrowserFlags"))
  276. {
  277. CanDelete = false;
  278. }
  279. }
  280. List->Clear();
  281. Registry->GetKeyNames(List.get());
  282. Registry->CloseKey();
  283. if (CanDelete)
  284. {
  285. for (int Index = 0; Index < List->Count; Index++)
  286. {
  287. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  288. }
  289. // will fail, if not all subkeys got removed
  290. Registry->DeleteKey(Key);
  291. }
  292. }
  293. }
  294. //---------------------------------------------------------------------------
  295. static void __fastcall RegisterProtocol(TRegistry * Registry,
  296. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  297. {
  298. if (Description.IsEmpty())
  299. {
  300. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  301. }
  302. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  303. if (Force || !Registry->KeyExists(ProtocolKey))
  304. {
  305. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  306. {
  307. Registry->WriteString(L"", Description);
  308. Registry->WriteString(L"URL Protocol", L"");
  309. Registry->WriteInteger(L"EditFlags", 0x02);
  310. Registry->WriteInteger(L"BrowserFlags", 0x08);
  311. if (Registry->OpenKey(L"DefaultIcon", true))
  312. {
  313. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  314. Registry->CloseKey();
  315. }
  316. else
  317. {
  318. Abort();
  319. }
  320. }
  321. else
  322. {
  323. Abort();
  324. }
  325. }
  326. }
  327. //---------------------------------------------------------------------------
  328. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  329. const UnicodeString & Protocol)
  330. {
  331. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  332. }
  333. //---------------------------------------------------------------------------
  334. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  335. {
  336. std::unique_ptr<TRegistry> Registry(new TRegistry());
  337. Registry->Access = KEY_WRITE | KEY_READ;
  338. Registry->RootKey = RootKey;
  339. return Registry.release();
  340. }
  341. //---------------------------------------------------------------------------
  342. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  343. const UnicodeString & Protocol, UnicodeString Description = L"")
  344. {
  345. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  346. RegisterProtocol(Registry.get(), Protocol, Description, true);
  347. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  348. Registry->OpenKey(L"shell", true) &&
  349. Registry->OpenKey(L"open", true) &&
  350. Registry->OpenKey(L"command", true))
  351. {
  352. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  353. Registry->CloseKey();
  354. }
  355. else
  356. {
  357. Abort();
  358. }
  359. }
  360. //---------------------------------------------------------------------------
  361. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  362. {
  363. try
  364. {
  365. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  366. // get rid of any HKCU registraction that would overrite the HKLM one
  367. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  368. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  369. {
  370. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  371. }
  372. }
  373. catch (Exception & E)
  374. {
  375. try
  376. {
  377. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  378. }
  379. catch(Exception & E)
  380. {
  381. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  382. }
  383. }
  384. }
  385. //---------------------------------------------------------------------------
  386. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  387. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  388. {
  389. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  390. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  391. if (Registry->OpenKey(DefaultIconKey, false))
  392. {
  393. UnicodeString Value = Registry->ReadString(L"");
  394. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  395. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  396. {
  397. Registry->DeleteValue(L"");
  398. }
  399. Registry->CloseKey();
  400. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  401. }
  402. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  403. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  404. {
  405. UnicodeString Value = Registry->ReadString(L"");
  406. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  407. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  408. {
  409. Registry->DeleteValue(L"");
  410. }
  411. Registry->CloseKey();
  412. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  413. }
  414. if (UnregisterProtocol)
  415. {
  416. ::UnregisterProtocol(Registry.get(), Protocol);
  417. }
  418. }
  419. //---------------------------------------------------------------------------
  420. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  421. {
  422. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  423. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  424. }
  425. //---------------------------------------------------------------------------
  426. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  427. {
  428. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  429. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  430. }
  431. //---------------------------------------------------------------------------
  432. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  433. {
  434. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  435. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  436. }
  437. //---------------------------------------------------------------------------
  438. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  439. //---------------------------------------------------------------------------
  440. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  441. {
  442. // Register protocol, if it does not exist yet.
  443. // Prior to Windows 8, we need to register ourselves as legacy handler to
  444. // become the default handler. On Windows 8, it's automatic as long as no other
  445. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  446. RegisterAsUrlHandler(RootKey, Protocol);
  447. // see http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#registration
  448. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  449. // create capabilities record
  450. // this has to be a separate branch from WinSCP one, as by its presence we
  451. // enforce registry storage usage, and the capabilities branch may exist
  452. // even if we are using INI file
  453. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  454. if (!Registry->OpenKey(CapabilitiesKey, true))
  455. {
  456. Abort();
  457. }
  458. UnicodeString Description = LoadStr(REGISTERED_APP_DESC);
  459. Registry->WriteString(L"ApplicationDescription", Description);
  460. if (!Registry->OpenKey(L"UrlAssociations", true))
  461. {
  462. Abort();
  463. }
  464. Registry->WriteString(Protocol, GenericUrlHandler);
  465. Registry->CloseKey();
  466. // register application
  467. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  468. {
  469. Abort();
  470. }
  471. Registry->WriteString(AppNameString(), CapabilitiesKey);
  472. Registry->CloseKey();
  473. }
  474. //---------------------------------------------------------------------------
  475. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  476. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  477. {
  478. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  479. // unregister the protocol
  480. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  481. // remove capabilities record
  482. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  483. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  484. if (Registry->OpenKey(UrlAssociationsKey, false))
  485. {
  486. Registry->DeleteValue(Protocol);
  487. Registry->CloseKey();
  488. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  489. }
  490. if (Registry->OpenKey(CapabilitiesKey, false))
  491. {
  492. if (!Registry->HasSubKeys())
  493. {
  494. Registry->DeleteValue(L"ApplicationDescription");
  495. }
  496. Registry->CloseKey();
  497. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  498. }
  499. if (!Registry->KeyExists(CapabilitiesKey))
  500. {
  501. // unregister application
  502. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  503. {
  504. Registry->DeleteValue(AppNameString());
  505. Registry->CloseKey();
  506. }
  507. }
  508. }
  509. //---------------------------------------------------------------------------
  510. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  511. {
  512. // register URL handler, if it does not exist yet
  513. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  514. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  515. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  516. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  517. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  518. // deliberately not including WebDAV/http,
  519. // it's unlikely that anyone would like to change http handler
  520. // to non-browser application
  521. }
  522. //---------------------------------------------------------------------------
  523. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  524. {
  525. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  526. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  527. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  528. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  529. // we should not really need the "force" flag here, but why not
  530. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  531. }
  532. //---------------------------------------------------------------------------
  533. static void __fastcall RegisterForDefaultPrograms()
  534. {
  535. try
  536. {
  537. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  538. // make sure we unregister any legacy protocol handler for CU,
  539. // this is needed for Windows Vista+7
  540. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  541. }
  542. catch (Exception & E)
  543. {
  544. try
  545. {
  546. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  547. }
  548. catch (Exception & E)
  549. {
  550. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  551. }
  552. }
  553. }
  554. //---------------------------------------------------------------------------
  555. static void __fastcall NotifyChangedAssociations()
  556. {
  557. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  558. }
  559. //---------------------------------------------------------------------------
  560. void __fastcall RegisterForDefaultProtocols()
  561. {
  562. if (IsWinVista())
  563. {
  564. RegisterForDefaultPrograms();
  565. }
  566. else
  567. {
  568. RegisterAsNonBrowserUrlHandler(UnicodeString());
  569. }
  570. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  571. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  572. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  573. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase());
  574. RegisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase());
  575. NotifyChangedAssociations();
  576. }
  577. //---------------------------------------------------------------------------
  578. void __fastcall UnregisterForProtocols()
  579. {
  580. UnregisterAsUrlHandlers(UnicodeString(), false);
  581. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  582. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  583. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  584. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVProtocol.UpperCase(), true);
  585. UnregisterAsUrlHandler(WinSCPProtocolPrefix + WebDAVSProtocol.UpperCase(), true);
  586. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  587. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  588. NotifyChangedAssociations();
  589. }
  590. //---------------------------------------------------------------------------
  591. void __fastcall LaunchAdvancedAssociationUI()
  592. {
  593. assert(IsWinVista());
  594. RegisterForDefaultPrograms();
  595. NotifyChangedAssociations();
  596. // sleep recommended by http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154.aspx#browser
  597. Sleep(1000);
  598. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  599. HRESULT Result =
  600. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  601. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  602. if (SUCCEEDED(Result))
  603. {
  604. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  605. AppAssocRegUI->Release();
  606. }
  607. }
  608. //---------------------------------------------------------------------------
  609. void __fastcall TemporaryDirectoryCleanup()
  610. {
  611. bool Continue = true;
  612. TStrings * Folders = NULL;
  613. try
  614. {
  615. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  616. {
  617. Folders = WinConfiguration->FindTemporaryFolders();
  618. Continue = (Folders != NULL);
  619. if (Continue)
  620. {
  621. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  622. TQueryButtonAlias Aliases[1];
  623. Aliases[0].Button = qaRetry;
  624. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  625. TMessageParams Params(mpNeverAskAgainCheck);
  626. Params.Aliases = Aliases;
  627. Params.AliasesCount = LENOF(Aliases);
  628. unsigned int Answer = MoreMessageDialog(
  629. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  630. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  631. if (Answer == qaNeverAskAgain)
  632. {
  633. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  634. Answer = qaYes;
  635. }
  636. else if (Answer == qaRetry)
  637. {
  638. for (int Index = 0; Index < Folders->Count; Index++)
  639. {
  640. ShellExecute(Application->Handle, NULL,
  641. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  642. }
  643. }
  644. Continue = (Answer == qaYes);
  645. }
  646. }
  647. if (Continue)
  648. {
  649. try
  650. {
  651. WinConfiguration->CleanupTemporaryFolders(Folders);
  652. }
  653. catch (Exception &E)
  654. {
  655. ShowExtendedException(&E);
  656. }
  657. }
  658. }
  659. __finally
  660. {
  661. delete Folders;
  662. }
  663. }
  664. //-------------------------------------------- -------------------------------
  665. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  666. {
  667. int MajorVer = Version / (10000*100*100);
  668. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  669. int Release = (Version % (10000*100)) / (10000);
  670. UnicodeString Result;
  671. if (Release > 0)
  672. {
  673. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  674. }
  675. else
  676. {
  677. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  678. }
  679. return Result;
  680. }
  681. //---------------------------------------------------------------------------
  682. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  683. {
  684. int CurrentCompoundVer = Configuration->CompoundVersion;
  685. AnsiString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  686. // Beware that these parameters may get truncated if URL is too long,
  687. // such as with ERROR_REPORT_URL2
  688. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  689. return AppendUrlParams(URL, Params);
  690. }
  691. //---------------------------------------------------------------------------
  692. UnicodeString __fastcall GetUsageData()
  693. {
  694. return Configuration->Usage->Serialize();
  695. }
  696. //---------------------------------------------------------------------------
  697. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  698. {
  699. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  700. UnicodeString CurrentVersionStr =
  701. FORMAT(L"%d.%d.%d.%d",
  702. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  703. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  704. UnicodeString Params =
  705. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  706. (CurrentVersionStr,
  707. IntToHex(__int64(GUIConfiguration->Locale), 4),
  708. int(IsInstalled())));
  709. if (Configuration->IsUnofficial)
  710. {
  711. Params += L"&unofficial=1";
  712. }
  713. return AppendUrlParams(URL, Params);
  714. }
  715. //---------------------------------------------------------------------------
  716. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  717. {
  718. bool Beta;
  719. if (WinConfiguration->IsBeta)
  720. {
  721. Beta = true;
  722. }
  723. else
  724. {
  725. switch (WinConfiguration->Updates.BetaVersions)
  726. {
  727. case asAuto:
  728. Beta = WinConfiguration->AnyBetaInVersionHistory;
  729. break;
  730. case asOn:
  731. Beta = true;
  732. break;
  733. default:
  734. Beta = false;
  735. break;
  736. }
  737. }
  738. if (Beta || Force)
  739. {
  740. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  741. }
  742. return URL;
  743. }
  744. //---------------------------------------------------------------------------
  745. void __fastcall QueryUpdates()
  746. {
  747. bool Complete = false;
  748. try
  749. {
  750. UnicodeString Response;
  751. int CurrentCompoundVer = Configuration->CompoundVersion;
  752. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  753. THttp * CheckForUpdatesHTTP = new THttp(Application);
  754. try
  755. {
  756. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  757. URL = WantBetaUrl(URL, false);
  758. URL += L"&dotnet=" + Updates.DotNetVersion;
  759. URL += L"&console=" + Updates.ConsoleVersion;
  760. UnicodeString Proxy;
  761. switch (Updates.ConnectionType)
  762. {
  763. case ctAuto:
  764. AutodetectProxyUrl(Proxy);
  765. if (!Proxy.IsEmpty())
  766. {
  767. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  768. }
  769. break;
  770. case ctProxy:
  771. Proxy = FORMAT(L"%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  772. Configuration->Usage->Inc(L"UpdateProxyManual");
  773. break;
  774. }
  775. CheckForUpdatesHTTP->Proxy = Proxy;
  776. CheckForUpdatesHTTP->URL = URL;
  777. if (Configuration->CollectUsage)
  778. {
  779. UTF8String UtfUsage = UTF8String(GetUsageData());
  780. CheckForUpdatesHTTP->Stream->Write(UtfUsage.c_str(), UtfUsage.Length());
  781. CheckForUpdatesHTTP->Post();
  782. }
  783. else
  784. {
  785. CheckForUpdatesHTTP->Action();
  786. }
  787. // sanity check
  788. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  789. {
  790. Abort();
  791. }
  792. UTF8String UtfResponse;
  793. UtfResponse.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  794. CheckForUpdatesHTTP->Stream->Read(UtfResponse.c_str(), UtfResponse.Length());
  795. Response = UnicodeString(UtfResponse);
  796. }
  797. __finally
  798. {
  799. delete CheckForUpdatesHTTP;
  800. }
  801. bool Changed = !Updates.HaveResults;
  802. Updates.LastCheck = Now();
  803. Updates.HaveResults = true;
  804. TUpdatesData PrevResults = Updates.Results;
  805. Updates.Results.Reset();
  806. Updates.Results.ForVersion = CurrentCompoundVer;
  807. while (!Response.IsEmpty())
  808. {
  809. UnicodeString Line = ::CutToChar(Response, L'\n', false);
  810. UnicodeString Name = ::CutToChar(Line, L'=', false);
  811. if (AnsiSameText(Name, "Version"))
  812. {
  813. int MajorVer = StrToInt(::CutToChar(Line, L'.', false));
  814. int MinorVer = StrToInt(::CutToChar(Line, L'.', false));
  815. int Release = StrToInt(::CutToChar(Line, L'.', false));
  816. int Build = StrToInt(::CutToChar(Line, L'.', false));
  817. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  818. Changed |= (NewVersion != PrevResults.Version);
  819. if (NewVersion <= CurrentCompoundVer)
  820. {
  821. NewVersion = 0;
  822. }
  823. Updates.Results.Version = NewVersion;
  824. Complete = true;
  825. }
  826. else if (AnsiSameText(Name, L"Message"))
  827. {
  828. Changed |= (PrevResults.Message != Line);
  829. Updates.Results.Message = Line;
  830. }
  831. else if (AnsiSameText(Name, L"Critical"))
  832. {
  833. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  834. Changed |= (PrevResults.Critical != NewCritical);
  835. Updates.Results.Critical = NewCritical;
  836. }
  837. else if (AnsiSameText(Name, L"Release"))
  838. {
  839. Changed |= (PrevResults.Release != Line);
  840. Updates.Results.Release = Line;
  841. }
  842. else if (AnsiSameText(Name, L"Disabled"))
  843. {
  844. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  845. Changed |= (PrevResults.Disabled != NewDisabled);
  846. Updates.Results.Disabled = NewDisabled;
  847. Complete = true;
  848. }
  849. else if (AnsiSameText(Name, L"Url"))
  850. {
  851. Changed |= (PrevResults.Url != Line);
  852. Updates.Results.Url = Line;
  853. }
  854. else if (AnsiSameText(Name, L"UrlButton"))
  855. {
  856. Changed |= (PrevResults.UrlButton != Line);
  857. Updates.Results.UrlButton = Line;
  858. }
  859. else if (AnsiSameText(Name, L"NewsUrl"))
  860. {
  861. Changed |= (PrevResults.NewsUrl != Line);
  862. Updates.Results.NewsUrl = Line;
  863. }
  864. else if (AnsiSameText(Name, L"NewsSize"))
  865. {
  866. TSize NewsSize;
  867. NewsSize.Width = StrToIntDef(::CutToChar(Line, L',', true), 0);
  868. NewsSize.Height = StrToIntDef(::CutToChar(Line, L',', true), 0);
  869. Changed |= (PrevResults.NewsSize != NewsSize);
  870. Updates.Results.NewsSize = NewsSize;
  871. }
  872. }
  873. if (Changed)
  874. {
  875. Updates.ShownResults = false;
  876. }
  877. WinConfiguration->Updates = Updates;
  878. if (!Complete)
  879. {
  880. EXCEPTION;
  881. }
  882. Configuration->Usage->Reset();
  883. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  884. }
  885. catch(Exception & E)
  886. {
  887. Configuration->Usage->Inc(L"UpdateChecksFailed");
  888. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  889. }
  890. }
  891. //---------------------------------------------------------------------------
  892. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  893. TQueryType & Type, bool Force)
  894. {
  895. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  896. assert(Updates.HaveResults);
  897. if (Updates.HaveResults)
  898. {
  899. if (Updates.Results.Disabled)
  900. {
  901. New = false;
  902. if (Force)
  903. {
  904. Message = LoadStr(UPDATE_DISABLED);
  905. }
  906. }
  907. else
  908. {
  909. New = (Updates.Results.Version > 0);
  910. if (New)
  911. {
  912. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  913. if (!Updates.Results.Release.IsEmpty())
  914. {
  915. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  916. }
  917. Message = FMTLOAD(NEW_VERSION4, (Version));
  918. }
  919. else
  920. {
  921. Message = LoadStr(NO_NEW_VERSION);
  922. }
  923. }
  924. if (!Message.IsEmpty())
  925. {
  926. Message = MainInstructions(Message);
  927. }
  928. if (!Updates.Results.Message.IsEmpty())
  929. {
  930. Message +=
  931. FMTLOAD(UPDATE_MESSAGE,
  932. (ReplaceStr(Updates.Results.Message, L"|", L"\n")));
  933. }
  934. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  935. }
  936. else
  937. {
  938. New = false;
  939. }
  940. }
  941. //---------------------------------------------------------------------------
  942. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  943. {
  944. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  945. OpenBrowser(LoadStr(HISTORY_URL));
  946. }
  947. //---------------------------------------------------------------------------
  948. bool __fastcall CheckForUpdates(bool CachedResults)
  949. {
  950. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  951. bool Result = false;
  952. TOperationVisualizer Visualizer;
  953. try
  954. {
  955. if (ActiveForm)
  956. {
  957. assert(ActiveForm->Enabled);
  958. ActiveForm->Enabled = false;
  959. }
  960. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  961. bool Cached =
  962. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  963. CachedResults;
  964. if (!Cached)
  965. {
  966. QueryUpdates();
  967. // reread new data
  968. Updates = WinConfiguration->Updates;
  969. }
  970. if (!Updates.ShownResults)
  971. {
  972. Updates.ShownResults = true;
  973. WinConfiguration->Updates = Updates;
  974. }
  975. assert(Updates.HaveResults);
  976. UnicodeString Message;
  977. bool New;
  978. TQueryType Type;
  979. GetUpdatesMessage(Message, New, Type, true);
  980. Configuration->Usage->Inc(L"UpdateDisplays");
  981. if (New)
  982. {
  983. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  984. }
  985. if (Updates.HaveResults &&
  986. (double(Updates.Period) > 0) &&
  987. // do not chow next check time, if we have new version info
  988. !New)
  989. {
  990. Message += L"\n\n" +
  991. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  992. }
  993. int Answers = qaOK |
  994. // show "what's new" button only when change list URL was not provided in results
  995. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  996. FLAGMASK(New, qaCancel) |
  997. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  998. TQueryButtonAlias Aliases[4];
  999. Aliases[0].Button = qaYes;
  1000. if (Updates.Results.UrlButton.IsEmpty())
  1001. {
  1002. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1003. }
  1004. else
  1005. {
  1006. Aliases[0].Alias = Updates.Results.UrlButton;
  1007. }
  1008. Aliases[1].Button = qaAll;
  1009. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1010. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  1011. Aliases[2].Button = qaCancel;
  1012. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1013. Aliases[3].Button = qaOK;
  1014. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1015. TMessageParams Params;
  1016. Params.Aliases = Aliases;
  1017. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1018. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1019. // alias "ok" button to "download" only if we have new version
  1020. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1021. unsigned int Answer =
  1022. MessageDialog(Message, Type,
  1023. Answers, HELP_UPDATES, &Params);
  1024. switch (Answer)
  1025. {
  1026. case qaOK:
  1027. if (New)
  1028. {
  1029. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1030. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1031. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1032. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1033. OpenBrowser(UpgradeUrl);
  1034. Result = true;
  1035. }
  1036. break;
  1037. case qaYes:
  1038. OpenBrowser(Updates.Results.Url);
  1039. break;
  1040. case qaAll:
  1041. FAIL;
  1042. break;
  1043. }
  1044. }
  1045. __finally
  1046. {
  1047. if (ActiveForm)
  1048. {
  1049. ActiveForm->Enabled = true;
  1050. }
  1051. }
  1052. return Result;
  1053. }
  1054. //---------------------------------------------------------------------------
  1055. class TUpdateThread : public TCompThread
  1056. {
  1057. public:
  1058. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1059. protected:
  1060. virtual void __fastcall Execute();
  1061. TThreadMethod FOnUpdatesChecked;
  1062. };
  1063. //---------------------------------------------------------------------------
  1064. TUpdateThread * UpdateThread = NULL;
  1065. //---------------------------------------------------------------------------
  1066. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1067. TCompThread(false),
  1068. FOnUpdatesChecked(OnUpdatesChecked)
  1069. {
  1070. }
  1071. //---------------------------------------------------------------------------
  1072. void __fastcall TUpdateThread::Execute()
  1073. {
  1074. try
  1075. {
  1076. QueryUpdates();
  1077. if (FOnUpdatesChecked != NULL)
  1078. {
  1079. Synchronize(FOnUpdatesChecked);
  1080. }
  1081. }
  1082. catch(...)
  1083. {
  1084. // ignore errors
  1085. }
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1089. {
  1090. assert(UpdateThread == NULL);
  1091. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1092. }
  1093. //---------------------------------------------------------------------------
  1094. void __fastcall StopUpdateThread()
  1095. {
  1096. if (UpdateThread != NULL)
  1097. {
  1098. SAFE_DESTROY(UpdateThread);
  1099. }
  1100. }
  1101. //---------------------------------------------------------------------------
  1102. void __fastcall SetupInitialize()
  1103. {
  1104. WinConfiguration->UpdateJumpList();
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1108. UnicodeString AdditionalParams, TStringList * Removed,
  1109. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1110. int IconIndex)
  1111. {
  1112. bool Result = false;
  1113. IObjectCollection * Collection = NULL;
  1114. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1115. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1116. {
  1117. try
  1118. {
  1119. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1120. int Count = 0;
  1121. for (int Index = 0; Index < Names->Count; Index++)
  1122. {
  1123. IShellLink * Link =
  1124. CreateDesktopSessionShortCut(
  1125. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1126. wchar_t Desc[2048];
  1127. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1128. {
  1129. if (Removed->IndexOf(Desc) < 0)
  1130. {
  1131. try
  1132. {
  1133. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1134. Count++;
  1135. }
  1136. __finally
  1137. {
  1138. Link->Release();
  1139. }
  1140. }
  1141. else
  1142. {
  1143. Names->Delete(Index);
  1144. Index--;
  1145. }
  1146. }
  1147. }
  1148. if (Count > 0)
  1149. {
  1150. IObjectArray * Array;
  1151. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1152. {
  1153. try
  1154. {
  1155. Result = SUCCEEDED(
  1156. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1157. }
  1158. __finally
  1159. {
  1160. Array->Release();
  1161. }
  1162. }
  1163. }
  1164. }
  1165. __finally
  1166. {
  1167. Collection->Release();
  1168. }
  1169. }
  1170. return Result;
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1174. {
  1175. ICustomDestinationList * DestinationList = NULL;
  1176. IObjectArray * RemovedArray = NULL;
  1177. TStringList * Removed = NULL;
  1178. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1179. try
  1180. {
  1181. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1182. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1183. {
  1184. unsigned int MinSlots;
  1185. unsigned int * PMinSlots = &MinSlots;
  1186. void ** PRemovedArray = (void**)&RemovedArray;
  1187. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1188. if (SUCCEEDED(Result) && ALWAYS_TRUE(RemovedArray != NULL))
  1189. {
  1190. Removed = new TStringList();
  1191. unsigned int RemovedCount;
  1192. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1193. {
  1194. RemovedCount = 0;
  1195. }
  1196. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1197. {
  1198. IShellLink * Link;
  1199. wchar_t Desc[2048];
  1200. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1201. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1202. {
  1203. Removed->Add(Desc);
  1204. }
  1205. }
  1206. AddJumpListCategory(
  1207. WorkspaceNames, L"", Removed, DestinationList,
  1208. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1209. AddJumpListCategory(
  1210. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1211. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1212. if (DestinationList != NULL)
  1213. {
  1214. DestinationList->CommitList();
  1215. }
  1216. }
  1217. }
  1218. }
  1219. __finally
  1220. {
  1221. SetErrorMode(OldErrMode);
  1222. if (RemovedArray != NULL)
  1223. {
  1224. RemovedArray->Release();
  1225. }
  1226. if (DestinationList != NULL)
  1227. {
  1228. DestinationList->Release();
  1229. }
  1230. delete Removed;
  1231. }
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. bool __fastcall AnyOtherInstanceOfSelf()
  1235. {
  1236. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1237. bool Result = false;
  1238. try
  1239. {
  1240. unsigned int Process = GetCurrentProcessId();
  1241. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1242. PROCESSENTRY32 ProcessEntry;
  1243. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1244. if (Process32First(Snapshot, &ProcessEntry))
  1245. {
  1246. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1247. {
  1248. // we should check if the process is running in the same session,
  1249. // but for that we probably need some special privileges
  1250. if ((Process != ProcessEntry.th32ProcessID) &&
  1251. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1252. {
  1253. Result = true;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. __finally
  1259. {
  1260. CloseHandle(Snapshot);
  1261. }
  1262. return Result;
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1266. {
  1267. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1268. Registry->RootKey = RootKey;
  1269. bool Result =
  1270. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1271. if (Result)
  1272. {
  1273. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1274. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1275. Result =
  1276. !InstallPath.IsEmpty() &&
  1277. CompareFileName(ExePath, InstallPath);
  1278. }
  1279. return Result;
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. bool __fastcall IsInstalled()
  1283. {
  1284. return
  1285. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1286. DoIsInstalled(HKEY_CURRENT_USER);
  1287. }