Setup.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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 <Common.h>
  10. #include <CoreMain.h>
  11. #include <Exceptions.h>
  12. #include <TextsWin.h>
  13. #include <HelpWin.h>
  14. #include <TcpIp.hpp>
  15. #include <CompThread.hpp>
  16. #include <FileInfo.h>
  17. #include "WinConfiguration.h"
  18. #include "WinInterface.h"
  19. #include "Tools.h"
  20. #include "Setup.h"
  21. //---------------------------------------------------------------------------
  22. /* Using quotes or not should make no difference but some programs (for
  23. instance cygwin and msys) don't like them. */
  24. /* #define USE_QUOTES */
  25. //---------------------------------------------------------------------------
  26. #define APP_NAME "WinSCP"
  27. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  28. _T("Session Manager\\Environment")
  29. #define AUTOEXEC_PATH _T("c:\\autoexec.bat")
  30. #define AUTOEXEC_INTRO "rem ***** The following line was added by " \
  31. APP_NAME " *****"
  32. #ifdef USE_QUOTES
  33. # define AUTOEXEC_CMD "set PATH=%%PATH%%;\"%s\""
  34. #else
  35. # define AUTOEXEC_CMD "set PATH=%%PATH%%;%s"
  36. #endif
  37. /* Command line options. */
  38. AnsiString LastPathError;
  39. //---------------------------------------------------------------------------
  40. #define verb_out(msg) ((void)0)
  41. #define verb_out_param(msg, param) ((void)0)
  42. //---------------------------------------------------------------------------
  43. // Display the error "err_msg".
  44. void err_out(LPCTSTR err_msg)
  45. {
  46. LastPathError = err_msg;
  47. }
  48. //---------------------------------------------------------------------------
  49. // Display "base_err_msg" followed by the description of the system error
  50. // identified by "sys_err".
  51. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  52. {
  53. LastPathError = FORMAT("%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  54. }
  55. //---------------------------------------------------------------------------
  56. // Works as "strcmp" but the comparison is not case sensitive.
  57. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  58. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  59. if (*str1 == '\0')
  60. return 0;
  61. return tolower(*str1) - tolower(*str2);
  62. }
  63. //---------------------------------------------------------------------------
  64. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  65. // not present). The returned value must be freed with "free".
  66. LPTSTR unquote(LPCTSTR str){
  67. int last_pos;
  68. LPTSTR ret;
  69. size_t new_len;
  70. last_pos = _tcslen(str) - 1;
  71. if (last_pos != -1 && str[0] == '"' && str[last_pos] == '"'){
  72. new_len= (_tcslen(str) - 1);
  73. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  74. lstrcpyn(ret, &str[1], new_len);
  75. }
  76. else
  77. ret = _tcsdup(str);
  78. return ret;
  79. }
  80. //---------------------------------------------------------------------------
  81. // Find "what" in the ";" separated string "str" and returns a pointer to
  82. // the first letter of "what" in the string. If "next" is not "NULL" it
  83. // points to the first letter after "what" (excluding the trailing ";").
  84. // If "what" isn't find the functions returns "NULL".
  85. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  86. LPTSTR tok_buff;
  87. LPTSTR curr_tok;
  88. LPTSTR curr_tok_dup;
  89. BOOL path_eq;
  90. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  91. int pos = -1;
  92. LPTSTR ret;
  93. tok_buff = _tcsdup(str);
  94. curr_tok = _tcstok(tok_buff, _T(";"));
  95. while (pos == -1 && curr_tok){
  96. curr_tok_dup = unquote(curr_tok);
  97. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  98. GetShortPathName(curr_tok_dup, sh_path2,
  99. LENOF(sh_path2)) &&
  100. (tcharicmp(sh_path1, sh_path2) == 0);
  101. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  102. pos = curr_tok - tok_buff;
  103. }
  104. free(curr_tok_dup);
  105. curr_tok = _tcstok(NULL, _T(";"));
  106. if (pos != -1 && next){
  107. if (curr_tok)
  108. *next = str + (curr_tok - tok_buff);
  109. else
  110. *next = str + _tcslen(str);
  111. }
  112. }
  113. free(tok_buff);
  114. if (pos != -1)
  115. ret = str + pos;
  116. else
  117. ret = NULL;
  118. return ret;
  119. }
  120. //---------------------------------------------------------------------------
  121. void path_reg_propagate()
  122. {
  123. DWORD send_message_result;
  124. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  125. (LPARAM)"Environment", SMTO_ABORTIFHUNG,
  126. 5000, &send_message_result);
  127. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  128. {
  129. err_out_sys(_T("Cannot propagate the new enviroment to ")
  130. _T("other processes. The new value will be ")
  131. _T("avaible after a reboot."), GetLastError());
  132. SimpleErrorDialog(LastPathError);
  133. LastPathError = "";
  134. }
  135. }
  136. //---------------------------------------------------------------------------
  137. // Add "path" to the registry. Return "TRUE" if the path has been added or
  138. // was already in the registry, "FALSE" otherwise.
  139. BOOL add_path_reg(LPCTSTR path){
  140. HKEY key;
  141. LONG ret;
  142. DWORD data_size;
  143. LPTSTR reg_str;
  144. BOOL func_ret = TRUE;
  145. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  146. KEY_WRITE | KEY_READ, &key);
  147. if (ret != ERROR_SUCCESS){
  148. err_out_sys(_T("Cannot open registry."), ret);
  149. return FALSE;
  150. }
  151. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  152. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  153. includes '\0'. */
  154. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  155. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  156. &data_size);
  157. if (ret != ERROR_SUCCESS){
  158. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  159. func_ret = FALSE;
  160. }
  161. else{
  162. if (!find_reg_str(reg_str, path, NULL)){
  163. _tcscat(reg_str, _T(";"));
  164. #ifdef USE_QUOTES
  165. _tcscat(reg_str, _T(";\""));
  166. #endif
  167. _tcscat(reg_str, path);
  168. #ifdef USE_QUOTES
  169. _tcscat(reg_str, _T("\""));
  170. #endif
  171. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  172. (LPBYTE)reg_str,
  173. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  174. if (ret != ERROR_SUCCESS){
  175. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  176. func_ret = FALSE;
  177. }
  178. /* Is this needed to make the new key avaible? */
  179. RegFlushKey(key);
  180. SetLastError(0);
  181. path_reg_propagate();
  182. }
  183. else
  184. verb_out(_T("Value already exists in the registry."));
  185. }
  186. RegCloseKey(key);
  187. free(reg_str);
  188. return func_ret;
  189. }
  190. //---------------------------------------------------------------------------
  191. // Removes "path" from the registry. Return "TRUE" if the path has been
  192. // removed or it wasn't in the registry, "FALSE" otherwise.
  193. BOOL remove_path_reg(LPCTSTR path){
  194. HKEY key;
  195. LONG ret;
  196. DWORD data_size;
  197. LPTSTR reg_str;
  198. LPTSTR reg_str2;
  199. BOOL func_ret = TRUE;
  200. LPTSTR next;
  201. LPTSTR del_part;
  202. int last_pos;
  203. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  204. KEY_WRITE | KEY_READ, &key);
  205. if (ret != ERROR_SUCCESS){
  206. err_out_sys(_T("Cannot open registry."), ret);
  207. return FALSE;
  208. }
  209. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  210. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  211. includes '\0'. */
  212. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  213. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  214. (LPBYTE)reg_str, &data_size);
  215. if (ret != ERROR_SUCCESS){
  216. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  217. func_ret = FALSE;
  218. }
  219. else{
  220. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  221. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  222. *del_part = '\0';
  223. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  224. last_pos = _tcslen(reg_str2) - 1;
  225. if (last_pos != -1 && reg_str2[last_pos] == ';')
  226. reg_str2[last_pos] = '\0';
  227. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  228. (LPBYTE)reg_str2,
  229. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  230. if (ret != ERROR_SUCCESS){
  231. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  232. func_ret = FALSE;
  233. }
  234. free(reg_str2);
  235. /* Is this needed to make the new key avaible? */
  236. RegFlushKey(key);
  237. SetLastError(0);
  238. path_reg_propagate();
  239. }
  240. else
  241. verb_out(_T("Value does not exist in the registry."));
  242. }
  243. RegCloseKey(key);
  244. free(reg_str);
  245. return func_ret;
  246. }
  247. //---------------------------------------------------------------------------
  248. /* Can this program run under Win9x if compiled with unicode support? */
  249. #if !defined _UNICODE
  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 = _tfopen(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 = _tfopen(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 = _tfopen(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. #endif /* #if !defined _UNICODE */
  383. //---------------------------------------------------------------------------
  384. void __fastcall AddSearchPath(const AnsiString Path)
  385. {
  386. bool Result;
  387. if (Win32Platform == VER_PLATFORM_WIN32_NT)
  388. {
  389. Result = add_path_reg(Path.c_str());
  390. }
  391. else
  392. {
  393. Result = add_path_autoexec(Path.c_str());
  394. }
  395. if (!Result)
  396. {
  397. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  398. }
  399. }
  400. //---------------------------------------------------------------------------
  401. void __fastcall RemoveSearchPath(const AnsiString Path)
  402. {
  403. bool Result;
  404. if (Win32Platform == VER_PLATFORM_WIN32_NT)
  405. {
  406. Result = remove_path_reg(Path.c_str());
  407. }
  408. else
  409. {
  410. Result = remove_path_autoexec(Path.c_str());
  411. }
  412. if (!Result)
  413. {
  414. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  415. }
  416. }
  417. //---------------------------------------------------------------------------
  418. void __fastcall RegisterAsUrlHandler()
  419. {
  420. try
  421. {
  422. bool Success;
  423. bool User = true;
  424. TRegistry * Registry = new TRegistry();
  425. try
  426. {
  427. do
  428. {
  429. Success = true;
  430. User = !User;
  431. try
  432. {
  433. assert(Configuration != NULL);
  434. AnsiString FileName = Application->ExeName;
  435. AnsiString BaseKey;
  436. Registry->Access = KEY_WRITE;
  437. if (User)
  438. {
  439. Registry->RootKey = HKEY_CURRENT_USER;
  440. BaseKey = "Software\\Classes\\";
  441. }
  442. else
  443. {
  444. Registry->RootKey = HKEY_CLASSES_ROOT;
  445. BaseKey = "";
  446. }
  447. AnsiString Protocol;
  448. for (int Index = 0; Index <= 1; Index++)
  449. {
  450. Protocol = (Index == 0) ? "SCP" : "SFTP";
  451. if (Registry->OpenKey(BaseKey + Protocol, true))
  452. {
  453. Registry->WriteString("", FMTLOAD(PROTOCOL_URL_DESC, (Protocol)));
  454. Registry->WriteString("URL Protocol", "");
  455. Registry->WriteInteger("EditFlags", 0x02);
  456. Registry->WriteInteger("BrowserFlags", 0x08);
  457. if (Registry->OpenKey("DefaultIcon", true))
  458. {
  459. Registry->WriteString("", FORMAT("\"%s\",0", (FileName)));
  460. Registry->CloseKey();
  461. }
  462. else
  463. {
  464. Abort();
  465. }
  466. }
  467. else
  468. {
  469. Abort();
  470. }
  471. if (Registry->OpenKey(BaseKey + Protocol, false) &&
  472. Registry->OpenKey("shell", true) &&
  473. Registry->OpenKey("open", true) &&
  474. Registry->OpenKey("command", true))
  475. {
  476. Registry->WriteString("", FORMAT("\"%s\" /unsafe \"%%1\"", (FileName)));
  477. Registry->CloseKey();
  478. }
  479. else
  480. {
  481. Abort();
  482. }
  483. }
  484. }
  485. catch(...)
  486. {
  487. Success = false;
  488. }
  489. }
  490. while (!Success && !User);
  491. }
  492. __finally
  493. {
  494. delete Registry;
  495. }
  496. }
  497. catch(Exception & E)
  498. {
  499. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR));
  500. }
  501. }
  502. //---------------------------------------------------------------------------
  503. void __fastcall TemporaryDirectoryCleanup()
  504. {
  505. bool Continue = true;
  506. TStrings * Folders = NULL;
  507. try
  508. {
  509. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  510. {
  511. Folders = WinConfiguration->FindTemporaryFolders();
  512. Continue = (Folders != NULL);
  513. if (Continue)
  514. {
  515. TQueryButtonAlias Aliases[1];
  516. Aliases[0].Button = qaRetry;
  517. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  518. TMessageParams Params(mpNeverAskAgainCheck);
  519. Params.Aliases = Aliases;
  520. Params.AliasesCount = LENOF(Aliases);
  521. int Answer = MoreMessageDialog(
  522. FMTLOAD(CLEANTEMP_CONFIRM, (Folders->Count)), Folders,
  523. qtWarning, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  524. if (Answer == qaNeverAskAgain)
  525. {
  526. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  527. Answer = qaYes;
  528. }
  529. else if (Answer == qaRetry)
  530. {
  531. for (int Index = 0; Index < Folders->Count; Index++)
  532. {
  533. ShellExecute(Application->Handle, NULL,
  534. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  535. }
  536. }
  537. Continue = (Answer == qaYes);
  538. }
  539. }
  540. if (Continue)
  541. {
  542. try
  543. {
  544. WinConfiguration->CleanupTemporaryFolders(Folders);
  545. }
  546. catch (Exception &E)
  547. {
  548. ShowExtendedException(&E);
  549. }
  550. }
  551. }
  552. __finally
  553. {
  554. delete Folders;
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. void __fastcall QueryUpdates()
  559. {
  560. bool Complete = false;
  561. try
  562. {
  563. AnsiString Response;
  564. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  565. int CurrentCompoundVer = Configuration->CompoundVersion;
  566. AnsiString CurrentVersionStr =
  567. FORMAT("%d.%d.%d.%d",
  568. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  569. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  570. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  571. THttp * CheckForUpdatesHTTP = new THttp(Application);
  572. try
  573. {
  574. AnsiString URL = LoadStr(UPDATES_URL) +
  575. FORMAT("?v=%s&lang=%s", (CurrentVersionStr,
  576. IntToHex(__int64(GUIConfiguration->Locale), 4)));
  577. bool Beta;
  578. switch (Updates.BetaVersions)
  579. {
  580. case asAuto:
  581. Beta = WinConfiguration->AnyBetaInVersionHistory;
  582. break;
  583. case asOn:
  584. Beta = true;
  585. break;
  586. default:
  587. Beta = false;
  588. break;
  589. }
  590. if (Beta)
  591. {
  592. URL += "&beta=1";
  593. }
  594. AnsiString Proxy;
  595. switch (Updates.ConnectionType)
  596. {
  597. case ctAuto:
  598. AutodetectProxyUrl(Proxy);
  599. break;
  600. case ctProxy:
  601. Proxy = FORMAT("%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  602. break;
  603. }
  604. CheckForUpdatesHTTP->Proxy = Proxy;
  605. CheckForUpdatesHTTP->URL = URL;
  606. CheckForUpdatesHTTP->Action();
  607. // sanity check
  608. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  609. {
  610. Abort();
  611. }
  612. Response.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  613. CheckForUpdatesHTTP->Stream->Read(Response.c_str(), Response.Length());
  614. }
  615. __finally
  616. {
  617. delete CheckForUpdatesHTTP;
  618. }
  619. bool Changed = !Updates.HaveResults;
  620. Updates.LastCheck = Now();
  621. Updates.HaveResults = true;
  622. TUpdatesData PrevResults = Updates.Results;
  623. Updates.Results.Reset();
  624. Updates.Results.ForVersion = CurrentCompoundVer;
  625. while (!Response.IsEmpty())
  626. {
  627. AnsiString Line = ::CutToChar(Response, '\n', false);
  628. AnsiString Name = ::CutToChar(Line, '=', false);
  629. if (AnsiSameText(Name, "Version"))
  630. {
  631. int MajorVer = StrToInt(::CutToChar(Line, '.', false));
  632. int MinorVer = StrToInt(::CutToChar(Line, '.', false));
  633. int Release = StrToInt(::CutToChar(Line, '.', false));
  634. int Build = StrToInt(::CutToChar(Line, '.', false));
  635. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  636. Changed |= (NewVersion != PrevResults.Version);
  637. if (NewVersion <= CurrentCompoundVer)
  638. {
  639. NewVersion = 0;
  640. }
  641. Updates.Results.Version = NewVersion;
  642. Complete = true;
  643. }
  644. else if (AnsiSameText(Name, "Message"))
  645. {
  646. Changed |= (PrevResults.Message != Line);
  647. Updates.Results.Message = Line;
  648. }
  649. else if (AnsiSameText(Name, "Critical"))
  650. {
  651. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  652. Changed |= (PrevResults.Critical != NewCritical);
  653. Updates.Results.Critical = NewCritical;
  654. }
  655. else if (AnsiSameText(Name, "Release"))
  656. {
  657. Changed |= (PrevResults.Release != Line);
  658. Updates.Results.Release = Line;
  659. }
  660. else if (AnsiSameText(Name, "Disabled"))
  661. {
  662. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  663. Changed |= (PrevResults.Disabled != NewDisabled);
  664. Updates.Results.Disabled = NewDisabled;
  665. Complete = true;
  666. }
  667. else if (AnsiSameText(Name, "Url"))
  668. {
  669. Changed |= (PrevResults.Url != Line);
  670. Updates.Results.Url = Line;
  671. }
  672. else if (AnsiSameText(Name, "UrlButton"))
  673. {
  674. Changed |= (PrevResults.UrlButton != Line);
  675. Updates.Results.UrlButton = Line;
  676. }
  677. }
  678. if (Changed)
  679. {
  680. Updates.ShownResults = false;
  681. }
  682. WinConfiguration->Updates = Updates;
  683. }
  684. catch(Exception & E)
  685. {
  686. throw ExtException(&E, LoadStr(CHECK_FOR_UPDATES_ERROR));
  687. }
  688. if (!Complete)
  689. {
  690. throw Exception(LoadStr(CHECK_FOR_UPDATES_ERROR));
  691. }
  692. }
  693. //---------------------------------------------------------------------------
  694. void __fastcall GetUpdatesMessage(AnsiString & Message, bool & New,
  695. TQueryType & Type, bool Force)
  696. {
  697. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  698. assert(Updates.HaveResults);
  699. if (Updates.HaveResults)
  700. {
  701. if (Updates.Results.Disabled)
  702. {
  703. if (Force)
  704. {
  705. Message = LoadStr(UPDATE_DISABLED)+"%s";
  706. }
  707. }
  708. else
  709. {
  710. New = (Updates.Results.Version > 0);
  711. if (New)
  712. {
  713. AnsiString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  714. if (!Updates.Results.Release.IsEmpty())
  715. {
  716. Version = FORMAT("%s %s", (Version, Updates.Results.Release));
  717. }
  718. Message = FMTLOAD(NEW_VERSION3, (Version, "%s"));
  719. }
  720. else
  721. {
  722. Message = LoadStr(NO_NEW_VERSION) + "%s";
  723. }
  724. }
  725. if (!Updates.Results.Message.IsEmpty())
  726. {
  727. Message = FORMAT(Message,
  728. (FMTLOAD(UPDATE_MESSAGE,
  729. (StringReplace(Updates.Results.Message, "|", "\n", TReplaceFlags() << rfReplaceAll)))));
  730. }
  731. else
  732. {
  733. Message = FORMAT(Message, (""));
  734. }
  735. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  736. }
  737. else
  738. {
  739. New = false;
  740. }
  741. }
  742. //---------------------------------------------------------------------------
  743. void __fastcall CheckForUpdates(bool CachedResults)
  744. {
  745. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  746. Busy(true);
  747. try
  748. {
  749. if (ActiveForm)
  750. {
  751. assert(ActiveForm->Enabled);
  752. ActiveForm->Enabled = false;
  753. }
  754. bool Again = false;
  755. do
  756. {
  757. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  758. bool Cached = !Again && Updates.HaveResults &&
  759. (double(Updates.Period) > 0) &&
  760. (Updates.Results.ForVersion == Configuration->CompoundVersion) &&
  761. CachedResults;
  762. if (!Cached)
  763. {
  764. QueryUpdates();
  765. // reread enw data
  766. Updates = WinConfiguration->Updates;
  767. }
  768. Again = false;
  769. if (!Updates.ShownResults)
  770. {
  771. Updates.ShownResults = true;
  772. WinConfiguration->Updates = Updates;
  773. }
  774. assert(Updates.HaveResults);
  775. AnsiString Message;
  776. bool New;
  777. TQueryType Type;
  778. GetUpdatesMessage(Message, New, Type, true);
  779. // add FLAGMASK(Cached, qaRetry) to enable "check again" button
  780. // for cached results
  781. int Answers = qaOK |
  782. FLAGMASK(New, qaCancel | qaAll) |
  783. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  784. TQueryButtonAlias Aliases[4];
  785. Aliases[0].Button = qaRetry;
  786. Aliases[0].Alias = LoadStr(CHECK_AGAIN_BUTTON);
  787. Aliases[1].Button = qaYes;
  788. if (Updates.Results.UrlButton.IsEmpty())
  789. {
  790. Aliases[1].Alias = LoadStr(UPDATE_URL_BUTTON);
  791. }
  792. else
  793. {
  794. Aliases[1].Alias = Updates.Results.UrlButton;
  795. }
  796. Aliases[2].Button = qaAll;
  797. Aliases[2].Alias = LoadStr(WHATS_NEW_BUTTON);
  798. Aliases[3].Button = qaOK;
  799. Aliases[3].Alias = LoadStr(DOWNLOAD_BUTTON);
  800. TMessageParams Params;
  801. Params.Aliases = Aliases;
  802. // alias "ok" button to "download" only if we have new version
  803. Params.AliasesCount = (New ? 4 : 3);
  804. int Answer =
  805. MessageDialog(Message, Type,
  806. Answers, HELP_UPDATES, &Params);
  807. switch (Answer)
  808. {
  809. case qaOK:
  810. if (New)
  811. {
  812. OpenBrowser(LoadStr(DOWNLOAD_URL));
  813. }
  814. break;
  815. case qaYes:
  816. OpenBrowser(Updates.Results.Url);
  817. break;
  818. case qaAll:
  819. OpenBrowser(LoadStr(HISTORY_URL));
  820. break;
  821. case qaRetry:
  822. Again = true;
  823. break;
  824. }
  825. }
  826. while (Again);
  827. }
  828. __finally
  829. {
  830. if (ActiveForm)
  831. {
  832. ActiveForm->Enabled = true;
  833. }
  834. Busy(false);
  835. }
  836. }
  837. //---------------------------------------------------------------------------
  838. class TUpdateThread : public TCompThread
  839. {
  840. public:
  841. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  842. protected:
  843. virtual void __fastcall Execute();
  844. TThreadMethod FOnUpdatesChecked;
  845. };
  846. //---------------------------------------------------------------------------
  847. TUpdateThread * UpdateThread = NULL;
  848. //---------------------------------------------------------------------------
  849. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  850. TCompThread(false),
  851. FOnUpdatesChecked(OnUpdatesChecked)
  852. {
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TUpdateThread::Execute()
  856. {
  857. try
  858. {
  859. QueryUpdates();
  860. if (FOnUpdatesChecked != NULL)
  861. {
  862. Synchronize(FOnUpdatesChecked);
  863. }
  864. }
  865. catch(...)
  866. {
  867. // ignore errors
  868. }
  869. }
  870. //---------------------------------------------------------------------------
  871. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  872. {
  873. assert(UpdateThread == NULL);
  874. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall StopUpdateThread()
  878. {
  879. if (UpdateThread != NULL)
  880. {
  881. SAFE_DESTROY(UpdateThread);
  882. }
  883. }