Setup.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. AnsiString __fastcall VersionStrFromCompoundVersion(int Version)
  559. {
  560. int MajorVer = Version / (10000*100*100);
  561. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  562. int Release = (Version % (10000*100)) / (10000);
  563. AnsiString Result;
  564. if (Release > 0)
  565. {
  566. Result = FORMAT("%d.%d.%d", (MajorVer, MinorVer, Release));
  567. }
  568. else
  569. {
  570. Result = FORMAT("%d.%d", (MajorVer, MinorVer));
  571. }
  572. return Result;
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall QueryUpdates()
  576. {
  577. bool Complete = false;
  578. try
  579. {
  580. AnsiString Response;
  581. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  582. int CurrentCompoundVer = Configuration->CompoundVersion;
  583. AnsiString CurrentVersionStr =
  584. FORMAT("%d.%d.%d.%d",
  585. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  586. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  587. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  588. THttp * CheckForUpdatesHTTP = new THttp(Application);
  589. try
  590. {
  591. AnsiString URL = LoadStr(UPDATES_URL) +
  592. FORMAT("?v=%s&lang=%s", (CurrentVersionStr,
  593. IntToHex(__int64(GUIConfiguration->Locale), 4)));
  594. bool Beta;
  595. switch (Updates.BetaVersions)
  596. {
  597. case asAuto:
  598. Beta = WinConfiguration->AnyBetaInVersionHistory;
  599. break;
  600. case asOn:
  601. Beta = true;
  602. break;
  603. default:
  604. Beta = false;
  605. break;
  606. }
  607. if (Beta)
  608. {
  609. URL += "&beta=1";
  610. }
  611. AnsiString Proxy;
  612. switch (Updates.ConnectionType)
  613. {
  614. case ctAuto:
  615. AutodetectProxyUrl(Proxy);
  616. break;
  617. case ctProxy:
  618. Proxy = FORMAT("%s:%d", (Updates.ProxyHost, Updates.ProxyPort));
  619. break;
  620. }
  621. CheckForUpdatesHTTP->Proxy = Proxy;
  622. CheckForUpdatesHTTP->URL = URL;
  623. CheckForUpdatesHTTP->Action();
  624. // sanity check
  625. if (CheckForUpdatesHTTP->Stream->Size > 102400)
  626. {
  627. Abort();
  628. }
  629. Response.SetLength(static_cast<int>(CheckForUpdatesHTTP->Stream->Size));
  630. CheckForUpdatesHTTP->Stream->Read(Response.c_str(), Response.Length());
  631. }
  632. __finally
  633. {
  634. delete CheckForUpdatesHTTP;
  635. }
  636. bool Changed = !Updates.HaveResults;
  637. Updates.LastCheck = Now();
  638. Updates.HaveResults = true;
  639. TUpdatesData PrevResults = Updates.Results;
  640. Updates.Results.Reset();
  641. Updates.Results.ForVersion = CurrentCompoundVer;
  642. while (!Response.IsEmpty())
  643. {
  644. AnsiString Line = ::CutToChar(Response, '\n', false);
  645. AnsiString Name = ::CutToChar(Line, '=', false);
  646. if (AnsiSameText(Name, "Version"))
  647. {
  648. int MajorVer = StrToInt(::CutToChar(Line, '.', false));
  649. int MinorVer = StrToInt(::CutToChar(Line, '.', false));
  650. int Release = StrToInt(::CutToChar(Line, '.', false));
  651. int Build = StrToInt(::CutToChar(Line, '.', false));
  652. int NewVersion = CalculateCompoundVersion(MajorVer, MinorVer, Release, Build);
  653. Changed |= (NewVersion != PrevResults.Version);
  654. if (NewVersion <= CurrentCompoundVer)
  655. {
  656. NewVersion = 0;
  657. }
  658. Updates.Results.Version = NewVersion;
  659. Complete = true;
  660. }
  661. else if (AnsiSameText(Name, "Message"))
  662. {
  663. Changed |= (PrevResults.Message != Line);
  664. Updates.Results.Message = Line;
  665. }
  666. else if (AnsiSameText(Name, "Critical"))
  667. {
  668. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  669. Changed |= (PrevResults.Critical != NewCritical);
  670. Updates.Results.Critical = NewCritical;
  671. }
  672. else if (AnsiSameText(Name, "Release"))
  673. {
  674. Changed |= (PrevResults.Release != Line);
  675. Updates.Results.Release = Line;
  676. }
  677. else if (AnsiSameText(Name, "Disabled"))
  678. {
  679. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  680. Changed |= (PrevResults.Disabled != NewDisabled);
  681. Updates.Results.Disabled = NewDisabled;
  682. Complete = true;
  683. }
  684. else if (AnsiSameText(Name, "Url"))
  685. {
  686. Changed |= (PrevResults.Url != Line);
  687. Updates.Results.Url = Line;
  688. }
  689. else if (AnsiSameText(Name, "UrlButton"))
  690. {
  691. Changed |= (PrevResults.UrlButton != Line);
  692. Updates.Results.UrlButton = Line;
  693. }
  694. }
  695. if (Changed)
  696. {
  697. Updates.ShownResults = false;
  698. }
  699. WinConfiguration->Updates = Updates;
  700. }
  701. catch(Exception & E)
  702. {
  703. throw ExtException(&E, LoadStr(CHECK_FOR_UPDATES_ERROR));
  704. }
  705. if (!Complete)
  706. {
  707. throw Exception(LoadStr(CHECK_FOR_UPDATES_ERROR));
  708. }
  709. }
  710. //---------------------------------------------------------------------------
  711. void __fastcall GetUpdatesMessage(AnsiString & Message, bool & New,
  712. TQueryType & Type, bool Force)
  713. {
  714. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  715. assert(Updates.HaveResults);
  716. if (Updates.HaveResults)
  717. {
  718. if (Updates.Results.Disabled)
  719. {
  720. if (Force)
  721. {
  722. Message = LoadStr(UPDATE_DISABLED)+"%s";
  723. }
  724. }
  725. else
  726. {
  727. New = (Updates.Results.Version > 0);
  728. if (New)
  729. {
  730. AnsiString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  731. if (!Updates.Results.Release.IsEmpty())
  732. {
  733. Version = FORMAT("%s %s", (Version, Updates.Results.Release));
  734. }
  735. Message = FMTLOAD(NEW_VERSION3, (Version, "%s"));
  736. }
  737. else
  738. {
  739. Message = LoadStr(NO_NEW_VERSION) + "%s";
  740. }
  741. }
  742. if (!Updates.Results.Message.IsEmpty())
  743. {
  744. Message = FORMAT(Message,
  745. (FMTLOAD(UPDATE_MESSAGE,
  746. (StringReplace(Updates.Results.Message, "|", "\n", TReplaceFlags() << rfReplaceAll)))));
  747. }
  748. else
  749. {
  750. Message = FORMAT(Message, (""));
  751. }
  752. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  753. }
  754. else
  755. {
  756. New = false;
  757. }
  758. }
  759. //---------------------------------------------------------------------------
  760. void __fastcall CheckForUpdates(bool CachedResults)
  761. {
  762. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  763. Busy(true);
  764. try
  765. {
  766. if (ActiveForm)
  767. {
  768. assert(ActiveForm->Enabled);
  769. ActiveForm->Enabled = false;
  770. }
  771. bool Again = false;
  772. do
  773. {
  774. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  775. bool Cached = !Again && Updates.HaveResults &&
  776. (double(Updates.Period) > 0) &&
  777. (Updates.Results.ForVersion == Configuration->CompoundVersion) &&
  778. CachedResults;
  779. if (!Cached)
  780. {
  781. QueryUpdates();
  782. // reread enw data
  783. Updates = WinConfiguration->Updates;
  784. }
  785. Again = false;
  786. if (!Updates.ShownResults)
  787. {
  788. Updates.ShownResults = true;
  789. WinConfiguration->Updates = Updates;
  790. }
  791. assert(Updates.HaveResults);
  792. AnsiString Message;
  793. bool New;
  794. TQueryType Type;
  795. GetUpdatesMessage(Message, New, Type, true);
  796. // add FLAGMASK(Cached, qaRetry) to enable "check again" button
  797. // for cached results
  798. int Answers = qaOK |
  799. FLAGMASK(New, qaCancel | qaAll) |
  800. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  801. TQueryButtonAlias Aliases[4];
  802. Aliases[0].Button = qaRetry;
  803. Aliases[0].Alias = LoadStr(CHECK_AGAIN_BUTTON);
  804. Aliases[1].Button = qaYes;
  805. if (Updates.Results.UrlButton.IsEmpty())
  806. {
  807. Aliases[1].Alias = LoadStr(UPDATE_URL_BUTTON);
  808. }
  809. else
  810. {
  811. Aliases[1].Alias = Updates.Results.UrlButton;
  812. }
  813. Aliases[2].Button = qaAll;
  814. Aliases[2].Alias = LoadStr(WHATS_NEW_BUTTON);
  815. Aliases[3].Button = qaOK;
  816. Aliases[3].Alias = LoadStr(DOWNLOAD_BUTTON);
  817. TMessageParams Params;
  818. Params.Aliases = Aliases;
  819. // alias "ok" button to "download" only if we have new version
  820. Params.AliasesCount = (New ? 4 : 3);
  821. int Answer =
  822. MessageDialog(Message, Type,
  823. Answers, HELP_UPDATES, &Params);
  824. switch (Answer)
  825. {
  826. case qaOK:
  827. if (New)
  828. {
  829. OpenBrowser(LoadStr(DOWNLOAD_URL));
  830. }
  831. break;
  832. case qaYes:
  833. OpenBrowser(Updates.Results.Url);
  834. break;
  835. case qaAll:
  836. OpenBrowser(LoadStr(HISTORY_URL));
  837. break;
  838. case qaRetry:
  839. Again = true;
  840. break;
  841. }
  842. }
  843. while (Again);
  844. }
  845. __finally
  846. {
  847. if (ActiveForm)
  848. {
  849. ActiveForm->Enabled = true;
  850. }
  851. Busy(false);
  852. }
  853. }
  854. //---------------------------------------------------------------------------
  855. class TUpdateThread : public TCompThread
  856. {
  857. public:
  858. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  859. protected:
  860. virtual void __fastcall Execute();
  861. TThreadMethod FOnUpdatesChecked;
  862. };
  863. //---------------------------------------------------------------------------
  864. TUpdateThread * UpdateThread = NULL;
  865. //---------------------------------------------------------------------------
  866. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  867. TCompThread(false),
  868. FOnUpdatesChecked(OnUpdatesChecked)
  869. {
  870. }
  871. //---------------------------------------------------------------------------
  872. void __fastcall TUpdateThread::Execute()
  873. {
  874. try
  875. {
  876. QueryUpdates();
  877. if (FOnUpdatesChecked != NULL)
  878. {
  879. Synchronize(FOnUpdatesChecked);
  880. }
  881. }
  882. catch(...)
  883. {
  884. // ignore errors
  885. }
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  889. {
  890. assert(UpdateThread == NULL);
  891. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  892. }
  893. //---------------------------------------------------------------------------
  894. void __fastcall StopUpdateThread()
  895. {
  896. if (UpdateThread != NULL)
  897. {
  898. SAFE_DESTROY(UpdateThread);
  899. }
  900. }