Setup.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  687. return AppendUrlParams(URL, Params);
  688. }
  689. //---------------------------------------------------------------------------
  690. UnicodeString __fastcall GetUsageData()
  691. {
  692. return Configuration->Usage->Serialize();
  693. }
  694. //---------------------------------------------------------------------------
  695. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  696. {
  697. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  698. UnicodeString CurrentVersionStr =
  699. FORMAT(L"%d.%d.%d.%d",
  700. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  701. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  702. UnicodeString Params =
  703. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  704. (CurrentVersionStr,
  705. IntToHex(__int64(GUIConfiguration->Locale), 4),
  706. int(IsInstalled())));
  707. if (Configuration->IsUnofficial)
  708. {
  709. Params += L"&unofficial=1";
  710. }
  711. return AppendUrlParams(URL, Params);
  712. }
  713. //---------------------------------------------------------------------------
  714. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  715. {
  716. bool Beta;
  717. if (WinConfiguration->IsBeta)
  718. {
  719. Beta = true;
  720. }
  721. else
  722. {
  723. switch (WinConfiguration->Updates.BetaVersions)
  724. {
  725. case asAuto:
  726. Beta = WinConfiguration->AnyBetaInVersionHistory;
  727. break;
  728. case asOn:
  729. Beta = true;
  730. break;
  731. default:
  732. Beta = false;
  733. break;
  734. }
  735. }
  736. if (Beta || Force)
  737. {
  738. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  739. }
  740. return URL;
  741. }
  742. //---------------------------------------------------------------------------
  743. void __fastcall QueryUpdates()
  744. {
  745. bool Complete = false;
  746. try
  747. {
  748. UnicodeString Response;
  749. int CurrentCompoundVer = Configuration->CompoundVersion;
  750. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  751. THttp * CheckForUpdatesHTTP = new THttp(Application);
  752. try
  753. {
  754. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  755. URL = WantBetaUrl(URL, false);
  756. URL += L"&dotnet=" + Updates.DotNetVersion;
  757. URL += L"&console=" + Updates.ConsoleVersion;
  758. UnicodeString Proxy;
  759. switch (Updates.ConnectionType)
  760. {
  761. case ctAuto:
  762. AutodetectProxyUrl(Proxy);
  763. if (!Proxy.IsEmpty())
  764. {
  765. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  766. }
  767. break;
  768. case ctProxy:
  769. Proxy = FORMAT(L"%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  770. Configuration->Usage->Inc(L"UpdateProxyManual");
  771. break;
  772. }
  773. CheckForUpdatesHTTP->Proxy = Proxy;
  774. CheckForUpdatesHTTP->URL = URL;
  775. if (Configuration->CollectUsage)
  776. {
  777. UTF8String UtfUsage = UTF8String(GetUsageData());
  778. CheckForUpdatesHTTP->Stream->Write(UtfUsage.c_str(), UtfUsage.Length());
  779. CheckForUpdatesHTTP->Post();
  780. }
  781. else
  782. {
  783. CheckForUpdatesHTTP->Action();
  784. }
  785. // sanity check
  786. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  787. {
  788. Abort();
  789. }
  790. UTF8String UtfResponse;
  791. UtfResponse.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  792. CheckForUpdatesHTTP->Stream->Read(UtfResponse.c_str(), UtfResponse.Length());
  793. Response = UnicodeString(UtfResponse);
  794. }
  795. __finally
  796. {
  797. delete CheckForUpdatesHTTP;
  798. }
  799. bool Changed = !Updates.HaveResults;
  800. Updates.LastCheck = Now();
  801. Updates.HaveResults = true;
  802. TUpdatesData PrevResults = Updates.Results;
  803. Updates.Results.Reset();
  804. Updates.Results.ForVersion = CurrentCompoundVer;
  805. while (!Response.IsEmpty())
  806. {
  807. UnicodeString Line = ::CutToChar(Response, L'\n', false);
  808. UnicodeString Name = ::CutToChar(Line, L'=', false);
  809. if (AnsiSameText(Name, "Version"))
  810. {
  811. int MajorVer = StrToInt(::CutToChar(Line, L'.', false));
  812. int MinorVer = StrToInt(::CutToChar(Line, L'.', false));
  813. int Release = StrToInt(::CutToChar(Line, L'.', false));
  814. int Build = StrToInt(::CutToChar(Line, L'.', false));
  815. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  816. Changed |= (NewVersion != PrevResults.Version);
  817. if (NewVersion <= CurrentCompoundVer)
  818. {
  819. NewVersion = 0;
  820. }
  821. Updates.Results.Version = NewVersion;
  822. Complete = true;
  823. }
  824. else if (AnsiSameText(Name, L"Message"))
  825. {
  826. Changed |= (PrevResults.Message != Line);
  827. Updates.Results.Message = Line;
  828. }
  829. else if (AnsiSameText(Name, L"Critical"))
  830. {
  831. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  832. Changed |= (PrevResults.Critical != NewCritical);
  833. Updates.Results.Critical = NewCritical;
  834. }
  835. else if (AnsiSameText(Name, L"Release"))
  836. {
  837. Changed |= (PrevResults.Release != Line);
  838. Updates.Results.Release = Line;
  839. }
  840. else if (AnsiSameText(Name, L"Disabled"))
  841. {
  842. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  843. Changed |= (PrevResults.Disabled != NewDisabled);
  844. Updates.Results.Disabled = NewDisabled;
  845. Complete = true;
  846. }
  847. else if (AnsiSameText(Name, L"Url"))
  848. {
  849. Changed |= (PrevResults.Url != Line);
  850. Updates.Results.Url = Line;
  851. }
  852. else if (AnsiSameText(Name, L"UrlButton"))
  853. {
  854. Changed |= (PrevResults.UrlButton != Line);
  855. Updates.Results.UrlButton = Line;
  856. }
  857. else if (AnsiSameText(Name, L"NewsUrl"))
  858. {
  859. Changed |= (PrevResults.NewsUrl != Line);
  860. Updates.Results.NewsUrl = Line;
  861. }
  862. else if (AnsiSameText(Name, L"NewsSize"))
  863. {
  864. TSize NewsSize;
  865. NewsSize.Width = StrToIntDef(::CutToChar(Line, L',', true), 0);
  866. NewsSize.Height = StrToIntDef(::CutToChar(Line, L',', true), 0);
  867. Changed |= (PrevResults.NewsSize != NewsSize);
  868. Updates.Results.NewsSize = NewsSize;
  869. }
  870. }
  871. if (Changed)
  872. {
  873. Updates.ShownResults = false;
  874. }
  875. WinConfiguration->Updates = Updates;
  876. if (!Complete)
  877. {
  878. EXCEPTION;
  879. }
  880. Configuration->Usage->Reset();
  881. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  882. }
  883. catch(Exception & E)
  884. {
  885. Configuration->Usage->Inc(L"UpdateChecksFailed");
  886. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  887. }
  888. }
  889. //---------------------------------------------------------------------------
  890. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  891. TQueryType & Type, bool Force)
  892. {
  893. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  894. assert(Updates.HaveResults);
  895. if (Updates.HaveResults)
  896. {
  897. if (Updates.Results.Disabled)
  898. {
  899. New = false;
  900. if (Force)
  901. {
  902. Message = LoadStr(UPDATE_DISABLED);
  903. }
  904. }
  905. else
  906. {
  907. New = (Updates.Results.Version > 0);
  908. if (New)
  909. {
  910. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  911. if (!Updates.Results.Release.IsEmpty())
  912. {
  913. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  914. }
  915. Message = FMTLOAD(NEW_VERSION4, (Version));
  916. }
  917. else
  918. {
  919. Message = LoadStr(NO_NEW_VERSION);
  920. }
  921. }
  922. if (!Message.IsEmpty())
  923. {
  924. Message = MainInstructions(Message);
  925. }
  926. if (!Updates.Results.Message.IsEmpty())
  927. {
  928. Message +=
  929. FMTLOAD(UPDATE_MESSAGE,
  930. (ReplaceStr(Updates.Results.Message, L"|", L"\n")));
  931. }
  932. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  933. }
  934. else
  935. {
  936. New = false;
  937. }
  938. }
  939. //---------------------------------------------------------------------------
  940. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/)
  941. {
  942. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  943. OpenBrowser(LoadStr(HISTORY_URL));
  944. }
  945. //---------------------------------------------------------------------------
  946. bool __fastcall CheckForUpdates(bool CachedResults)
  947. {
  948. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  949. bool Result = false;
  950. TOperationVisualizer Visualizer;
  951. try
  952. {
  953. if (ActiveForm)
  954. {
  955. assert(ActiveForm->Enabled);
  956. ActiveForm->Enabled = false;
  957. }
  958. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  959. bool Cached =
  960. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  961. CachedResults;
  962. if (!Cached)
  963. {
  964. QueryUpdates();
  965. // reread new data
  966. Updates = WinConfiguration->Updates;
  967. }
  968. if (!Updates.ShownResults)
  969. {
  970. Updates.ShownResults = true;
  971. WinConfiguration->Updates = Updates;
  972. }
  973. assert(Updates.HaveResults);
  974. UnicodeString Message;
  975. bool New;
  976. TQueryType Type;
  977. GetUpdatesMessage(Message, New, Type, true);
  978. Configuration->Usage->Inc(L"UpdateDisplays");
  979. if (New)
  980. {
  981. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  982. }
  983. if (Updates.HaveResults &&
  984. (double(Updates.Period) > 0) &&
  985. // do not chow next check time, if we have new version info
  986. !New)
  987. {
  988. Message += L"\n\n" +
  989. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  990. }
  991. int Answers = qaOK |
  992. // show "what's new" button only when change list URL was not provided in results
  993. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  994. FLAGMASK(New, qaCancel) |
  995. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  996. TQueryButtonAlias Aliases[4];
  997. Aliases[0].Button = qaYes;
  998. if (Updates.Results.UrlButton.IsEmpty())
  999. {
  1000. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1001. }
  1002. else
  1003. {
  1004. Aliases[0].Alias = Updates.Results.UrlButton;
  1005. }
  1006. Aliases[1].Button = qaAll;
  1007. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1008. Aliases[1].OnClick = MakeMethod<TNotifyEvent>(NULL, OpenHistory);
  1009. Aliases[2].Button = qaCancel;
  1010. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1011. Aliases[3].Button = qaOK;
  1012. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1013. TMessageParams Params;
  1014. Params.Aliases = Aliases;
  1015. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1016. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1017. // alias "ok" button to "download" only if we have new version
  1018. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1019. unsigned int Answer =
  1020. MessageDialog(Message, Type,
  1021. Answers, HELP_UPDATES, &Params);
  1022. switch (Answer)
  1023. {
  1024. case qaOK:
  1025. if (New)
  1026. {
  1027. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1028. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1029. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1030. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1031. OpenBrowser(UpgradeUrl);
  1032. Result = true;
  1033. }
  1034. break;
  1035. case qaYes:
  1036. OpenBrowser(Updates.Results.Url);
  1037. break;
  1038. case qaAll:
  1039. FAIL;
  1040. break;
  1041. }
  1042. }
  1043. __finally
  1044. {
  1045. if (ActiveForm)
  1046. {
  1047. ActiveForm->Enabled = true;
  1048. }
  1049. }
  1050. return Result;
  1051. }
  1052. //---------------------------------------------------------------------------
  1053. class TUpdateThread : public TCompThread
  1054. {
  1055. public:
  1056. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1057. protected:
  1058. virtual void __fastcall Execute();
  1059. TThreadMethod FOnUpdatesChecked;
  1060. };
  1061. //---------------------------------------------------------------------------
  1062. TUpdateThread * UpdateThread = NULL;
  1063. //---------------------------------------------------------------------------
  1064. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1065. TCompThread(false),
  1066. FOnUpdatesChecked(OnUpdatesChecked)
  1067. {
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TUpdateThread::Execute()
  1071. {
  1072. try
  1073. {
  1074. QueryUpdates();
  1075. if (FOnUpdatesChecked != NULL)
  1076. {
  1077. Synchronize(FOnUpdatesChecked);
  1078. }
  1079. }
  1080. catch(...)
  1081. {
  1082. // ignore errors
  1083. }
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1087. {
  1088. assert(UpdateThread == NULL);
  1089. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1090. }
  1091. //---------------------------------------------------------------------------
  1092. void __fastcall StopUpdateThread()
  1093. {
  1094. if (UpdateThread != NULL)
  1095. {
  1096. SAFE_DESTROY(UpdateThread);
  1097. }
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall SetupInitialize()
  1101. {
  1102. WinConfiguration->UpdateJumpList();
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1106. UnicodeString AdditionalParams, TStringList * Removed,
  1107. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1108. int IconIndex)
  1109. {
  1110. bool Result = false;
  1111. IObjectCollection * Collection = NULL;
  1112. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1113. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1114. {
  1115. try
  1116. {
  1117. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1118. int Count = 0;
  1119. for (int Index = 0; Index < Names->Count; Index++)
  1120. {
  1121. IShellLink * Link =
  1122. CreateDesktopSessionShortCut(
  1123. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1124. wchar_t Desc[2048];
  1125. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1126. {
  1127. if (Removed->IndexOf(Desc) < 0)
  1128. {
  1129. try
  1130. {
  1131. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1132. Count++;
  1133. }
  1134. __finally
  1135. {
  1136. Link->Release();
  1137. }
  1138. }
  1139. else
  1140. {
  1141. Names->Delete(Index);
  1142. Index--;
  1143. }
  1144. }
  1145. }
  1146. if (Count > 0)
  1147. {
  1148. IObjectArray * Array;
  1149. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1150. {
  1151. try
  1152. {
  1153. Result = SUCCEEDED(
  1154. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1155. }
  1156. __finally
  1157. {
  1158. Array->Release();
  1159. }
  1160. }
  1161. }
  1162. }
  1163. __finally
  1164. {
  1165. Collection->Release();
  1166. }
  1167. }
  1168. return Result;
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1172. {
  1173. ICustomDestinationList * DestinationList = NULL;
  1174. IObjectArray * RemovedArray = NULL;
  1175. TStringList * Removed = NULL;
  1176. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1177. try
  1178. {
  1179. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1180. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1181. {
  1182. unsigned int MinSlots;
  1183. unsigned int * PMinSlots = &MinSlots;
  1184. void ** PRemovedArray = (void**)&RemovedArray;
  1185. HRESULT Result = DestinationList->BeginList(PMinSlots, IID_IObjectArray, PRemovedArray);
  1186. if (SUCCEEDED(Result) && ALWAYS_TRUE(RemovedArray != NULL))
  1187. {
  1188. Removed = new TStringList();
  1189. unsigned int RemovedCount;
  1190. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1191. {
  1192. RemovedCount = 0;
  1193. }
  1194. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1195. {
  1196. IShellLink * Link;
  1197. wchar_t Desc[2048];
  1198. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1199. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1200. {
  1201. Removed->Add(Desc);
  1202. }
  1203. }
  1204. AddJumpListCategory(
  1205. WorkspaceNames, L"", Removed, DestinationList,
  1206. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1207. AddJumpListCategory(
  1208. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1209. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1210. if (DestinationList != NULL)
  1211. {
  1212. DestinationList->CommitList();
  1213. }
  1214. }
  1215. }
  1216. }
  1217. __finally
  1218. {
  1219. SetErrorMode(OldErrMode);
  1220. if (RemovedArray != NULL)
  1221. {
  1222. RemovedArray->Release();
  1223. }
  1224. if (DestinationList != NULL)
  1225. {
  1226. DestinationList->Release();
  1227. }
  1228. delete Removed;
  1229. }
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. bool __fastcall AnyOtherInstanceOfSelf()
  1233. {
  1234. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1235. bool Result = false;
  1236. try
  1237. {
  1238. unsigned int Process = GetCurrentProcessId();
  1239. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1240. PROCESSENTRY32 ProcessEntry;
  1241. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1242. if (Process32First(Snapshot, &ProcessEntry))
  1243. {
  1244. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1245. {
  1246. // we should check if the process is running in the same session,
  1247. // but for that we probably need some special privileges
  1248. if ((Process != ProcessEntry.th32ProcessID) &&
  1249. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1250. {
  1251. Result = true;
  1252. }
  1253. }
  1254. }
  1255. }
  1256. __finally
  1257. {
  1258. CloseHandle(Snapshot);
  1259. }
  1260. return Result;
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1264. {
  1265. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1266. Registry->RootKey = RootKey;
  1267. bool Result =
  1268. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1269. if (Result)
  1270. {
  1271. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1272. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1273. Result =
  1274. !InstallPath.IsEmpty() &&
  1275. CompareFileName(ExePath, InstallPath);
  1276. }
  1277. return Result;
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. bool __fastcall IsInstalled()
  1281. {
  1282. return
  1283. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1284. DoIsInstalled(HKEY_CURRENT_USER);
  1285. }