Setup.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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 <Common.h>
  11. #include <CoreMain.h>
  12. #include <Exceptions.h>
  13. #include <TextsWin.h>
  14. #include <HelpWin.h>
  15. #include <TcpIp.hpp>
  16. #include <CompThread.hpp>
  17. #include <FileInfo.h>
  18. #include "WinConfiguration.h"
  19. #include "WinInterface.h"
  20. #include "Tools.h"
  21. #include "Setup.h"
  22. //---------------------------------------------------------------------------
  23. /* Using quotes or not should make no difference but some programs (for
  24. instance cygwin and msys) don't like them. */
  25. /* #define USE_QUOTES */
  26. //---------------------------------------------------------------------------
  27. #define APP_NAME "WinSCP"
  28. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  29. _T("Session Manager\\Environment")
  30. #define AUTOEXEC_PATH _T("c:\\autoexec.bat")
  31. #define AUTOEXEC_INTRO _T("rem ***** The following line was added by " \
  32. APP_NAME " *****")
  33. #ifdef USE_QUOTES
  34. # define AUTOEXEC_CMD _T("set PATH=%%PATH%%;\"%s\"")
  35. #else
  36. # define AUTOEXEC_CMD _T("set PATH=%%PATH%%;%s")
  37. #endif
  38. /* Command line options. */
  39. UnicodeString LastPathError;
  40. //---------------------------------------------------------------------------
  41. #define verb_out(msg) ((void)0)
  42. #define verb_out_param(msg, param) ((void)0)
  43. //---------------------------------------------------------------------------
  44. // Display the error "err_msg".
  45. void err_out(LPCTSTR err_msg)
  46. {
  47. LastPathError = err_msg;
  48. }
  49. //---------------------------------------------------------------------------
  50. // Display "base_err_msg" followed by the description of the system error
  51. // identified by "sys_err".
  52. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  53. {
  54. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  55. }
  56. //---------------------------------------------------------------------------
  57. // Works as "strcmp" but the comparison is not case sensitive.
  58. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  59. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  60. if (*str1 == L'\0')
  61. return 0;
  62. return tolower(*str1) - tolower(*str2);
  63. }
  64. //---------------------------------------------------------------------------
  65. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  66. // not present). The returned value must be freed with "free".
  67. LPTSTR unquote(LPCTSTR str){
  68. int last_pos;
  69. LPTSTR ret;
  70. size_t new_len;
  71. last_pos = _tcslen(str) - 1;
  72. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  73. new_len= (_tcslen(str) - 1);
  74. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  75. lstrcpyn(ret, &str[1], new_len);
  76. }
  77. else
  78. ret = _tcsdup(str);
  79. return ret;
  80. }
  81. //---------------------------------------------------------------------------
  82. // Find "what" in the ";" separated string "str" and returns a pointer to
  83. // the first letter of "what" in the string. If "next" is not "NULL" it
  84. // points to the first letter after "what" (excluding the trailing ";").
  85. // If "what" isn't find the functions returns "NULL".
  86. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  87. LPTSTR tok_buff;
  88. LPTSTR curr_tok;
  89. LPTSTR curr_tok_dup;
  90. BOOL path_eq;
  91. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  92. int pos = -1;
  93. LPTSTR ret;
  94. tok_buff = _tcsdup(str);
  95. curr_tok = _tcstok(tok_buff, _T(";"));
  96. while (pos == -1 && curr_tok){
  97. curr_tok_dup = unquote(curr_tok);
  98. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  99. GetShortPathName(curr_tok_dup, sh_path2,
  100. LENOF(sh_path2)) &&
  101. (tcharicmp(sh_path1, sh_path2) == 0);
  102. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  103. pos = curr_tok - tok_buff;
  104. }
  105. free(curr_tok_dup);
  106. curr_tok = _tcstok(NULL, _T(";"));
  107. if (pos != -1 && next){
  108. if (curr_tok)
  109. *next = str + (curr_tok - tok_buff);
  110. else
  111. *next = str + _tcslen(str);
  112. }
  113. }
  114. free(tok_buff);
  115. if (pos != -1)
  116. ret = str + pos;
  117. else
  118. ret = NULL;
  119. return ret;
  120. }
  121. //---------------------------------------------------------------------------
  122. void path_reg_propagate()
  123. {
  124. DWORD send_message_result;
  125. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  126. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  127. 5000, &send_message_result);
  128. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  129. {
  130. err_out_sys(_T("Cannot propagate the new enviroment to ")
  131. _T("other processes. The new value will be ")
  132. _T("avaible after a reboot."), GetLastError());
  133. SimpleErrorDialog(LastPathError);
  134. LastPathError = L"";
  135. }
  136. }
  137. //---------------------------------------------------------------------------
  138. // Add "path" to the registry. Return "TRUE" if the path has been added or
  139. // was already in the registry, "FALSE" otherwise.
  140. BOOL add_path_reg(LPCTSTR path){
  141. HKEY key;
  142. LONG ret;
  143. DWORD data_size;
  144. LPTSTR reg_str;
  145. BOOL func_ret = TRUE;
  146. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  147. KEY_WRITE | KEY_READ, &key);
  148. if (ret != ERROR_SUCCESS){
  149. err_out_sys(_T("Cannot open registry."), ret);
  150. return FALSE;
  151. }
  152. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  153. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  154. includes '\0'. */
  155. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  156. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  157. &data_size);
  158. if (ret != ERROR_SUCCESS){
  159. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  160. func_ret = FALSE;
  161. }
  162. else{
  163. if (!find_reg_str(reg_str, path, NULL)){
  164. _tcscat(reg_str, _T(";"));
  165. #ifdef USE_QUOTES
  166. _tcscat(reg_str, _T(";\""));
  167. #endif
  168. _tcscat(reg_str, path);
  169. #ifdef USE_QUOTES
  170. _tcscat(reg_str, _T("\""));
  171. #endif
  172. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  173. (LPBYTE)reg_str,
  174. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  175. if (ret != ERROR_SUCCESS){
  176. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  177. func_ret = FALSE;
  178. }
  179. /* Is this needed to make the new key avaible? */
  180. RegFlushKey(key);
  181. SetLastError(0);
  182. path_reg_propagate();
  183. }
  184. else
  185. verb_out(_T("Value already exists in the registry."));
  186. }
  187. RegCloseKey(key);
  188. free(reg_str);
  189. return func_ret;
  190. }
  191. //---------------------------------------------------------------------------
  192. // Removes "path" from the registry. Return "TRUE" if the path has been
  193. // removed or it wasn't in the registry, "FALSE" otherwise.
  194. BOOL remove_path_reg(LPCTSTR path){
  195. HKEY key;
  196. LONG ret;
  197. DWORD data_size;
  198. LPTSTR reg_str;
  199. LPTSTR reg_str2;
  200. BOOL func_ret = TRUE;
  201. LPTSTR next;
  202. LPTSTR del_part;
  203. int last_pos;
  204. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  205. KEY_WRITE | KEY_READ, &key);
  206. if (ret != ERROR_SUCCESS){
  207. err_out_sys(_T("Cannot open registry."), ret);
  208. return FALSE;
  209. }
  210. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  211. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  212. includes '\0'. */
  213. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  214. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  215. (LPBYTE)reg_str, &data_size);
  216. if (ret != ERROR_SUCCESS){
  217. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  218. func_ret = FALSE;
  219. }
  220. else{
  221. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  222. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  223. *del_part = '\0';
  224. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  225. last_pos = _tcslen(reg_str2) - 1;
  226. if (last_pos != -1 && reg_str2[last_pos] == ';')
  227. reg_str2[last_pos] = '\0';
  228. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  229. (LPBYTE)reg_str2,
  230. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  231. if (ret != ERROR_SUCCESS){
  232. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  233. func_ret = FALSE;
  234. }
  235. free(reg_str2);
  236. /* Is this needed to make the new key avaible? */
  237. RegFlushKey(key);
  238. SetLastError(0);
  239. path_reg_propagate();
  240. }
  241. else
  242. verb_out(_T("Value does not exist in the registry."));
  243. }
  244. RegCloseKey(key);
  245. free(reg_str);
  246. return func_ret;
  247. }
  248. //---------------------------------------------------------------------------
  249. /* Can this program run under Win9x if compiled with unicode support? */
  250. //---------------------------------------------------------------------------
  251. // Add "path" to "autoexec.bat". Return "TRUE" if the path has been added or
  252. // was already in the file, "FALSE" otherwise.
  253. BOOL add_path_autoexec(LPCTSTR long_path){
  254. FILE * file;
  255. LPTSTR path;
  256. size_t path_size;
  257. LPTSTR line;
  258. LPTSTR out_line;
  259. size_t line_size;
  260. size_t sz1, sz2;
  261. LPTSTR autoexec_intro;
  262. BOOL found;
  263. BOOL func_ret = TRUE;
  264. file = _wfopen(AUTOEXEC_PATH, _T("r+"));
  265. if (!file){
  266. err_out(_T("Cannot open \"autoexec.bat\"."));
  267. return FALSE;
  268. }
  269. path_size = _tcslen(long_path) + 1;
  270. path = (LPTSTR)malloc(path_size * sizeof(TCHAR));
  271. if (!GetShortPathName(long_path, path, path_size))
  272. _tcsncpy(path, long_path, path_size);
  273. sz1 = _tcslen(path) + _tcslen(AUTOEXEC_CMD);
  274. sz2 = _tcslen(AUTOEXEC_INTRO) + 2 /* '\n' and '\0'. */;
  275. line_size = sz1 > sz2 ? sz1 : sz2;
  276. line = (LPTSTR)malloc(line_size * sizeof(TCHAR));
  277. out_line = (LPTSTR)malloc(line_size * sizeof(TCHAR));
  278. _stprintf(out_line, AUTOEXEC_CMD, path);
  279. _tcscat(out_line, _T("\n"));
  280. autoexec_intro = (LPTSTR)malloc((_tcslen(AUTOEXEC_INTRO) + 2 /* '\0', '\n' */)
  281. * sizeof(TCHAR));
  282. _tcscpy(autoexec_intro, AUTOEXEC_INTRO);
  283. _tcscat(autoexec_intro, _T("\n"));
  284. found = FALSE;
  285. while (!found && _fgetts(line, line_size, file)){
  286. if (_tcscmp(autoexec_intro, line) == 0){
  287. _fgetts(line, line_size, file);
  288. if (_tcscmp(out_line, line) == 0)
  289. found = TRUE;
  290. }
  291. }
  292. if (!found){
  293. if (fseek(file, 0, SEEK_END) != 0 ||
  294. _fputts(_T("\n"), file) == _TEOF ||
  295. _fputts(autoexec_intro, file) == _TEOF ||
  296. _fputts(out_line, file) == _TEOF)
  297. func_ret = FALSE;
  298. }
  299. else
  300. verb_out(_T("Value already exists in \"autoexec.bat\"."));
  301. fclose(file);
  302. free(path);
  303. free(line);
  304. free(out_line);
  305. free(autoexec_intro);
  306. return func_ret;
  307. }
  308. //---------------------------------------------------------------------------
  309. // Removes "path" from "autoexec.bat". Return "TRUE" if the path has been
  310. // removed or it wasn't in the file, "FALSE" otherwise.
  311. BOOL remove_path_autoexec(LPTSTR long_path){
  312. FILE * file;
  313. LPTSTR path;
  314. size_t path_size;
  315. LPTSTR data;
  316. long file_size;
  317. LPTSTR expected_text;
  318. size_t expected_text_size;
  319. LPTSTR buff;
  320. size_t buff_size;
  321. LPTSTR begin_pos;
  322. LPTSTR final_part;
  323. size_t fread_ret;
  324. BOOL func_ret = TRUE;
  325. file = _wfopen(AUTOEXEC_PATH, _T("rb"));
  326. if (!file){
  327. err_out(_T("Cannot open \"autoexec.bat\" for reading."));
  328. return FALSE;
  329. }
  330. fseek(file, 0, SEEK_END);
  331. file_size = ftell(file);
  332. data = (LPTSTR)malloc(file_size + sizeof(TCHAR) /* '\0'. */);
  333. data[file_size / sizeof(TCHAR)] = '\0';
  334. fseek(file, 0, SEEK_SET);
  335. fread_ret = fread(data, file_size, 1, file);
  336. fclose(file);
  337. if (fread_ret != 1){
  338. err_out(_T("Cannot read \"autoexec.bat\"."));
  339. return FALSE;
  340. }
  341. path_size = _tcslen(long_path) + 1;
  342. path = (LPTSTR)malloc(path_size * sizeof(TCHAR));
  343. if (!GetShortPathName(long_path, path, path_size))
  344. _tcsncpy(path, long_path, path_size);
  345. buff_size = _tcslen(AUTOEXEC_CMD) + _tcslen(path);
  346. buff = (LPTSTR)malloc(buff_size * sizeof(TCHAR));
  347. expected_text_size = buff_size + _tcslen(AUTOEXEC_INTRO)
  348. + 4 /* 2 * '\r\n' */;
  349. expected_text = (LPTSTR)malloc(expected_text_size * sizeof(TCHAR));
  350. _tcscpy(expected_text, AUTOEXEC_INTRO);
  351. _tcscat(expected_text, _T("\r\n"));
  352. _stprintf(buff, AUTOEXEC_CMD, path);
  353. _tcscat(expected_text, buff);
  354. _tcscat(expected_text, _T("\r\n"));
  355. begin_pos = _tcsstr(data, expected_text);
  356. if (begin_pos){
  357. file = _wfopen(AUTOEXEC_PATH, _T("wb"));
  358. if (!file){
  359. err_out(_T("Cannot open \"autoexec.bat\" for writing."));
  360. func_ret = FALSE;
  361. }
  362. else{
  363. final_part = begin_pos + _tcslen(expected_text);
  364. if ((fwrite(data, begin_pos - data, 1, file) != 1 &&
  365. (begin_pos - data)) || /* "fwrite"fails if the
  366. second argument is 0 */
  367. (fwrite(final_part, _tcslen(final_part), 1, file) != 1 &&
  368. _tcslen(final_part)))
  369. func_ret = FALSE;
  370. fclose(file);
  371. }
  372. }
  373. else
  374. verb_out(_T("Value does not exist in \"autoexec.bat\"."));
  375. free(data);
  376. free(path);
  377. free(buff);
  378. free(expected_text);
  379. return func_ret;
  380. }
  381. //---------------------------------------------------------------------------
  382. void __fastcall AddSearchPath(const UnicodeString Path)
  383. {
  384. bool Result;
  385. if (Win32Platform == VER_PLATFORM_WIN32_NT)
  386. {
  387. Result = add_path_reg(Path.c_str());
  388. }
  389. else
  390. {
  391. Result = add_path_autoexec(Path.c_str());
  392. }
  393. if (!Result)
  394. {
  395. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  396. }
  397. }
  398. //---------------------------------------------------------------------------
  399. void __fastcall RemoveSearchPath(const UnicodeString Path)
  400. {
  401. bool Result;
  402. if (Win32Platform == VER_PLATFORM_WIN32_NT)
  403. {
  404. Result = remove_path_reg(Path.c_str());
  405. }
  406. else
  407. {
  408. Result = remove_path_autoexec(Path.c_str());
  409. }
  410. if (!Result)
  411. {
  412. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  413. }
  414. }
  415. //---------------------------------------------------------------------------
  416. void __fastcall RegisterAsUrlHandler()
  417. {
  418. try
  419. {
  420. bool Success;
  421. bool User = true;
  422. TRegistry * Registry = new TRegistry();
  423. try
  424. {
  425. do
  426. {
  427. Success = true;
  428. User = !User;
  429. try
  430. {
  431. assert(Configuration != NULL);
  432. UnicodeString FileName = Application->ExeName;
  433. UnicodeString BaseKey;
  434. Registry->Access = KEY_WRITE;
  435. if (User)
  436. {
  437. Registry->RootKey = HKEY_CURRENT_USER;
  438. BaseKey = _T("Software\\Classes\\");
  439. }
  440. else
  441. {
  442. Registry->RootKey = HKEY_CLASSES_ROOT;
  443. BaseKey = _T("");
  444. }
  445. UnicodeString Protocol;
  446. for (int Index = 0; Index <= 1; Index++)
  447. {
  448. Protocol = (Index == 0) ? L"SCP" : L"SFTP";
  449. if (Registry->OpenKey(BaseKey + Protocol, true))
  450. {
  451. Registry->WriteString(L"", FMTLOAD(PROTOCOL_URL_DESC, (Protocol)));
  452. Registry->WriteString(L"URL Protocol", L"");
  453. Registry->WriteInteger(L"EditFlags", 0x02);
  454. Registry->WriteInteger(L"BrowserFlags", 0x08);
  455. if (Registry->OpenKey(L"DefaultIcon", true))
  456. {
  457. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (FileName)));
  458. Registry->CloseKey();
  459. }
  460. else
  461. {
  462. Abort();
  463. }
  464. }
  465. else
  466. {
  467. Abort();
  468. }
  469. if (Registry->OpenKey(BaseKey + Protocol, false) &&
  470. Registry->OpenKey(L"shell", true) &&
  471. Registry->OpenKey(L"open", true) &&
  472. Registry->OpenKey(L"command", true))
  473. {
  474. Registry->WriteString(L"", FORMAT(L"\"%s\" /unsafe \"%%1\"", (FileName)));
  475. Registry->CloseKey();
  476. }
  477. else
  478. {
  479. Abort();
  480. }
  481. }
  482. }
  483. catch(...)
  484. {
  485. Success = false;
  486. }
  487. }
  488. while (!Success && !User);
  489. }
  490. __finally
  491. {
  492. delete Registry;
  493. }
  494. }
  495. catch(Exception & E)
  496. {
  497. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR));
  498. }
  499. }
  500. //---------------------------------------------------------------------------
  501. void __fastcall TemporaryDirectoryCleanup()
  502. {
  503. bool Continue = true;
  504. TStrings * Folders = NULL;
  505. try
  506. {
  507. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  508. {
  509. Folders = WinConfiguration->FindTemporaryFolders();
  510. Continue = (Folders != NULL);
  511. if (Continue)
  512. {
  513. TQueryButtonAlias Aliases[1];
  514. Aliases[0].Button = qaRetry;
  515. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  516. TMessageParams Params(mpNeverAskAgainCheck);
  517. Params.Aliases = Aliases;
  518. Params.AliasesCount = LENOF(Aliases);
  519. unsigned int Answer = MoreMessageDialog(
  520. FMTLOAD(CLEANTEMP_CONFIRM, (Folders->Count)), Folders,
  521. qtWarning, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  522. if (Answer == qaNeverAskAgain)
  523. {
  524. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  525. Answer = qaYes;
  526. }
  527. else if (Answer == qaRetry)
  528. {
  529. for (int Index = 0; Index < Folders->Count; Index++)
  530. {
  531. ShellExecute(Application->Handle, NULL,
  532. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  533. }
  534. }
  535. Continue = (Answer == qaYes);
  536. }
  537. }
  538. if (Continue)
  539. {
  540. try
  541. {
  542. WinConfiguration->CleanupTemporaryFolders(Folders);
  543. }
  544. catch (Exception &E)
  545. {
  546. ShowExtendedException(&E);
  547. }
  548. }
  549. }
  550. __finally
  551. {
  552. delete Folders;
  553. }
  554. }
  555. //-------------------------------------------- -------------------------------
  556. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  557. {
  558. int MajorVer = Version / (10000*100*100);
  559. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  560. int Release = (Version % (10000*100)) / (10000);
  561. UnicodeString Result;
  562. if (Release > 0)
  563. {
  564. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  565. }
  566. else
  567. {
  568. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  569. }
  570. return Result;
  571. }
  572. //---------------------------------------------------------------------------
  573. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  574. {
  575. if (URL.Pos(L"?") == 0)
  576. {
  577. URL += L"?";
  578. }
  579. else
  580. {
  581. URL += L"&";
  582. }
  583. int CurrentCompoundVer = Configuration->CompoundVersion;
  584. AnsiString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  585. URL += FORMAT(L"utm_source=winscp&utm_medium=app&utm_campaign=%s", (Version));
  586. return URL;
  587. }
  588. //---------------------------------------------------------------------------
  589. UnicodeString __fastcall GetUsageData()
  590. {
  591. return Configuration->Usage->Serialize();
  592. }
  593. //---------------------------------------------------------------------------
  594. void __fastcall QueryUpdates()
  595. {
  596. bool Complete = false;
  597. try
  598. {
  599. UnicodeString Response;
  600. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  601. int CurrentCompoundVer = Configuration->CompoundVersion;
  602. UnicodeString CurrentVersionStr =
  603. FORMAT(L"%d.%d.%d.%d",
  604. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  605. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  606. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  607. THttp * CheckForUpdatesHTTP = new THttp(Application);
  608. try
  609. {
  610. UnicodeString URL = LoadStr(UPDATES_URL) +
  611. FORMAT(L"?v=%s&lang=%s", (CurrentVersionStr,
  612. IntToHex(__int64(GUIConfiguration->Locale), 4)));
  613. bool Beta;
  614. if (WinConfiguration->IsBeta)
  615. {
  616. Beta = true;
  617. }
  618. else
  619. {
  620. switch (Updates.BetaVersions)
  621. {
  622. case asAuto:
  623. Beta = WinConfiguration->AnyBetaInVersionHistory;
  624. break;
  625. case asOn:
  626. Beta = true;
  627. break;
  628. default:
  629. Beta = false;
  630. break;
  631. }
  632. }
  633. if (Beta)
  634. {
  635. URL += L"&beta=1";
  636. }
  637. URL += L"&dotnet=" + Updates.DotNetVersion;
  638. URL += L"&console=" + Updates.ConsoleVersion;
  639. UnicodeString Proxy;
  640. switch (Updates.ConnectionType)
  641. {
  642. case ctAuto:
  643. AutodetectProxyUrl(Proxy);
  644. break;
  645. case ctProxy:
  646. Proxy = FORMAT(L"%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  647. break;
  648. }
  649. CheckForUpdatesHTTP->Proxy = Proxy;
  650. CheckForUpdatesHTTP->URL = URL;
  651. if (Configuration->CollectUsage)
  652. {
  653. UTF8String UtfUsage = UTF8String(GetUsageData());
  654. CheckForUpdatesHTTP->Stream->Write(UtfUsage.c_str(), UtfUsage.Length());
  655. CheckForUpdatesHTTP->Post();
  656. }
  657. else
  658. {
  659. CheckForUpdatesHTTP->Action();
  660. }
  661. // sanity check
  662. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  663. {
  664. Abort();
  665. }
  666. UTF8String UtfResponse;
  667. UtfResponse.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  668. CheckForUpdatesHTTP->Stream->Read(UtfResponse.c_str(), UtfResponse.Length());
  669. Response = UnicodeString(UtfResponse);
  670. }
  671. __finally
  672. {
  673. delete CheckForUpdatesHTTP;
  674. }
  675. bool Changed = !Updates.HaveResults;
  676. Updates.LastCheck = Now();
  677. Updates.HaveResults = true;
  678. TUpdatesData PrevResults = Updates.Results;
  679. Updates.Results.Reset();
  680. Updates.Results.ForVersion = CurrentCompoundVer;
  681. while (!Response.IsEmpty())
  682. {
  683. UnicodeString Line = ::CutToChar(Response, L'\n', false);
  684. UnicodeString Name = ::CutToChar(Line, L'=', false);
  685. if (AnsiSameText(Name, "Version"))
  686. {
  687. int MajorVer = StrToInt(::CutToChar(Line, L'.', false));
  688. int MinorVer = StrToInt(::CutToChar(Line, L'.', false));
  689. int Release = StrToInt(::CutToChar(Line, L'.', false));
  690. int Build = StrToInt(::CutToChar(Line, L'.', false));
  691. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  692. Changed |= (NewVersion != PrevResults.Version);
  693. if (NewVersion <= CurrentCompoundVer)
  694. {
  695. NewVersion = 0;
  696. }
  697. Updates.Results.Version = NewVersion;
  698. Complete = true;
  699. }
  700. else if (AnsiSameText(Name, L"Message"))
  701. {
  702. Changed |= (PrevResults.Message != Line);
  703. Updates.Results.Message = Line;
  704. }
  705. else if (AnsiSameText(Name, L"Critical"))
  706. {
  707. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  708. Changed |= (PrevResults.Critical != NewCritical);
  709. Updates.Results.Critical = NewCritical;
  710. }
  711. else if (AnsiSameText(Name, L"Release"))
  712. {
  713. Changed |= (PrevResults.Release != Line);
  714. Updates.Results.Release = Line;
  715. }
  716. else if (AnsiSameText(Name, L"Disabled"))
  717. {
  718. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  719. Changed |= (PrevResults.Disabled != NewDisabled);
  720. Updates.Results.Disabled = NewDisabled;
  721. Complete = true;
  722. }
  723. else if (AnsiSameText(Name, L"Url"))
  724. {
  725. Changed |= (PrevResults.Url != Line);
  726. Updates.Results.Url = Line;
  727. }
  728. else if (AnsiSameText(Name, L"UrlButton"))
  729. {
  730. Changed |= (PrevResults.UrlButton != Line);
  731. Updates.Results.UrlButton = Line;
  732. }
  733. }
  734. if (Changed)
  735. {
  736. Updates.ShownResults = false;
  737. }
  738. WinConfiguration->Updates = Updates;
  739. }
  740. catch(Exception & E)
  741. {
  742. throw ExtException(&E, LoadStr(CHECK_FOR_UPDATES_ERROR));
  743. }
  744. if (Complete)
  745. {
  746. Configuration->Usage->Reset();
  747. }
  748. else
  749. {
  750. throw Exception(LoadStr(CHECK_FOR_UPDATES_ERROR));
  751. }
  752. }
  753. //---------------------------------------------------------------------------
  754. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  755. TQueryType & Type, bool Force)
  756. {
  757. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  758. assert(Updates.HaveResults);
  759. if (Updates.HaveResults)
  760. {
  761. if (Updates.Results.Disabled)
  762. {
  763. if (Force)
  764. {
  765. Message = LoadStr(UPDATE_DISABLED)+L"%s";
  766. }
  767. }
  768. else
  769. {
  770. New = (Updates.Results.Version > 0);
  771. if (New)
  772. {
  773. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  774. if (!Updates.Results.Release.IsEmpty())
  775. {
  776. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  777. }
  778. Message = FMTLOAD(NEW_VERSION3, (Version, L"%s"));
  779. }
  780. else
  781. {
  782. Message = LoadStr(NO_NEW_VERSION) + L"%s";
  783. }
  784. }
  785. if (!Updates.Results.Message.IsEmpty())
  786. {
  787. Message = FORMAT(Message,
  788. (FMTLOAD(UPDATE_MESSAGE,
  789. (StringReplace(Updates.Results.Message, L"|", L"\n", TReplaceFlags() << rfReplaceAll)))));
  790. }
  791. else
  792. {
  793. Message = FORMAT(Message, (L""));
  794. }
  795. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  796. }
  797. else
  798. {
  799. New = false;
  800. }
  801. }
  802. //---------------------------------------------------------------------------
  803. void __fastcall CheckForUpdates(bool CachedResults)
  804. {
  805. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  806. Busy(true);
  807. try
  808. {
  809. if (ActiveForm)
  810. {
  811. assert(ActiveForm->Enabled);
  812. ActiveForm->Enabled = false;
  813. }
  814. bool Again = false;
  815. do
  816. {
  817. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  818. bool Cached = !Again && Updates.HaveResults &&
  819. (double(Updates.Period) > 0) &&
  820. (Updates.Results.ForVersion == Configuration->CompoundVersion) &&
  821. CachedResults;
  822. if (!Cached)
  823. {
  824. QueryUpdates();
  825. // reread new data
  826. Updates = WinConfiguration->Updates;
  827. }
  828. Again = false;
  829. if (!Updates.ShownResults)
  830. {
  831. Updates.ShownResults = true;
  832. WinConfiguration->Updates = Updates;
  833. }
  834. assert(Updates.HaveResults);
  835. UnicodeString Message;
  836. bool New;
  837. TQueryType Type;
  838. GetUpdatesMessage(Message, New, Type, true);
  839. if (Updates.HaveResults)
  840. {
  841. Message += L"\n\n" +
  842. FMTLOAD(UPDATE_LAST,
  843. (FormatDateTime("ddddd", Updates.LastCheck)));
  844. if (double(Updates.Period) > 0)
  845. {
  846. Message += L"\n" +
  847. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  848. }
  849. }
  850. // add FLAGMASK(Cached, qaRetry) to enable "check again" button
  851. // for cached results
  852. int Answers = qaOK |
  853. FLAGMASK(New, qaCancel | qaAll) |
  854. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  855. TQueryButtonAlias Aliases[4];
  856. Aliases[0].Button = qaRetry;
  857. Aliases[0].Alias = LoadStr(CHECK_AGAIN_BUTTON);
  858. Aliases[1].Button = qaYes;
  859. if (Updates.Results.UrlButton.IsEmpty())
  860. {
  861. Aliases[1].Alias = LoadStr(UPDATE_URL_BUTTON);
  862. }
  863. else
  864. {
  865. Aliases[1].Alias = Updates.Results.UrlButton;
  866. }
  867. Aliases[2].Button = qaAll;
  868. Aliases[2].Alias = LoadStr(WHATS_NEW_BUTTON);
  869. Aliases[3].Button = qaOK;
  870. Aliases[3].Alias = LoadStr(DOWNLOAD_BUTTON);
  871. TMessageParams Params;
  872. Params.Aliases = Aliases;
  873. // alias "ok" button to "download" only if we have new version
  874. Params.AliasesCount = (New ? 4 : 3);
  875. unsigned int Answer =
  876. MessageDialog(Message, Type,
  877. Answers, HELP_UPDATES, &Params);
  878. switch (Answer)
  879. {
  880. case qaOK:
  881. if (New)
  882. {
  883. OpenBrowser(LoadStr(DOWNLOAD_URL));
  884. }
  885. break;
  886. case qaYes:
  887. OpenBrowser(Updates.Results.Url);
  888. break;
  889. case qaAll:
  890. OpenBrowser(LoadStr(HISTORY_URL));
  891. break;
  892. case qaRetry:
  893. Again = true;
  894. break;
  895. }
  896. }
  897. while (Again);
  898. }
  899. __finally
  900. {
  901. if (ActiveForm)
  902. {
  903. ActiveForm->Enabled = true;
  904. }
  905. Busy(false);
  906. }
  907. }
  908. //---------------------------------------------------------------------------
  909. class TUpdateThread : public TCompThread
  910. {
  911. public:
  912. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  913. protected:
  914. virtual void __fastcall Execute();
  915. TThreadMethod FOnUpdatesChecked;
  916. };
  917. //---------------------------------------------------------------------------
  918. TUpdateThread * UpdateThread = NULL;
  919. //---------------------------------------------------------------------------
  920. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  921. TCompThread(false),
  922. FOnUpdatesChecked(OnUpdatesChecked)
  923. {
  924. }
  925. //---------------------------------------------------------------------------
  926. void __fastcall TUpdateThread::Execute()
  927. {
  928. try
  929. {
  930. QueryUpdates();
  931. if (FOnUpdatesChecked != NULL)
  932. {
  933. Synchronize(FOnUpdatesChecked);
  934. }
  935. }
  936. catch(...)
  937. {
  938. // ignore errors
  939. }
  940. }
  941. //---------------------------------------------------------------------------
  942. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  943. {
  944. assert(UpdateThread == NULL);
  945. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  946. }
  947. //---------------------------------------------------------------------------
  948. void __fastcall StopUpdateThread()
  949. {
  950. if (UpdateThread != NULL)
  951. {
  952. SAFE_DESTROY(UpdateThread);
  953. }
  954. }
  955. //---------------------------------------------------------------------------
  956. void __fastcall SetupInitialize()
  957. {
  958. WinConfiguration->UpdateJumpList();
  959. }
  960. //---------------------------------------------------------------------------
  961. void __fastcall UpdateJumpList(TStrings * SessionNames)
  962. {
  963. ICustomDestinationList * DestinationList = NULL;
  964. IObjectArray * RemovedArray = NULL;
  965. TStringList * Removed = NULL;
  966. IObjectCollection * Collection = NULL;
  967. try
  968. {
  969. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  970. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  971. {
  972. unsigned int MinSlots;
  973. if (SUCCEEDED(DestinationList->BeginList(&MinSlots, IID_IObjectArray, (void**)&RemovedArray)))
  974. {
  975. Removed = new TStringList();
  976. unsigned int RemovedCount;
  977. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  978. {
  979. RemovedCount = 0;
  980. }
  981. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  982. {
  983. IShellLink * Link;
  984. wchar_t Desc[2048];
  985. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  986. SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  987. {
  988. Removed->Add(Desc);
  989. }
  990. }
  991. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  992. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  993. {
  994. int Count = 0;
  995. for (int Index = 0; Index < SessionNames->Count; Index++)
  996. {
  997. IShellLink * Link;
  998. bool DefaultsOnly;
  999. TSessionData * SessionData =
  1000. StoredSessions->ParseUrl(SessionNames->Strings[Index], NULL, DefaultsOnly);
  1001. try
  1002. {
  1003. Link =
  1004. CreateDesktopSessionShortCut(
  1005. SessionData, SessionData->LocalName, L"/UploadIfAny", -1, true);
  1006. }
  1007. __finally
  1008. {
  1009. delete SessionData;
  1010. }
  1011. wchar_t Desc[2048];
  1012. if (SUCCEEDED(Link->GetDescription(Desc, sizeof(Desc) - 1)))
  1013. {
  1014. if (Removed->IndexOf(Desc) < 0)
  1015. {
  1016. try
  1017. {
  1018. CHECK(SUCCEEDED(Collection->AddObject(Link)));
  1019. Count++;
  1020. }
  1021. __finally
  1022. {
  1023. Link->Release();
  1024. }
  1025. }
  1026. else
  1027. {
  1028. SessionNames->Delete(Index);
  1029. Index--;
  1030. }
  1031. }
  1032. }
  1033. if (Count > 0)
  1034. {
  1035. IObjectArray * Array;
  1036. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1037. {
  1038. DestinationList->AppendCategory(LoadStr(JUMPLIST_RECENT).c_str(), Array);
  1039. Array->Release();
  1040. }
  1041. }
  1042. Collection->Release();
  1043. Collection = NULL;
  1044. DestinationList->CommitList();
  1045. }
  1046. }
  1047. }
  1048. }
  1049. __finally
  1050. {
  1051. if (Collection != NULL)
  1052. {
  1053. Collection->Release();
  1054. }
  1055. if (RemovedArray != NULL)
  1056. {
  1057. RemovedArray->Release();
  1058. }
  1059. if (DestinationList != NULL)
  1060. {
  1061. DestinationList->Release();
  1062. }
  1063. delete Removed;
  1064. }
  1065. }