Setup.cpp 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697
  1. //---------------------------------------------------------------------------
  2. // Part of this code is
  3. // Copyright (C) 2002-2004, Marco Barisione <[email protected]>
  4. //---------------------------------------------------------------------------
  5. #include <vcl.h>
  6. #pragma hdrstop
  7. #include <stdio.h>
  8. #include <tchar.h>
  9. #include <shlobj.h>
  10. #include <tlhelp32.h>
  11. #include <Common.h>
  12. #include <CoreMain.h>
  13. #include <Exceptions.h>
  14. #include <TextsWin.h>
  15. #include <TextsCore.h>
  16. #include <HelpWin.h>
  17. #include <Http.h>
  18. #include <CompThread.hpp>
  19. #include <FileInfo.h>
  20. #include "WinConfiguration.h"
  21. #include "WinInterface.h"
  22. #include "Tools.h"
  23. #include "Setup.h"
  24. #include <StrUtils.hpp>
  25. #include "ProgParams.h"
  26. #include <Consts.hpp>
  27. #include <GUITools.h>
  28. #include <PuttyTools.h>
  29. #include <VCLCommon.h>
  30. #include <WebBrowserEx.hpp>
  31. #include <DateUtils.hpp>
  32. #include <OperationWithTimeout.hpp>
  33. #include <Soap.HTTPUtil.hpp>
  34. //---------------------------------------------------------------------------
  35. #define KEY _T("SYSTEM\\CurrentControlSet\\Control\\") \
  36. _T("Session Manager\\Environment")
  37. // when the PATH registry key is over aprox 2048 characters,
  38. // PATH as well as WINDIR variables are actually not set, breaking the system
  39. #define MAX_PATH_LEN 2000
  40. /* Command line options. */
  41. UnicodeString LastPathError;
  42. //---------------------------------------------------------------------------
  43. UnicodeString NetVersionStr;
  44. UnicodeString PowerShellVersionStr;
  45. //---------------------------------------------------------------------------
  46. // Display the error "err_msg".
  47. void err_out(LPCTSTR err_msg)
  48. {
  49. LastPathError = err_msg;
  50. }
  51. //---------------------------------------------------------------------------
  52. // Display "base_err_msg" followed by the description of the system error
  53. // identified by "sys_err".
  54. void err_out_sys(LPCTSTR base_err_msg, LONG sys_err)
  55. {
  56. LastPathError = FORMAT(L"%s %s", (base_err_msg, SysErrorMessage(sys_err)));
  57. }
  58. //---------------------------------------------------------------------------
  59. // Works as "strcmp" but the comparison is not case sensitive.
  60. int tcharicmp(LPCTSTR str1, LPCTSTR str2){
  61. for (; tolower(*str1) == tolower(*str2); ++str1, ++str2)
  62. if (*str1 == L'\0')
  63. return 0;
  64. return tolower(*str1) - tolower(*str2);
  65. }
  66. //---------------------------------------------------------------------------
  67. // Returns un unquoted copy of "str" (or a copy of "str" if the quotes are
  68. // not present). The returned value must be freed with "free".
  69. LPTSTR unquote(LPCTSTR str){
  70. int last_pos;
  71. LPTSTR ret;
  72. size_t new_len;
  73. last_pos = _tcslen(str) - 1;
  74. if (last_pos != -1 && str[0] == L'"' && str[last_pos] == L'"'){
  75. new_len= (_tcslen(str) - 1);
  76. ret = (LPTSTR)malloc(new_len * sizeof(TCHAR));
  77. lstrcpyn(ret, &str[1], new_len);
  78. }
  79. else
  80. ret = _tcsdup(str);
  81. return ret;
  82. }
  83. //---------------------------------------------------------------------------
  84. // Find "what" in the ";" separated string "str" and returns a pointer to
  85. // the first letter of "what" in the string. If "next" is not "NULL" it
  86. // points to the first letter after "what" (excluding the trailing ";").
  87. // If "what" isn't find the functions returns "NULL".
  88. LPTSTR find_reg_str(LPTSTR str, LPCTSTR what, LPTSTR * next){
  89. LPTSTR tok_buff;
  90. LPTSTR curr_tok;
  91. LPTSTR curr_tok_dup;
  92. BOOL path_eq;
  93. TCHAR sh_path1[MAX_PATH], sh_path2[MAX_PATH];
  94. int pos = -1;
  95. LPTSTR ret;
  96. tok_buff = _tcsdup(str);
  97. curr_tok = _tcstok(tok_buff, _T(";"));
  98. while (pos == -1 && curr_tok){
  99. curr_tok_dup = unquote(curr_tok);
  100. path_eq = GetShortPathName(what, sh_path1, LENOF(sh_path1)) &&
  101. GetShortPathName(curr_tok_dup, sh_path2,
  102. LENOF(sh_path2)) &&
  103. (tcharicmp(sh_path1, sh_path2) == 0);
  104. if (path_eq || tcharicmp(what, curr_tok_dup) == 0){
  105. pos = curr_tok - tok_buff;
  106. }
  107. free(curr_tok_dup);
  108. curr_tok = _tcstok(NULL, _T(";"));
  109. if (pos != -1 && next){
  110. if (curr_tok)
  111. *next = str + (curr_tok - tok_buff);
  112. else
  113. *next = str + _tcslen(str);
  114. }
  115. }
  116. free(tok_buff);
  117. if (pos != -1)
  118. ret = str + pos;
  119. else
  120. ret = NULL;
  121. return ret;
  122. }
  123. //---------------------------------------------------------------------------
  124. void path_reg_propagate()
  125. {
  126. DWORD send_message_result;
  127. LONG ret = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
  128. (LPARAM)_T("Environment"), SMTO_ABORTIFHUNG,
  129. 5000, &send_message_result);
  130. if (ret != ERROR_SUCCESS && GetLastError() != 0)
  131. {
  132. err_out_sys(_T("Cannot propagate the new enviroment to ")
  133. _T("other processes. The new value will be ")
  134. _T("avaible after a reboot."), GetLastError());
  135. SimpleErrorDialog(LastPathError);
  136. LastPathError = L"";
  137. }
  138. }
  139. //---------------------------------------------------------------------------
  140. // Add "path" to the registry. Return "TRUE" if the path has been added or
  141. // was already in the registry, "FALSE" otherwise.
  142. BOOL add_path_reg(LPCTSTR path){
  143. HKEY key;
  144. LONG ret;
  145. DWORD data_size;
  146. LPTSTR reg_str;
  147. BOOL func_ret = TRUE;
  148. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  149. KEY_WRITE | KEY_READ, &key);
  150. if (ret != ERROR_SUCCESS){
  151. err_out_sys(_T("Cannot open registry."), ret);
  152. return FALSE;
  153. }
  154. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  155. data_size += _tcslen(path) + 3 ; /* ";" and quotes, "data_size" already
  156. includes '\0'. */
  157. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  158. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL, (LPBYTE)reg_str,
  159. &data_size);
  160. if (ret != ERROR_SUCCESS){
  161. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  162. func_ret = FALSE;
  163. }
  164. else{
  165. if (!find_reg_str(reg_str, path, NULL)){
  166. _tcscat(reg_str, _T(";"));
  167. _tcscat(reg_str, path);
  168. size_t len = _tcslen(reg_str);
  169. if (len >= MAX_PATH_LEN)
  170. {
  171. err_out(LoadStr(PATH_ENV_TOO_LONG).c_str());
  172. func_ret = FALSE;
  173. }
  174. else
  175. {
  176. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  177. (LPBYTE)reg_str,
  178. (_tcslen(reg_str) + 1) * sizeof(TCHAR));
  179. if (ret != ERROR_SUCCESS){
  180. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  181. func_ret = FALSE;
  182. }
  183. /* Is this needed to make the new key avaible? */
  184. RegFlushKey(key);
  185. SetLastError(0);
  186. path_reg_propagate();
  187. }
  188. }
  189. }
  190. RegCloseKey(key);
  191. free(reg_str);
  192. return func_ret;
  193. }
  194. //---------------------------------------------------------------------------
  195. // Removes "path" from the registry. Return "TRUE" if the path has been
  196. // removed or it wasn't in the registry, "FALSE" otherwise.
  197. BOOL remove_path_reg(LPCTSTR path){
  198. HKEY key;
  199. LONG ret;
  200. DWORD data_size;
  201. LPTSTR reg_str;
  202. LPTSTR reg_str2;
  203. BOOL func_ret = TRUE;
  204. LPTSTR next;
  205. LPTSTR del_part;
  206. int last_pos;
  207. ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, KEY, 0,
  208. KEY_WRITE | KEY_READ, &key);
  209. if (ret != ERROR_SUCCESS){
  210. err_out_sys(_T("Cannot open registry."), ret);
  211. return FALSE;
  212. }
  213. RegQueryValueEx(key, _T("PATH"), NULL, NULL, NULL, &data_size);
  214. data_size += _tcslen(path) + 3; /* ";" and quotes,"data_size" already
  215. includes '\0'. */
  216. reg_str = (LPTSTR)malloc(data_size * sizeof(TCHAR));
  217. ret = RegQueryValueEx(key, _T("PATH"), NULL, NULL,
  218. (LPBYTE)reg_str, &data_size);
  219. if (ret != ERROR_SUCCESS){
  220. err_out_sys(_T("Cannot read \"PATH\" key."), ret);
  221. func_ret = FALSE;
  222. }
  223. else{
  224. if ((del_part = find_reg_str(reg_str, path, &next)) != NULL){
  225. reg_str2 = (LPTSTR)malloc((_tcslen(reg_str) + 1) * sizeof(TCHAR));
  226. *del_part = '\0';
  227. _stprintf(reg_str2, _T("%s%s"), reg_str, next);
  228. last_pos = _tcslen(reg_str2) - 1;
  229. if (last_pos != -1 && reg_str2[last_pos] == ';')
  230. reg_str2[last_pos] = '\0';
  231. ret = RegSetValueEx(key, _T("PATH"), 0, REG_EXPAND_SZ,
  232. (LPBYTE)reg_str2,
  233. (_tcslen(reg_str2) + 1) * sizeof(TCHAR));
  234. if (ret != ERROR_SUCCESS){
  235. err_out_sys(_T("Cannot write \"PATH\" key."), ret);
  236. func_ret = FALSE;
  237. }
  238. free(reg_str2);
  239. /* Is this needed to make the new key avaible? */
  240. RegFlushKey(key);
  241. SetLastError(0);
  242. path_reg_propagate();
  243. }
  244. }
  245. RegCloseKey(key);
  246. free(reg_str);
  247. return func_ret;
  248. }
  249. //---------------------------------------------------------------------------
  250. //---------------------------------------------------------------------------
  251. void __fastcall AddSearchPath(const UnicodeString Path)
  252. {
  253. if (!add_path_reg(Path.c_str()))
  254. {
  255. throw ExtException(FMTLOAD(ADD_PATH_ERROR, (Path)), LastPathError);
  256. }
  257. }
  258. //---------------------------------------------------------------------------
  259. void __fastcall RemoveSearchPath(const UnicodeString Path)
  260. {
  261. if (!remove_path_reg(Path.c_str()))
  262. {
  263. throw ExtException(FMTLOAD(REMOVE_PATH_ERROR, (Path)), LastPathError);
  264. }
  265. }
  266. //---------------------------------------------------------------------------
  267. static const UnicodeString SoftwareClassesBaseKey = L"Software\\Classes\\";
  268. //---------------------------------------------------------------------------
  269. static void __fastcall DeleteKeyIfEmpty(TRegistry * Registry, const UnicodeString & Key, bool AllowRootValues)
  270. {
  271. if (Registry->OpenKey(Key, false))
  272. {
  273. std::unique_ptr<TStrings> List(new TStringList());
  274. Registry->GetValueNames(List.get());
  275. bool CanDelete = true;
  276. for (int Index = 0; CanDelete && (Index < List->Count); Index++)
  277. {
  278. UnicodeString ValueName = List->Strings[Index];
  279. if (!AllowRootValues)
  280. {
  281. CanDelete = false;
  282. }
  283. if ((ValueName != L"") &&
  284. (ValueName != L"URL Protocol") &&
  285. (ValueName != L"EditFlags") &&
  286. (ValueName != L"BrowserFlags"))
  287. {
  288. CanDelete = false;
  289. }
  290. }
  291. List->Clear();
  292. Registry->GetKeyNames(List.get());
  293. Registry->CloseKey();
  294. if (CanDelete)
  295. {
  296. for (int Index = 0; Index < List->Count; Index++)
  297. {
  298. DeleteKeyIfEmpty(Registry, IncludeTrailingBackslash(Key) + List->Strings[Index], false);
  299. }
  300. // will fail, if not all subkeys got removed
  301. Registry->DeleteKey(Key);
  302. }
  303. }
  304. }
  305. //---------------------------------------------------------------------------
  306. static void __fastcall RegisterProtocol(TRegistry * Registry,
  307. const UnicodeString & Protocol, UnicodeString Description, bool Force)
  308. {
  309. if (Description.IsEmpty())
  310. {
  311. Description = FMTLOAD(PROTOCOL_URL_DESC, (Protocol));
  312. }
  313. UnicodeString ProtocolKey = SoftwareClassesBaseKey + Protocol;
  314. if (Force || !Registry->KeyExists(ProtocolKey))
  315. {
  316. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, true))
  317. {
  318. Registry->WriteString(L"", Description);
  319. Registry->WriteString(L"URL Protocol", L"");
  320. Registry->WriteInteger(L"EditFlags", 0x02);
  321. Registry->WriteInteger(L"BrowserFlags", 0x08);
  322. if (Registry->OpenKey(L"DefaultIcon", true))
  323. {
  324. Registry->WriteString(L"", FORMAT(L"\"%s\",0", (Application->ExeName)));
  325. Registry->CloseKey();
  326. }
  327. else
  328. {
  329. Abort();
  330. }
  331. }
  332. else
  333. {
  334. Abort();
  335. }
  336. }
  337. }
  338. //---------------------------------------------------------------------------
  339. static void __fastcall UnregisterProtocol(TRegistry * Registry,
  340. const UnicodeString & Protocol)
  341. {
  342. DeleteKeyIfEmpty(Registry, SoftwareClassesBaseKey + Protocol, true);
  343. }
  344. //---------------------------------------------------------------------------
  345. static TRegistry * __fastcall CreateRegistry(HKEY RootKey)
  346. {
  347. std::unique_ptr<TRegistry> Registry(new TRegistry());
  348. Registry->Access = KEY_WRITE | KEY_READ;
  349. Registry->RootKey = RootKey;
  350. return Registry.release();
  351. }
  352. //---------------------------------------------------------------------------
  353. static void __fastcall RegisterAsUrlHandler(HKEY RootKey,
  354. const UnicodeString & Protocol, UnicodeString Description = L"")
  355. {
  356. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  357. RegisterProtocol(Registry.get(), Protocol, Description, true);
  358. if (Registry->OpenKey(SoftwareClassesBaseKey + Protocol, false) &&
  359. Registry->OpenKey(L"shell", true) &&
  360. Registry->OpenKey(L"open", true) &&
  361. Registry->OpenKey(L"command", true))
  362. {
  363. Registry->WriteString(L"", FORMAT(L"\"%s\" %s \"%%1\"", (Application->ExeName, TProgramParams::FormatSwitch(UNSAFE_SWITCH))));
  364. Registry->CloseKey();
  365. }
  366. else
  367. {
  368. Abort();
  369. }
  370. }
  371. //---------------------------------------------------------------------------
  372. static void __fastcall RegisterAsUrlHandler(const UnicodeString & Protocol, UnicodeString Description = L"")
  373. {
  374. try
  375. {
  376. RegisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, Description);
  377. // get rid of any HKCU registraction that would overrite the HKLM one
  378. std::unique_ptr<TRegistry> Registry(CreateRegistry(HKEY_CURRENT_USER));
  379. if (Registry->KeyExists(SoftwareClassesBaseKey + Protocol))
  380. {
  381. Registry->DeleteKey(SoftwareClassesBaseKey + Protocol);
  382. }
  383. }
  384. catch (Exception & E)
  385. {
  386. try
  387. {
  388. RegisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, Description);
  389. }
  390. catch(Exception & E)
  391. {
  392. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  393. }
  394. }
  395. }
  396. //---------------------------------------------------------------------------
  397. static void __fastcall UnregisterAsUrlHandler(HKEY RootKey,
  398. const UnicodeString & Protocol, bool UnregisterProtocol, bool ForceHandlerUnregistration)
  399. {
  400. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  401. UnicodeString DefaultIconKey = SoftwareClassesBaseKey + Protocol + L"\\DefaultIcon";
  402. if (Registry->OpenKey(DefaultIconKey, false))
  403. {
  404. UnicodeString Value = Registry->ReadString(L"");
  405. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  406. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  407. {
  408. Registry->DeleteValue(L"");
  409. }
  410. Registry->CloseKey();
  411. DeleteKeyIfEmpty(Registry.get(), DefaultIconKey, false);
  412. }
  413. UnicodeString ShellKey = SoftwareClassesBaseKey + Protocol + L"\\shell";
  414. if (Registry->OpenKey(ShellKey + L"\\open\\command", false))
  415. {
  416. UnicodeString Value = Registry->ReadString(L"");
  417. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  418. if (ForceHandlerUnregistration || ContainsText(Value, ExeBaseName))
  419. {
  420. Registry->DeleteValue(L"");
  421. }
  422. Registry->CloseKey();
  423. DeleteKeyIfEmpty(Registry.get(), ShellKey, false);
  424. }
  425. if (UnregisterProtocol)
  426. {
  427. ::UnregisterProtocol(Registry.get(), Protocol);
  428. }
  429. }
  430. //---------------------------------------------------------------------------
  431. static void __fastcall UnregisterAsUrlHandler(const UnicodeString & Protocol, bool UnregisterProtocol)
  432. {
  433. UnregisterAsUrlHandler(HKEY_LOCAL_MACHINE, Protocol, UnregisterProtocol, false);
  434. UnregisterAsUrlHandler(HKEY_CURRENT_USER, Protocol, UnregisterProtocol, false);
  435. }
  436. //---------------------------------------------------------------------------
  437. static void __fastcall RegisterAsNonBrowserUrlHandler(const UnicodeString & Prefix)
  438. {
  439. RegisterAsUrlHandler(Prefix + SftpProtocol.UpperCase());
  440. RegisterAsUrlHandler(Prefix + ScpProtocol.UpperCase());
  441. RegisterAsUrlHandler(Prefix + WebDAVProtocol.UpperCase());
  442. RegisterAsUrlHandler(Prefix + WebDAVSProtocol.UpperCase());
  443. RegisterAsUrlHandler(Prefix + S3Protocol.UpperCase());
  444. }
  445. //---------------------------------------------------------------------------
  446. static void __fastcall UnregisterAsUrlHandlers(const UnicodeString & Prefix, bool UnregisterProtocol)
  447. {
  448. UnregisterAsUrlHandler(Prefix + SftpProtocol, UnregisterProtocol);
  449. UnregisterAsUrlHandler(Prefix + ScpProtocol, UnregisterProtocol);
  450. UnregisterAsUrlHandler(Prefix + WebDAVProtocol, UnregisterProtocol);
  451. UnregisterAsUrlHandler(Prefix + WebDAVSProtocol, UnregisterProtocol);
  452. UnregisterAsUrlHandler(Prefix + S3Protocol, UnregisterProtocol);
  453. }
  454. //---------------------------------------------------------------------------
  455. static const UnicodeString GenericUrlHandler(L"WinSCP.Url");
  456. //---------------------------------------------------------------------------
  457. static void __fastcall RegisterProtocolForDefaultPrograms(HKEY RootKey, const UnicodeString & Protocol)
  458. {
  459. // Register protocol, if it does not exist yet.
  460. // Prior to Windows 8, we need to register ourselves as legacy handler to
  461. // become the default handler. On Windows 8, it's automatic as long as no other
  462. // application is registered for the protocol (i.e. RegisterProtocol would be enough)
  463. RegisterAsUrlHandler(RootKey, Protocol);
  464. // see https://docs.microsoft.com/en-us/windows/desktop/shell/default-programs#registering-an-application-for-use-with-default-programs
  465. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  466. // create capabilities record
  467. // this has to be a separate branch from WinSCP one, as by its presence we
  468. // enforce registry storage usage, and the capabilities branch may exist
  469. // even if we are using INI file
  470. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  471. if (!Registry->OpenKey(CapabilitiesKey, true))
  472. {
  473. Abort();
  474. }
  475. UnicodeString Description = LoadStr(REGISTERED_APP_DESC3);
  476. Registry->WriteString(L"ApplicationDescription", Description);
  477. if (!Registry->OpenKey(L"UrlAssociations", true))
  478. {
  479. Abort();
  480. }
  481. Registry->WriteString(Protocol, GenericUrlHandler);
  482. Registry->CloseKey();
  483. // register application
  484. if (!Registry->OpenKey(L"Software\\RegisteredApplications", true))
  485. {
  486. Abort();
  487. }
  488. Registry->WriteString(AppNameString(), CapabilitiesKey);
  489. Registry->CloseKey();
  490. }
  491. //---------------------------------------------------------------------------
  492. static void __fastcall UnregisterProtocolForDefaultPrograms(HKEY RootKey,
  493. const UnicodeString & Protocol, bool ForceHandlerUnregistration)
  494. {
  495. std::unique_ptr<TRegistry> Registry(CreateRegistry(RootKey));
  496. // unregister the protocol
  497. UnregisterAsUrlHandler(RootKey, Protocol, false, ForceHandlerUnregistration);
  498. // remove capabilities record
  499. UnicodeString CapabilitiesKey = IncludeTrailingBackslash(GetCompanyRegistryKey()) + L"WinSCPCapabilities";
  500. UnicodeString UrlAssociationsKey = CapabilitiesKey + L"\\UrlAssociations";
  501. if (Registry->OpenKey(UrlAssociationsKey, false))
  502. {
  503. Registry->DeleteValue(Protocol);
  504. Registry->CloseKey();
  505. DeleteKeyIfEmpty(Registry.get(), UrlAssociationsKey, false);
  506. }
  507. if (Registry->OpenKey(CapabilitiesKey, false))
  508. {
  509. if (!Registry->HasSubKeys())
  510. {
  511. Registry->DeleteValue(L"ApplicationDescription");
  512. }
  513. Registry->CloseKey();
  514. DeleteKeyIfEmpty(Registry.get(), CapabilitiesKey, false);
  515. }
  516. if (!Registry->KeyExists(CapabilitiesKey))
  517. {
  518. // unregister application
  519. if (Registry->OpenKey(L"Software\\RegisteredApplications", false))
  520. {
  521. Registry->DeleteValue(AppNameString());
  522. Registry->CloseKey();
  523. }
  524. }
  525. }
  526. //---------------------------------------------------------------------------
  527. static void __fastcall RegisterProtocolsForDefaultPrograms(HKEY RootKey)
  528. {
  529. // register URL handler, if it does not exist yet
  530. RegisterAsUrlHandler(RootKey, GenericUrlHandler, L"WinSCP URL");
  531. RegisterProtocolForDefaultPrograms(RootKey, FtpProtocol);
  532. RegisterProtocolForDefaultPrograms(RootKey, FtpsProtocol);
  533. RegisterProtocolForDefaultPrograms(RootKey, FtpesProtocol);
  534. RegisterProtocolForDefaultPrograms(RootKey, SftpProtocol);
  535. RegisterProtocolForDefaultPrograms(RootKey, ScpProtocol);
  536. RegisterProtocolForDefaultPrograms(RootKey, SshProtocol);
  537. RegisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol);
  538. RegisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol);
  539. RegisterProtocolForDefaultPrograms(RootKey, S3Protocol);
  540. // deliberately not including http,
  541. // it's unlikely that anyone would like to change http handler
  542. // to non-browser application
  543. }
  544. //---------------------------------------------------------------------------
  545. static void __fastcall UnregisterProtocolsForDefaultPrograms(HKEY RootKey, bool ForceHandlerUnregistration)
  546. {
  547. UnregisterProtocolForDefaultPrograms(RootKey, FtpProtocol, ForceHandlerUnregistration);
  548. UnregisterProtocolForDefaultPrograms(RootKey, FtpsProtocol, ForceHandlerUnregistration);
  549. UnregisterProtocolForDefaultPrograms(RootKey, FtpesProtocol, ForceHandlerUnregistration);
  550. UnregisterProtocolForDefaultPrograms(RootKey, SftpProtocol, ForceHandlerUnregistration);
  551. UnregisterProtocolForDefaultPrograms(RootKey, ScpProtocol, ForceHandlerUnregistration);
  552. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVProtocol, ForceHandlerUnregistration);
  553. UnregisterProtocolForDefaultPrograms(RootKey, WebDAVSProtocol, ForceHandlerUnregistration);
  554. UnregisterProtocolForDefaultPrograms(RootKey, S3Protocol, ForceHandlerUnregistration);
  555. // we should not really need the "force" flag here, but why not
  556. UnregisterAsUrlHandler(RootKey, GenericUrlHandler, true, true);
  557. }
  558. //---------------------------------------------------------------------------
  559. static void __fastcall RegisterForDefaultPrograms()
  560. {
  561. try
  562. {
  563. RegisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE);
  564. // make sure we unregister any legacy protocol handler for CU,
  565. // this is needed for Windows Vista+7
  566. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, true);
  567. }
  568. catch (Exception & E)
  569. {
  570. try
  571. {
  572. // Maybe we should skip this if HKLM key existed already (we are running non-privileged)
  573. RegisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER);
  574. }
  575. catch (Exception & E)
  576. {
  577. throw ExtException(&E, LoadStr(REGISTER_URL_ERROR2));
  578. }
  579. }
  580. }
  581. //---------------------------------------------------------------------------
  582. static void __fastcall NotifyChangedAssociations()
  583. {
  584. SHChangeNotify(SHCNE_ASSOCCHANGED, 0, 0, 0);
  585. }
  586. //---------------------------------------------------------------------------
  587. void __fastcall RegisterForDefaultProtocols()
  588. {
  589. if (IsWinVista())
  590. {
  591. RegisterForDefaultPrograms();
  592. }
  593. else
  594. {
  595. RegisterAsNonBrowserUrlHandler(UnicodeString());
  596. }
  597. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  598. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  599. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  600. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  601. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  602. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  603. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  604. NotifyChangedAssociations();
  605. }
  606. //---------------------------------------------------------------------------
  607. void __fastcall UnregisterForProtocols()
  608. {
  609. UnregisterAsUrlHandlers(UnicodeString(), false);
  610. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  611. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  612. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  613. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  614. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  615. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  616. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  617. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  618. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  619. NotifyChangedAssociations();
  620. }
  621. //---------------------------------------------------------------------------
  622. void __fastcall LaunchAdvancedAssociationUI()
  623. {
  624. DebugAssert(IsWinVista());
  625. RegisterForDefaultPrograms();
  626. NotifyChangedAssociations();
  627. // sleep recommended by https://docs.microsoft.com/en-us/windows/desktop/shell/default-programs#becoming-the-default-browser
  628. Sleep(1000);
  629. if (IsWin10())
  630. {
  631. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  632. // https://stackoverflow.com/q/32178986/850848
  633. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  634. IOpenControlPanel * OpenControlPanel;
  635. HRESULT Result =
  636. CoCreateInstance(CLSID_OpenControlPanel,
  637. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  638. if (SUCCEEDED(Result))
  639. {
  640. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  641. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  642. OpenControlPanel->Release();
  643. }
  644. }
  645. else
  646. {
  647. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  648. HRESULT Result =
  649. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  650. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  651. if (SUCCEEDED(Result))
  652. {
  653. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  654. AppAssocRegUI->Release();
  655. }
  656. }
  657. }
  658. //---------------------------------------------------------------------------
  659. void __fastcall TemporaryDirectoryCleanup()
  660. {
  661. bool Continue = true;
  662. TStrings * Folders = NULL;
  663. try
  664. {
  665. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  666. {
  667. Folders = WinConfiguration->FindTemporaryFolders();
  668. Continue = (Folders != NULL);
  669. if (Continue)
  670. {
  671. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  672. TQueryButtonAlias Aliases[1];
  673. Aliases[0].Button = qaRetry;
  674. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  675. TMessageParams Params(mpNeverAskAgainCheck);
  676. Params.Aliases = Aliases;
  677. Params.AliasesCount = LENOF(Aliases);
  678. unsigned int Answer = MoreMessageDialog(
  679. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders,
  680. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  681. if (Answer == qaNeverAskAgain)
  682. {
  683. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  684. Answer = qaYes;
  685. }
  686. else if (Answer == qaRetry)
  687. {
  688. for (int Index = 0; Index < Folders->Count; Index++)
  689. {
  690. ShellExecute(Application->Handle, NULL,
  691. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  692. }
  693. }
  694. Continue = (Answer == qaYes);
  695. }
  696. }
  697. if (Continue)
  698. {
  699. try
  700. {
  701. WinConfiguration->CleanupTemporaryFolders(Folders);
  702. }
  703. catch (Exception &E)
  704. {
  705. ShowExtendedException(&E);
  706. }
  707. }
  708. }
  709. __finally
  710. {
  711. delete Folders;
  712. }
  713. }
  714. //-------------------------------------------- -------------------------------
  715. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  716. {
  717. int MajorVer = Version / (10000*100*100);
  718. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  719. int Release = (Version % (10000*100)) / (10000);
  720. UnicodeString Result;
  721. if (Release > 0)
  722. {
  723. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  724. }
  725. else
  726. {
  727. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  728. }
  729. return Result;
  730. }
  731. //---------------------------------------------------------------------------
  732. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  733. {
  734. int CurrentCompoundVer = Configuration->CompoundVersion;
  735. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  736. UnicodeString Medium = IsUWP() ? L"uwp" : L"app";
  737. // Beware that these parameters may get truncated if URL is too long,
  738. // such as with ERROR_REPORT_URL2
  739. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=%s&utm_campaign=%s", (Medium, Version));
  740. return AppendUrlParams(URL, Params);
  741. }
  742. //---------------------------------------------------------------------------
  743. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  744. {
  745. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  746. UnicodeString CurrentVersionStr =
  747. FORMAT(L"%d.%d.%d.%d",
  748. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  749. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  750. UnicodeString Params =
  751. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  752. (CurrentVersionStr,
  753. GUIConfiguration->AppliedLocaleHex,
  754. int(IsInstalled())));
  755. if (Configuration->IsUnofficial)
  756. {
  757. Params += L"&unofficial=1";
  758. }
  759. return AppendUrlParams(URL, Params);
  760. }
  761. //---------------------------------------------------------------------------
  762. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  763. {
  764. bool Beta;
  765. if (WinConfiguration->IsBeta)
  766. {
  767. Beta = true;
  768. }
  769. else
  770. {
  771. switch (WinConfiguration->Updates.BetaVersions)
  772. {
  773. case asAuto:
  774. Beta = WinConfiguration->AnyBetaInVersionHistory;
  775. break;
  776. case asOn:
  777. Beta = true;
  778. break;
  779. default:
  780. Beta = false;
  781. break;
  782. }
  783. }
  784. if (Beta || Force)
  785. {
  786. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  787. }
  788. return URL;
  789. }
  790. //---------------------------------------------------------------------------
  791. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  792. {
  793. std::unique_ptr<THttp> Http(new THttp());
  794. UnicodeString ProxyHost;
  795. int ProxyPort = 0;
  796. switch (Updates.ConnectionType)
  797. {
  798. case ctAuto:
  799. if (AutodetectProxy(ProxyHost, ProxyPort))
  800. {
  801. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  802. }
  803. break;
  804. case ctProxy:
  805. ProxyHost = Updates.ProxyHost;
  806. ProxyPort = Updates.ProxyPort;
  807. Configuration->Usage->Inc(L"UpdateProxyManual");
  808. break;
  809. }
  810. Http->ProxyHost = ProxyHost;
  811. Http->ProxyPort = ProxyPort;
  812. return Http.release();
  813. }
  814. //---------------------------------------------------------------------------
  815. THttp * __fastcall CreateHttp()
  816. {
  817. return CreateHttp(WinConfiguration->Updates);
  818. }
  819. //---------------------------------------------------------------------------
  820. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  821. {
  822. bool Complete = false;
  823. UnicodeString Response;
  824. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  825. try
  826. {
  827. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  828. URL = WantBetaUrl(URL, false);
  829. URL += L"&dotnet=" + Updates.DotNetVersion;
  830. URL += L"&console=" + Updates.ConsoleVersion;
  831. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  832. if (!LocaleVersion.IsEmpty())
  833. {
  834. URL += L"&localever=" + LocaleVersion;
  835. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  836. }
  837. if (!Updates.AuthenticationEmail.IsEmpty())
  838. {
  839. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  840. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  841. }
  842. CheckForUpdatesHTTP->URL = URL;
  843. // sanity check
  844. CheckForUpdatesHTTP->ResponseLimit = 102400;
  845. try
  846. {
  847. if (CollectUsage)
  848. {
  849. UnicodeString Usage = Configuration->Usage->Serialize();
  850. CheckForUpdatesHTTP->Post(Usage);
  851. }
  852. else
  853. {
  854. CheckForUpdatesHTTP->Get();
  855. }
  856. }
  857. catch (...)
  858. {
  859. if (CheckForUpdatesHTTP->IsCertificateError())
  860. {
  861. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  862. }
  863. throw;
  864. }
  865. Response = CheckForUpdatesHTTP->Response;
  866. }
  867. __finally
  868. {
  869. delete CheckForUpdatesHTTP;
  870. }
  871. int CurrentCompoundVer = Configuration->CompoundVersion;
  872. bool Changed = !Updates.HaveResults;
  873. Updates.LastCheck = Now();
  874. Updates.HaveResults = true;
  875. TUpdatesData PrevResults = Updates.Results;
  876. Updates.Results.Reset();
  877. Updates.Results.ForVersion = CurrentCompoundVer;
  878. while (!Response.IsEmpty())
  879. {
  880. UnicodeString Line = CutToChar(Response, L'\n', false);
  881. UnicodeString Name = CutToChar(Line, L'=', false);
  882. if (SameText(Name, "Version"))
  883. {
  884. int NewVersion = StrToCompoundVersion(Line);
  885. Changed |= (NewVersion != PrevResults.Version);
  886. if (NewVersion <= CurrentCompoundVer)
  887. {
  888. NewVersion = 0;
  889. }
  890. Updates.Results.Version = NewVersion;
  891. Complete = true;
  892. }
  893. else if (SameText(Name, L"Message"))
  894. {
  895. Changed |= (PrevResults.Message != Line);
  896. Updates.Results.Message = Line;
  897. }
  898. else if (SameText(Name, L"Critical"))
  899. {
  900. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  901. Changed |= (PrevResults.Critical != NewCritical);
  902. Updates.Results.Critical = NewCritical;
  903. }
  904. else if (SameText(Name, L"Release"))
  905. {
  906. Changed |= (PrevResults.Release != Line);
  907. Updates.Results.Release = Line;
  908. }
  909. else if (SameText(Name, L"Disabled"))
  910. {
  911. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  912. Changed |= (PrevResults.Disabled != NewDisabled);
  913. Updates.Results.Disabled = NewDisabled;
  914. Complete = true;
  915. }
  916. else if (SameText(Name, L"Url"))
  917. {
  918. Changed |= (PrevResults.Url != Line);
  919. Updates.Results.Url = Line;
  920. }
  921. else if (SameText(Name, L"UrlButton"))
  922. {
  923. Changed |= (PrevResults.UrlButton != Line);
  924. Updates.Results.UrlButton = Line;
  925. }
  926. else if (SameText(Name, L"NewsUrl"))
  927. {
  928. Changed |= (PrevResults.NewsUrl != Line);
  929. Updates.Results.NewsUrl = Line;
  930. }
  931. else if (SameText(Name, L"NewsSize"))
  932. {
  933. TSize NewsSize;
  934. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  935. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  936. Changed |= (PrevResults.NewsSize != NewsSize);
  937. Updates.Results.NewsSize = NewsSize;
  938. }
  939. else if (SameText(Name, L"DownloadUrl"))
  940. {
  941. Changed |= (PrevResults.DownloadUrl != Line);
  942. Updates.Results.DownloadUrl = Line;
  943. }
  944. else if (SameText(Name, L"DownloadSize"))
  945. {
  946. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  947. }
  948. else if (SameText(Name, L"DownloadSha256"))
  949. {
  950. Updates.Results.DownloadSha256 = Line;
  951. }
  952. else if (SameText(Name, L"AuthenticationError"))
  953. {
  954. Changed |= (PrevResults.AuthenticationError != Line);
  955. Updates.Results.AuthenticationError = Line;
  956. }
  957. else if (SameText(Name, L"OpenGettingStarted"))
  958. {
  959. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  960. }
  961. else if (SameText(Name, L"DownloadingUrl"))
  962. {
  963. Updates.Results.DownloadingUrl = Line;
  964. }
  965. else if (SameText(Name, L"TipsSize"))
  966. {
  967. TSize TipsSize;
  968. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  969. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  970. Updates.Results.TipsSize = TipsSize;
  971. }
  972. else if (SameText(Name, L"TipsUrl"))
  973. {
  974. Updates.Results.TipsUrl = Line;
  975. }
  976. else if (SameText(Name, L"Tips"))
  977. {
  978. Updates.Results.Tips = Line;
  979. }
  980. else if (SameText(Name, L"TipsIntervalDays"))
  981. {
  982. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  983. if (TipsIntervalDays < 0)
  984. {
  985. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  986. }
  987. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  988. }
  989. else if (SameText(Name, L"TipsIntervalRuns"))
  990. {
  991. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  992. if (TipsIntervalRuns < 0)
  993. {
  994. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  995. }
  996. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  997. }
  998. }
  999. if (Changed)
  1000. {
  1001. Updates.ShownResults = false;
  1002. }
  1003. return Complete;
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1007. {
  1008. return DoQueryUpdates(Updates, false);
  1009. }
  1010. //---------------------------------------------------------------------------
  1011. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1012. {
  1013. try
  1014. {
  1015. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1016. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1017. WinConfiguration->Updates = Updates;
  1018. if (!Complete)
  1019. {
  1020. EXCEPTION;
  1021. }
  1022. Configuration->Usage->Reset();
  1023. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1024. }
  1025. catch(Exception & E)
  1026. {
  1027. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1028. UnicodeString Message;
  1029. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1030. {
  1031. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1032. }
  1033. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1034. }
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. UnicodeString __fastcall FormatUpdatesMessage(UnicodeString Message)
  1038. {
  1039. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1040. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1041. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1042. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", LoadStr(UPDATE_MISSING_ADDRESS));
  1043. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1044. Message = ReplaceStr(Message, L"|", L"\n");
  1045. return Message;
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1049. TQueryType & Type, bool Force)
  1050. {
  1051. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1052. DebugAssert(Updates.HaveResults);
  1053. if (Updates.HaveResults)
  1054. {
  1055. if (Updates.Results.Disabled)
  1056. {
  1057. New = false;
  1058. if (Force)
  1059. {
  1060. Message = LoadStr(UPDATE_DISABLED);
  1061. }
  1062. }
  1063. else
  1064. {
  1065. New = (Updates.Results.Version > 0);
  1066. if (New)
  1067. {
  1068. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1069. if (!Updates.Results.Release.IsEmpty())
  1070. {
  1071. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1072. }
  1073. Message = FMTLOAD(NEW_VERSION4, (Version));
  1074. }
  1075. else
  1076. {
  1077. Message = LoadStr(NO_NEW_VERSION);
  1078. }
  1079. }
  1080. if (!Message.IsEmpty())
  1081. {
  1082. Message = MainInstructions(Message);
  1083. }
  1084. if (!Updates.Results.Message.IsEmpty())
  1085. {
  1086. Message +=
  1087. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.Message)));
  1088. }
  1089. if (!Updates.Results.AuthenticationError.IsEmpty())
  1090. {
  1091. Message +=
  1092. FMTLOAD(UPDATE_MESSAGE, (FormatUpdatesMessage(Updates.Results.AuthenticationError)));
  1093. }
  1094. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1095. }
  1096. else
  1097. {
  1098. New = false;
  1099. }
  1100. }
  1101. //---------------------------------------------------------------------------
  1102. UnicodeString __fastcall GetEnableAutomaticUpdatesUrl()
  1103. {
  1104. return AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1");
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. void __fastcall EnableAutomaticUpdates()
  1108. {
  1109. OpenBrowser(GetEnableAutomaticUpdatesUrl());
  1110. }
  1111. //---------------------------------------------------------------------------
  1112. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/, unsigned int & /*Answer*/)
  1113. {
  1114. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1115. OpenBrowser(LoadStr(HISTORY_URL));
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1119. {
  1120. return static_cast<int>(Size / 1024);
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. class TUpdateDownloadThread : public TCompThread
  1124. {
  1125. public:
  1126. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1127. virtual __fastcall ~TUpdateDownloadThread();
  1128. void __fastcall CancelClicked(TObject * Sender);
  1129. bool __fastcall CancelDownload();
  1130. __property bool Done = { read = FDone };
  1131. protected:
  1132. virtual void __fastcall Execute();
  1133. void __fastcall UpdateDownloaded();
  1134. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1135. void __fastcall UpdateProgress();
  1136. void __fastcall ShowException();
  1137. void __fastcall DownloadNotVerified();
  1138. void __fastcall CancelForm();
  1139. private:
  1140. TCustomForm * FForm;
  1141. TProgressBar * FProgressBar;
  1142. __int64 FDownloaded;
  1143. std::unique_ptr<Exception> FException;
  1144. std::unique_ptr<THttp> FHttp;
  1145. TUpdatesConfiguration FUpdates;
  1146. bool FDone;
  1147. };
  1148. //---------------------------------------------------------------------------
  1149. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1150. TCompThread(true)
  1151. {
  1152. // cache, as the progress bar miht be destroyed already when
  1153. // we need the form at the end of Execute()
  1154. FForm = GetParentForm(ProgressBar);
  1155. FProgressBar = ProgressBar;
  1156. // cache to prevent concurrency
  1157. FUpdates = WinConfiguration->Updates;
  1158. FDone = false;
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1162. {
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. void __fastcall TUpdateDownloadThread::Execute()
  1166. {
  1167. try
  1168. {
  1169. bool Retried = false;
  1170. bool Retry;
  1171. do
  1172. {
  1173. Retry = false;
  1174. try
  1175. {
  1176. FDownloaded = 0;
  1177. FHttp.reset(CreateHttp(FUpdates));
  1178. FHttp->URL = FUpdates.Results.DownloadUrl;
  1179. FHttp->OnDownload = HttpDownload;
  1180. FHttp->Get();
  1181. }
  1182. catch (EAbort &)
  1183. {
  1184. throw;
  1185. }
  1186. catch (Exception & E)
  1187. {
  1188. // The original URL failed, try to get a fresh one and retry
  1189. if (!Retried)
  1190. {
  1191. try
  1192. {
  1193. // Check if new update data (URL particlarly) is available
  1194. if (QueryUpdates(FUpdates) &&
  1195. !FUpdates.Results.DownloadUrl.IsEmpty())
  1196. {
  1197. Retry = true;
  1198. Retried = true;
  1199. }
  1200. }
  1201. catch (...)
  1202. {
  1203. }
  1204. }
  1205. if (!Retry)
  1206. {
  1207. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1208. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1209. }
  1210. }
  1211. }
  1212. while (Retry);
  1213. Synchronize(UpdateDownloaded);
  1214. }
  1215. catch (EAbort &)
  1216. {
  1217. // noop
  1218. }
  1219. catch (Exception & E)
  1220. {
  1221. Configuration->Usage->Inc(L"UpdateFailures");
  1222. FException.reset(CloneException(&E));
  1223. Synchronize(ShowException);
  1224. }
  1225. FDone = true;
  1226. Synchronize(CancelForm);
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. void __fastcall TUpdateDownloadThread::CancelForm()
  1230. {
  1231. FForm->ModalResult = mrCancel;
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1235. {
  1236. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1237. const char * Buffer = FHttp->ResponseRaw.c_str();
  1238. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1239. {
  1240. DownloadNotVerified();
  1241. }
  1242. UnicodeString Digest = Sha256(Buffer, Size);
  1243. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1244. {
  1245. DownloadNotVerified();
  1246. }
  1247. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1248. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1249. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1250. UnicodeString SetupPath = SetupPathBase;
  1251. int Index = 0;
  1252. while (FileExists(SetupPath))
  1253. {
  1254. Index++;
  1255. SetupPath =
  1256. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1257. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1258. }
  1259. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1260. FileStream->Write(Buffer, Size);
  1261. FileStream.reset(NULL);
  1262. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1263. if (FUpdates.Results.OpenGettingStarted)
  1264. {
  1265. Params += L" /OpenGettingStarted";
  1266. }
  1267. ExecuteShellChecked(SetupPath, Params);
  1268. Configuration->Usage->Inc(L"UpdateRuns");
  1269. TerminateApplication();
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1273. {
  1274. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1278. {
  1279. FDownloaded = Size;
  1280. Synchronize(UpdateProgress);
  1281. // Do not waste bandwidth, if something goes wrong
  1282. if (FDownloaded > FUpdates.Results.DownloadSize)
  1283. {
  1284. DownloadNotVerified();
  1285. }
  1286. if (Terminated)
  1287. {
  1288. Cancel = true;
  1289. }
  1290. }
  1291. //---------------------------------------------------------------------------
  1292. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1293. {
  1294. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TUpdateDownloadThread::ShowException()
  1298. {
  1299. DebugAssert(FException.get() != NULL);
  1300. ShowExtendedException(FException.get());
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1304. {
  1305. bool Result = !Terminated;
  1306. if (Result)
  1307. {
  1308. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1309. Terminate();
  1310. }
  1311. return Result;
  1312. }
  1313. //---------------------------------------------------------------------------
  1314. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1315. {
  1316. if (CancelDownload())
  1317. {
  1318. WaitFor();
  1319. }
  1320. }
  1321. //---------------------------------------------------------------------------
  1322. //---------------------------------------------------------------------------
  1323. class TUpdateDownloadData : public TComponent
  1324. {
  1325. public:
  1326. TUpdateDownloadThread * Thread;
  1327. __fastcall TUpdateDownloadData() :
  1328. TComponent(NULL)
  1329. {
  1330. }
  1331. virtual __fastcall ~TUpdateDownloadData()
  1332. {
  1333. // will stop the thread
  1334. delete Thread;
  1335. }
  1336. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1337. {
  1338. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1339. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1340. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1341. }
  1342. };
  1343. //---------------------------------------------------------------------------
  1344. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1345. {
  1346. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1347. // If the form was closed by CancelForm at the end of the thread, do nothing
  1348. if (!UpdateDownloadData->Thread->Done)
  1349. {
  1350. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1351. // May this should actually call CancelClicked?
  1352. if (UpdateDownloadData->Thread->CancelDownload())
  1353. {
  1354. Action = caNone;
  1355. }
  1356. }
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender, unsigned int & /*Answer*/)
  1360. {
  1361. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1362. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1363. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1364. TPanel * Panel = CreateBlankPanel(Form);
  1365. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1366. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1367. ProgressBar->Top = 0;
  1368. ProgressBar->Left = 0;
  1369. ProgressBar->Width = Panel->Width;
  1370. ProgressBar->Parent = Panel;
  1371. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1372. Panel->Height = ProgressBar->Height;
  1373. InsertPanelToMessageDialog(Form, Panel);
  1374. Button->Enabled = false;
  1375. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1376. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1377. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1378. // The form becomes owner of the thread (via TUpdateDownloadData),
  1379. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1380. // But it gets done only after the form controls are gone, and the thread
  1381. // might try to access them meanwhile. So we stop the thread explicitly.
  1382. CancelButton->OnClick = Thread->CancelClicked;
  1383. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1384. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1385. Data->Thread = Thread;
  1386. Form->InsertComponent(Data);
  1387. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1388. if (!DownloadingUrl.IsEmpty())
  1389. {
  1390. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1391. }
  1392. DebugAssert(Form->OnClose == NULL);
  1393. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1394. Thread->Resume();
  1395. }
  1396. //---------------------------------------------------------------------------
  1397. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1398. {
  1399. EnableAutomaticUpdates();
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1403. {
  1404. const UnicodeString DonatePanelName = L"DonatePanel";
  1405. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1406. // OnShow can happen multiple times, for example when showing dialog on start up (being main window)
  1407. if (FindComponentRecursively(Dialog, DonatePanelName) == NULL)
  1408. {
  1409. TPanel * Panel = CreateBlankPanel(Dialog);
  1410. Panel->Name = DonatePanelName;
  1411. Panel->Caption = UnicodeString(); // override default use of Name
  1412. TWebBrowserEx * DonateBrowser = CreateBrowserViewer(Panel, UnicodeString());
  1413. ReadyBrowserForStreaming(DonateBrowser);
  1414. WaitBrowserToIdle(DonateBrowser);
  1415. DonateBrowser->Height = ScaleByTextHeight(Dialog, 36);
  1416. DonateBrowser->Top = 0;
  1417. DonateBrowser->Left = 0;
  1418. Panel->Height = DonateBrowser->Height;
  1419. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1420. // (what should not happen)
  1421. InsertPanelToMessageDialog(Dialog, Panel);
  1422. UnicodeString DocumentBody = LoadStr(UPDATES_DONATE_HTML);
  1423. DocumentBody = ReplaceStr(DocumentBody, L"%DONATE_URL%", GetEnableAutomaticUpdatesUrl());
  1424. UnicodeString AboutStoreUrl = LoadStr(ABOUT_STORE_URL);
  1425. DocumentBody = ReplaceStr(DocumentBody, L"%STORE_URL%", AboutStoreUrl);
  1426. UnicodeString StoreButtonUrl = ProgramUrl(LoadStr(STORE_GET_IMG_URL));
  1427. StoreButtonUrl = HTMLEscape(StoreButtonUrl);
  1428. UnicodeString StoreButton =
  1429. FORMAT(L"<img src=\"%s\" style=\"height: 1.8em; vertical-align: -0.4em; padding-top: 0.2em; border: 0;\">", (StoreButtonUrl));
  1430. UnicodeString StoreUrl = FMTLOAD(STORE_URL, (L"update"));
  1431. UnicodeString StoreLink = FORMAT(L"<a href=\"%s\">%s</a>", (StoreUrl, StoreButton));
  1432. DocumentBody = ReplaceStr(DocumentBody, L"%GET_IMG% ", FORMAT(L"%s&nbsp;", (StoreLink)));
  1433. DocumentBody = FORMAT(L"<p>%s</p>", (DocumentBody));
  1434. UnicodeString Document = GenerateAppHtmlPage(Dialog->Font, Panel, DocumentBody, true);
  1435. LoadBrowserDocument(DonateBrowser, Document);
  1436. HideBrowserScrollbars(DonateBrowser);
  1437. }
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. bool __fastcall CheckForUpdates(bool CachedResults)
  1441. {
  1442. TCustomForm * ActiveForm = Screen->ActiveCustomForm;
  1443. bool Result = false;
  1444. TOperationVisualizer Visualizer;
  1445. try
  1446. {
  1447. if (ActiveForm)
  1448. {
  1449. DebugAssert(ActiveForm->Enabled);
  1450. ActiveForm->Enabled = false;
  1451. }
  1452. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1453. bool Cached =
  1454. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1455. CachedResults;
  1456. if (!Cached)
  1457. {
  1458. DoQueryUpdates(WinConfiguration->CollectUsage);
  1459. // reread new data
  1460. Updates = WinConfiguration->Updates;
  1461. }
  1462. if (!Updates.ShownResults)
  1463. {
  1464. Updates.ShownResults = true;
  1465. WinConfiguration->Updates = Updates;
  1466. }
  1467. DebugAssert(Updates.HaveResults);
  1468. UnicodeString Message;
  1469. bool New;
  1470. TQueryType Type;
  1471. GetUpdatesMessage(Message, New, Type, true);
  1472. Configuration->Usage->Inc(L"UpdateDisplays");
  1473. if (New)
  1474. {
  1475. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1476. }
  1477. if (Updates.HaveResults &&
  1478. (double(Updates.Period) > 0) &&
  1479. // do not show next check time, if we have new version info
  1480. !New)
  1481. {
  1482. Message += L"\n\n" +
  1483. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1484. }
  1485. int Answers = qaOK |
  1486. // show "what's new" button only when change list URL was not provided in results
  1487. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1488. FLAGMASK(New, qaCancel) |
  1489. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1490. TQueryButtonAlias Aliases[4];
  1491. Aliases[0].Button = qaYes;
  1492. if (Updates.Results.UrlButton.IsEmpty())
  1493. {
  1494. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1495. }
  1496. else
  1497. {
  1498. Aliases[0].Alias = Updates.Results.UrlButton;
  1499. }
  1500. Aliases[1].Button = qaAll;
  1501. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1502. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, OpenHistory);
  1503. Aliases[2].Button = qaCancel;
  1504. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1505. // Used only when New == true, see AliasesCount below
  1506. Aliases[3].Button = qaOK;
  1507. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1508. if (!Updates.Results.DownloadUrl.IsEmpty())
  1509. {
  1510. Aliases[3].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, DownloadUpdate);
  1511. Aliases[3].ElevationRequired = true;
  1512. }
  1513. TMessageParams Params;
  1514. Params.Aliases = Aliases;
  1515. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1516. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1517. // alias "ok" button to "upgrade" only if we have new version
  1518. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1519. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1520. if (New)
  1521. {
  1522. Params.ImageName = L"Installer";
  1523. }
  1524. std::unique_ptr<TForm> Dialog(
  1525. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1526. if (New)
  1527. {
  1528. // Internet Explorer on Windows XP cannot talk to CDN77, where we host Store Get button.
  1529. // As a simple solution, we just do not display the donation panel on Windows XP.
  1530. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled() && IsWinVista())
  1531. {
  1532. DebugAssert(Dialog->OnShow == NULL);
  1533. // InsertDonateLink need to be called only after MessageBrowser is created
  1534. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1535. }
  1536. }
  1537. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1538. switch (Answer)
  1539. {
  1540. case qaOK:
  1541. if (New)
  1542. {
  1543. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1544. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1545. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1546. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1547. OpenBrowser(UpgradeUrl);
  1548. Result = true;
  1549. }
  1550. break;
  1551. case qaYes:
  1552. OpenBrowser(Updates.Results.Url);
  1553. break;
  1554. case qaAll:
  1555. DebugFail();
  1556. break;
  1557. }
  1558. }
  1559. __finally
  1560. {
  1561. if (ActiveForm)
  1562. {
  1563. ActiveForm->Enabled = true;
  1564. }
  1565. }
  1566. return Result;
  1567. }
  1568. //---------------------------------------------------------------------------
  1569. class TUpdateThread : public TCompThread
  1570. {
  1571. public:
  1572. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1573. protected:
  1574. virtual void __fastcall Execute();
  1575. TThreadMethod FOnUpdatesChecked;
  1576. };
  1577. //---------------------------------------------------------------------------
  1578. TUpdateThread * UpdateThread = NULL;
  1579. //---------------------------------------------------------------------------
  1580. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1581. TCompThread(false),
  1582. FOnUpdatesChecked(OnUpdatesChecked)
  1583. {
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall TUpdateThread::Execute()
  1587. {
  1588. try
  1589. {
  1590. DoQueryUpdates(WinConfiguration->CollectUsage);
  1591. if (FOnUpdatesChecked != NULL)
  1592. {
  1593. Synchronize(FOnUpdatesChecked);
  1594. }
  1595. }
  1596. catch(...)
  1597. {
  1598. // ignore errors
  1599. }
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1603. {
  1604. DebugAssert(UpdateThread == NULL);
  1605. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1606. }
  1607. //---------------------------------------------------------------------------
  1608. void __fastcall StopUpdateThread()
  1609. {
  1610. if (UpdateThread != NULL)
  1611. {
  1612. SAFE_DESTROY(UpdateThread);
  1613. }
  1614. }
  1615. //---------------------------------------------------------------------------
  1616. void __fastcall SetupInitialize()
  1617. {
  1618. WinConfiguration->UpdateJumpList();
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1622. UnicodeString AdditionalParams, TStringList * Removed,
  1623. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1624. int IconIndex)
  1625. {
  1626. bool Result = false;
  1627. IObjectCollection * Collection = NULL;
  1628. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1629. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1630. {
  1631. try
  1632. {
  1633. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1634. int Count = 0;
  1635. for (int Index = 0; Index < Names->Count; Index++)
  1636. {
  1637. IShellLink * Link =
  1638. CreateDesktopSessionShortCut(
  1639. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1640. wchar_t Desc[2048];
  1641. if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1642. {
  1643. if (Removed->IndexOf(Desc) < 0)
  1644. {
  1645. try
  1646. {
  1647. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1648. Count++;
  1649. }
  1650. __finally
  1651. {
  1652. Link->Release();
  1653. }
  1654. }
  1655. else
  1656. {
  1657. Names->Delete(Index);
  1658. Index--;
  1659. }
  1660. }
  1661. }
  1662. if (Count > 0)
  1663. {
  1664. IObjectArray * Array;
  1665. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1666. {
  1667. try
  1668. {
  1669. Result = SUCCEEDED(
  1670. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1671. }
  1672. __finally
  1673. {
  1674. Array->Release();
  1675. }
  1676. }
  1677. }
  1678. }
  1679. __finally
  1680. {
  1681. Collection->Release();
  1682. }
  1683. }
  1684. return Result;
  1685. }
  1686. //---------------------------------------------------------------------------
  1687. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1688. {
  1689. ICustomDestinationList * DestinationList = NULL;
  1690. IObjectArray * RemovedArray;
  1691. TStringList * Removed = NULL;
  1692. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1693. try
  1694. {
  1695. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1696. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1697. {
  1698. unsigned int MinSlots;
  1699. HRESULT Result = DestinationListBeginList(DestinationList, MinSlots, IID_IObjectArray, reinterpret_cast<void *>(RemovedArray), 50000);
  1700. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1701. {
  1702. Removed = new TStringList();
  1703. unsigned int RemovedCount;
  1704. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1705. {
  1706. RemovedCount = 0;
  1707. }
  1708. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1709. {
  1710. IShellLink * Link;
  1711. wchar_t Desc[2048];
  1712. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1713. SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1714. {
  1715. Removed->Add(Desc);
  1716. }
  1717. }
  1718. AddJumpListCategory(
  1719. WorkspaceNames, L"", Removed, DestinationList,
  1720. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1721. AddJumpListCategory(
  1722. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1723. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1724. if (DestinationList != NULL)
  1725. {
  1726. DestinationList->CommitList();
  1727. }
  1728. }
  1729. }
  1730. }
  1731. __finally
  1732. {
  1733. SetErrorMode(OldErrMode);
  1734. if (DestinationList != NULL)
  1735. {
  1736. DestinationList->Release();
  1737. }
  1738. delete Removed;
  1739. }
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. bool __fastcall AnyOtherInstanceOfSelf()
  1743. {
  1744. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1745. bool Result = false;
  1746. try
  1747. {
  1748. unsigned int Process = GetCurrentProcessId();
  1749. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1750. PROCESSENTRY32 ProcessEntry;
  1751. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1752. if (Process32First(Snapshot, &ProcessEntry))
  1753. {
  1754. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1755. {
  1756. // we should check if the process is running in the same session,
  1757. // but for that we probably need some special privileges
  1758. if ((Process != ProcessEntry.th32ProcessID) &&
  1759. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1760. {
  1761. Result = true;
  1762. }
  1763. }
  1764. }
  1765. }
  1766. __finally
  1767. {
  1768. CloseHandle(Snapshot);
  1769. }
  1770. return Result;
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. static bool __fastcall DoIsInstalled(HKEY RootKey)
  1774. {
  1775. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1776. Registry->RootKey = RootKey;
  1777. bool Result =
  1778. Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false);
  1779. if (Result)
  1780. {
  1781. UnicodeString InstallPath = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1782. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1783. Result =
  1784. !InstallPath.IsEmpty() &&
  1785. IsPathToSameFile(ExePath, InstallPath);
  1786. }
  1787. return Result;
  1788. }
  1789. //---------------------------------------------------------------------------
  1790. bool __fastcall IsInstalled()
  1791. {
  1792. return
  1793. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1794. DoIsInstalled(HKEY_CURRENT_USER);
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. static TStringList * __fastcall TextToTipList(const UnicodeString & Text)
  1798. {
  1799. std::unique_ptr<TStringList> List(new TStringList());
  1800. List->CommaText = Text;
  1801. return List.release();
  1802. }
  1803. //---------------------------------------------------------------------------
  1804. UnicodeString __fastcall FirstUnshownTip()
  1805. {
  1806. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1807. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1808. Tips->CaseSensitive = false;
  1809. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1810. TipsSeen->CaseSensitive = false;
  1811. int LastTipSeen = -1;
  1812. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1813. {
  1814. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1815. if (TipIndex >= 0)
  1816. {
  1817. LastTipSeen = TipIndex;
  1818. }
  1819. }
  1820. UnicodeString Result;
  1821. if (LastTipSeen < Tips->Count - 1)
  1822. {
  1823. Result = Tips->Strings[LastTipSeen + 1];
  1824. }
  1825. return Result;
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. class TTipsData : public TComponent
  1829. {
  1830. public:
  1831. __fastcall TTipsData() :
  1832. TComponent(NULL)
  1833. {
  1834. }
  1835. int Index;
  1836. TStringList * Tips;
  1837. static TTipsData * __fastcall Retrieve(TObject * Object)
  1838. {
  1839. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1840. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1841. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1842. }
  1843. };
  1844. //---------------------------------------------------------------------------
  1845. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1846. {
  1847. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1848. }
  1849. //---------------------------------------------------------------------------
  1850. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  1851. {
  1852. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1853. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(YesButtonName)));
  1854. PrevButton->Enabled = (TipsData->Index > 0);
  1855. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  1856. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  1857. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(FindComponentRecursively(Form, MainMessageLabelName)));
  1858. MessageLabel->Caption = TipsMessage(TipsData);
  1859. }
  1860. //---------------------------------------------------------------------------
  1861. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  1862. {
  1863. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  1864. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  1865. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  1866. }
  1867. //---------------------------------------------------------------------------
  1868. static void __fastcall TipSeen(const UnicodeString & Tip)
  1869. {
  1870. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1871. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  1872. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  1873. WinConfiguration->TipsShown = Now();
  1874. WinConfiguration->RunsSinceLastTip = 0;
  1875. // prevent parallel app instances showing the same tip
  1876. WinConfiguration->Save();
  1877. }
  1878. //---------------------------------------------------------------------------
  1879. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender, unsigned int & /*Answer*/)
  1880. {
  1881. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  1882. TTipsData * TipsData = TTipsData::Retrieve(Form);
  1883. TipsData->Index += reinterpret_cast<int>(Data);
  1884. UpdateTipsForm(Form);
  1885. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  1886. UnicodeString Url = TipUrl(TipsData);
  1887. NavigateMessageDialogToUrl(Form, Url);
  1888. }
  1889. //---------------------------------------------------------------------------
  1890. static void __fastcall ShowTip(bool AutoShow)
  1891. {
  1892. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1893. UnicodeString Tip = FirstUnshownTip();
  1894. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1895. Tips->CaseSensitive = false;
  1896. int Index;
  1897. if (Tip.IsEmpty())
  1898. {
  1899. Index = Tips->Count - 1;
  1900. Tip = Tips->Strings[Index];
  1901. }
  1902. else
  1903. {
  1904. Index = Tips->IndexOf(Tip);
  1905. }
  1906. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  1907. TipsData->Name = TTipsData::QualifiedClassName();
  1908. TipsData->Index = Index;
  1909. TipsData->Tips = Tips.get();
  1910. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  1911. TQueryButtonAlias Aliases[3];
  1912. Aliases[0].Button = qaYes;
  1913. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  1914. Aliases[0].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  1915. Aliases[1].Button = qaNo;
  1916. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  1917. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  1918. Aliases[2].Button = qaCancel;
  1919. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  1920. TMessageParams Params;
  1921. Params.CustomCaption = LoadStr(TIPS_TITLE);
  1922. Params.MoreMessagesSize = Updates.Results.TipsSize;
  1923. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  1924. Params.Aliases = Aliases;
  1925. Params.AliasesCount = LENOF(Aliases);
  1926. Params.ImageName = L"Bulb On n p";
  1927. if (AutoShow)
  1928. {
  1929. // Won't be used automatically as we have more than the "OK" button
  1930. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  1931. Params.NeverAskAgainAnswer = qaCancel;
  1932. Params.Params |= mpNeverAskAgainCheck;
  1933. }
  1934. int Answers = qaYes | qaNo | qaCancel;
  1935. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  1936. Dialog->InsertComponent(TipsData.release());
  1937. UpdateTipsForm(Dialog.get());
  1938. TipSeen(Tip);
  1939. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1940. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  1941. {
  1942. WinConfiguration->ShowTips = false;
  1943. }
  1944. WinConfiguration->Updates = Updates;
  1945. }
  1946. //---------------------------------------------------------------------------
  1947. void __fastcall AutoShowNewTip()
  1948. {
  1949. Configuration->Usage->Inc(L"TipsShownAuto");
  1950. ShowTip(true);
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. void __fastcall ShowTips()
  1954. {
  1955. {
  1956. TOperationVisualizer Visualizer;
  1957. DoQueryUpdates(false);
  1958. }
  1959. if (WinConfiguration->Updates.Results.Tips.IsEmpty())
  1960. {
  1961. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  1962. }
  1963. Configuration->Usage->Inc(L"TipsShownCommand");
  1964. ShowTip(false);
  1965. }
  1966. //---------------------------------------------------------------------------
  1967. void __fastcall TipsUpdateStaticUsage()
  1968. {
  1969. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1970. std::unique_ptr<TStringList> Tips(TextToTipList(Updates.Results.Tips));
  1971. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  1972. std::unique_ptr<TStringList> TipsSeen(TextToTipList(WinConfiguration->TipsSeen));
  1973. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  1974. }
  1975. //---------------------------------------------------------------------------
  1976. static void ReadNetVersion(TRegistryStorage * Registry)
  1977. {
  1978. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  1979. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  1980. {
  1981. NetVersionStr = VersionStr;
  1982. }
  1983. }
  1984. //---------------------------------------------------------------------------
  1985. UnicodeString __fastcall GetNetVersionStr()
  1986. {
  1987. if (NetVersionStr.IsEmpty())
  1988. {
  1989. NetVersionStr = L"0"; // not to retry on failure
  1990. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  1991. if (Registry->OpenRootKey(false))
  1992. {
  1993. std::unique_ptr<TStringList> Keys(new TStringList());
  1994. Registry->GetSubKeyNames(Keys.get());
  1995. for (int Index = 0; Index < Keys->Count; Index++)
  1996. {
  1997. UnicodeString Key = Keys->Strings[Index];
  1998. if (Registry->OpenSubKey(Key, false))
  1999. {
  2000. ReadNetVersion(Registry.get());
  2001. if (Registry->OpenSubKey(L"Full", false))
  2002. {
  2003. ReadNetVersion(Registry.get());
  2004. Registry->CloseSubKey();
  2005. }
  2006. if (Registry->OpenSubKey(L"Client", false))
  2007. {
  2008. ReadNetVersion(Registry.get());
  2009. Registry->CloseSubKey();
  2010. }
  2011. Registry->CloseSubKey();
  2012. }
  2013. }
  2014. }
  2015. }
  2016. return NetVersionStr;
  2017. }
  2018. //---------------------------------------------------------------------------
  2019. UnicodeString __fastcall GetPowerShellVersionStr()
  2020. {
  2021. if (PowerShellVersionStr.IsEmpty())
  2022. {
  2023. PowerShellVersionStr = 0; // not to retry on failure
  2024. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2025. if (Registry->OpenRootKey(false))
  2026. {
  2027. std::unique_ptr<TStringList> Keys(new TStringList());
  2028. Registry->GetSubKeyNames(Keys.get());
  2029. for (int Index = 0; Index < Keys->Count; Index++)
  2030. {
  2031. UnicodeString Key = Keys->Strings[Index];
  2032. if (Registry->OpenSubKey(Key + L"\\PowerShellEngine", false, true))
  2033. {
  2034. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2035. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2036. {
  2037. PowerShellVersionStr = VersionStr;
  2038. }
  2039. Registry->CloseSubKey();
  2040. }
  2041. }
  2042. }
  2043. }
  2044. return PowerShellVersionStr;
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. //---------------------------------------------------------------------------
  2048. static void CollectCLSIDKey(
  2049. TConsole * Console, TStrings * Keys, int PlatformSet, TRegistryStorage * Storage, const UnicodeString & CLSID,
  2050. UnicodeString & CommonCodeBase, const UnicodeString & Platform, UnicodeString & Platforms)
  2051. {
  2052. UnicodeString CLSIDKey = FORMAT(L"CLSID\\%s", (CLSID));
  2053. if (Storage->OpenSubKey(CLSIDKey, false, true))
  2054. {
  2055. int Index = Keys->IndexOf(CLSIDKey);
  2056. if (Index >= 0)
  2057. {
  2058. Keys->Objects[Index] = reinterpret_cast<TObject *>(PlatformSet | reinterpret_cast<int>(Keys->Objects[Index]));
  2059. }
  2060. else
  2061. {
  2062. Keys->AddObject(CLSIDKey, reinterpret_cast<TObject *>(PlatformSet));
  2063. }
  2064. UnicodeString CodeBase;
  2065. if (Storage->OpenSubKey(L"InprocServer32", false))
  2066. {
  2067. CodeBase = Storage->ReadString(L"CodeBase", UnicodeString());
  2068. UnicodeString Assembly = Storage->ReadString(L"Assembly", UnicodeString());
  2069. UnicodeString Version;
  2070. if (!Assembly.IsEmpty())
  2071. {
  2072. UnicodeString VersionPrefix = L"Version=";
  2073. int P = Assembly.UpperCase().Pos(VersionPrefix.UpperCase());
  2074. if (P > 0)
  2075. {
  2076. Assembly.Delete(1, P + VersionPrefix.Length() - 1);
  2077. Version = CutToChar(Assembly, L',', true);
  2078. }
  2079. }
  2080. if (CodeBase.IsEmpty() || Version.IsEmpty())
  2081. {
  2082. Console->PrintLine(FORMAT(L"Warning: Could not find codebase and version for %s.", (CLSID)));
  2083. CodeBase = UnicodeString();
  2084. }
  2085. else
  2086. {
  2087. CodeBase = FORMAT(L"%s (%s)", (CodeBase, Version));
  2088. if (CommonCodeBase.IsEmpty())
  2089. {
  2090. Console->PrintLine(FORMAT(L"Codebase %s, unless stated otherwise", (CodeBase)));
  2091. CommonCodeBase = CodeBase;
  2092. }
  2093. if (SameText(CommonCodeBase, CodeBase))
  2094. {
  2095. CodeBase = L"";
  2096. }
  2097. }
  2098. Storage->CloseSubKey();
  2099. }
  2100. Storage->CloseSubKey();
  2101. UnicodeString Buf = Platform;
  2102. AddToList(Buf, CodeBase, L" - ");
  2103. AddToList(Platforms, Buf, ", ");
  2104. }
  2105. }
  2106. //---------------------------------------------------------------------------
  2107. static UnicodeString PlatformStr(int PlatformSet)
  2108. {
  2109. UnicodeString Result;
  2110. if (PlatformSet == 0)
  2111. {
  2112. Result = L"shared";
  2113. }
  2114. else
  2115. {
  2116. if (FLAGSET(PlatformSet, 32))
  2117. {
  2118. Result = L"32-bit";
  2119. }
  2120. if (FLAGSET(PlatformSet, 64))
  2121. {
  2122. AddToList(Result, L"64-bit", L", ");
  2123. }
  2124. }
  2125. return Result;
  2126. }
  2127. //---------------------------------------------------------------------------
  2128. static void DoCollectComRegistration(TConsole * Console, TStrings * Keys)
  2129. {
  2130. UnicodeString TypeLib = L"{A0B93468-D98A-4845-A234-8076229AD93F}"; // Duplicated in AssemblyInfo.cs
  2131. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT));
  2132. Storage->MungeStringValues = false;
  2133. Storage->AccessMode = smRead;
  2134. std::unique_ptr<TRegistryStorage> Storage64;
  2135. if (IsWin64())
  2136. {
  2137. Storage64.reset(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT, KEY_WOW64_64KEY));
  2138. Storage64->MungeStringValues = false;
  2139. Storage64->AccessMode = smRead;
  2140. }
  2141. // Classes, TypeLib and Record are shared between 32-bit and 64-bit registry view.
  2142. // 32-bit and 64-bit version of regasm adds CLSID keys to its respective view.
  2143. // Both 32-bit and 64-bit version of regasm seem to add Interface keys to both 32-bit and 64-bit views.
  2144. // On Vista, Interface keys are reflected (so when 32-bit keys is deleted, it's also deleted from 64-bit key,
  2145. // and we show an error, trying to delete the 64-bit key).
  2146. if (Storage->OpenRootKey(false))
  2147. {
  2148. Console->PrintLine(FORMAT(L"Versions of type library %s:", (TypeLib)));
  2149. UnicodeString TypeLibKey = FORMAT(L"TypeLib\\%s", (TypeLib));
  2150. if (Storage->OpenSubKey(TypeLibKey, false, true))
  2151. {
  2152. Keys->Add(TypeLibKey);
  2153. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2154. Storage->GetSubKeyNames(KeyNames.get());
  2155. if (KeyNames->Count == 0)
  2156. {
  2157. Console->PrintLine(L"Warning: The type library key exists, but no type libraries are present.");
  2158. }
  2159. else
  2160. {
  2161. for (int Index = 0; Index < KeyNames->Count; Index++)
  2162. {
  2163. UnicodeString Version = KeyNames->Strings[Index];
  2164. if (!Storage->OpenSubKey(FORMAT(L"%s\\0", (Version)), false, true))
  2165. {
  2166. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" cannot be opened.", (Version)));
  2167. }
  2168. else
  2169. {
  2170. std::unique_ptr<TStringList> Platforms(new TStringList());
  2171. Storage->GetSubKeyNames(Platforms.get());
  2172. if (Platforms->Count == 0)
  2173. {
  2174. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" exists, but platforms are present.", (Version)));
  2175. }
  2176. else
  2177. {
  2178. for (int Index2 = 0; Index2 < Platforms->Count; Index2++)
  2179. {
  2180. UnicodeString Platform = Platforms->Strings[Index2];
  2181. if (!Storage->OpenSubKey(Platform, false))
  2182. {
  2183. Console->PrintLine(FORMAT(L"Warning: Platform \"%s\" for type library \"%s\" cannot be opened.", (Platform, Version)));
  2184. }
  2185. else
  2186. {
  2187. UnicodeString TypeLibraryPath = Storage->ReadString(UnicodeString(), UnicodeString());
  2188. UnicodeString Exists = FileExists(TypeLibraryPath) ? L"exists" : L"does not exist";
  2189. Console->PrintLine(FORMAT(L"%s (%s): %s (%s)", (Version, Platform, TypeLibraryPath, Exists)));
  2190. Storage->CloseSubKey();
  2191. }
  2192. }
  2193. }
  2194. Storage->CloseSubKey();
  2195. }
  2196. }
  2197. }
  2198. Storage->CloseSubKey();
  2199. }
  2200. else
  2201. {
  2202. Console->PrintLine(L"Type library not registered.");
  2203. }
  2204. Console->PrintLine();
  2205. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2206. Storage->GetSubKeyNames(KeyNames.get());
  2207. UnicodeString NamespacePrefix = L"WinSCP.";
  2208. Console->PrintLine(L"Classes:");
  2209. UnicodeString CommonCodeBase;
  2210. int Found = 0;
  2211. for (int Index = 0; Index < KeyNames->Count; Index++)
  2212. {
  2213. UnicodeString KeyName = KeyNames->Strings[Index];
  2214. if (StartsText(NamespacePrefix, KeyName))
  2215. {
  2216. if (Storage->OpenSubKey(FORMAT(L"%s\\%s", (KeyName, L"CLSID")), false, true))
  2217. {
  2218. UnicodeString Class = KeyName;
  2219. UnicodeString CLSID = Trim(Storage->ReadString(UnicodeString(), UnicodeString()));
  2220. Storage->CloseSubKey();
  2221. if (!CLSID.IsEmpty())
  2222. {
  2223. Keys->Add(KeyName);
  2224. UnicodeString Platforms;
  2225. CollectCLSIDKey(Console, Keys, 32, Storage.get(), CLSID, CommonCodeBase, L"32-bit", Platforms);
  2226. if (Storage64.get() != NULL)
  2227. {
  2228. CollectCLSIDKey(Console, Keys, 64, Storage64.get(), CLSID, CommonCodeBase, L"64-bit", Platforms);
  2229. }
  2230. UnicodeString Line = FORMAT(L"%s - %s", (Class, CLSID));
  2231. if (Platforms.IsEmpty())
  2232. {
  2233. Console->PrintLine(FORMAT(L"Warning: Could not find CLSID %s for class %s.", (CLSID, Class)));
  2234. }
  2235. else
  2236. {
  2237. Line += FORMAT(L" [%s]", (Platforms));
  2238. }
  2239. Console->PrintLine(Line);
  2240. Found++;
  2241. }
  2242. }
  2243. }
  2244. }
  2245. if (Found == 0)
  2246. {
  2247. Console->PrintLine(L"No classes found.");
  2248. }
  2249. Console->PrintLine();
  2250. UnicodeString InterfaceKey = L"Interface";
  2251. if (Storage->OpenSubKey(InterfaceKey, false) &&
  2252. ((Storage64.get() == NULL) || Storage64->OpenSubKey(InterfaceKey, false)))
  2253. {
  2254. Console->PrintLine(L"Interfaces:");
  2255. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2256. Storage->GetSubKeyNames(KeyNames.get());
  2257. KeyNames->Sorted = true;
  2258. for (int Index = 0; Index < KeyNames->Count; Index++)
  2259. {
  2260. KeyNames->Objects[Index] = reinterpret_cast<TObject *>(32);
  2261. }
  2262. if (Storage64.get() != NULL)
  2263. {
  2264. std::unique_ptr<TStringList> KeyNames64(new TStringList());
  2265. Storage64->GetSubKeyNames(KeyNames64.get());
  2266. for (int Index = 0; Index < KeyNames64->Count; Index++)
  2267. {
  2268. UnicodeString Key64 = KeyNames64->Strings[Index];
  2269. int Index32 = KeyNames->IndexOf(Key64);
  2270. if (Index32 >= 0)
  2271. {
  2272. KeyNames->Objects[Index32] = reinterpret_cast<TObject *>(32 | 64);
  2273. }
  2274. else
  2275. {
  2276. KeyNames->AddObject(Key64, reinterpret_cast<TObject *>(64));
  2277. }
  2278. }
  2279. }
  2280. int Found = 0;
  2281. for (int Index = 0; Index < KeyNames->Count; Index++)
  2282. {
  2283. UnicodeString KeyName = KeyNames->Strings[Index];
  2284. // Open sub key first, to check if we are interested in the interface, as an optimization
  2285. int PlatformSet = reinterpret_cast<int>(KeyNames->Objects[Index]);
  2286. THierarchicalStorage * KeyStorage = FLAGSET(PlatformSet, 32) ? Storage.get() : Storage64.get();
  2287. if (KeyStorage->OpenSubKey(FORMAT(L"%s\\TypeLib", (KeyName)), false, true))
  2288. {
  2289. UnicodeString InterfaceTypeLib = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2290. UnicodeString Version = KeyStorage->ReadString(L"Version", UnicodeString());
  2291. KeyStorage->CloseSubKey();
  2292. if (SameText(InterfaceTypeLib, TypeLib))
  2293. {
  2294. if (KeyStorage->OpenSubKey(KeyName, false))
  2295. {
  2296. UnicodeString Key = ExcludeTrailingBackslash(KeyStorage->CurrentSubKey);
  2297. UnicodeString Interface = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2298. KeyStorage->CloseSubKey();
  2299. Keys->AddObject(Key, reinterpret_cast<TObject *>(PlatformSet));
  2300. Console->PrintLine(FORMAT(L"%s - %s (%s) [%s]", (Interface, KeyName, Version, PlatformStr(PlatformSet))));
  2301. Found++;
  2302. }
  2303. }
  2304. }
  2305. }
  2306. if (Found == 0)
  2307. {
  2308. Console->PrintLine(L"No interfaces found.");
  2309. }
  2310. Storage->CloseSubKey();
  2311. Console->PrintLine();
  2312. }
  2313. if (Storage->OpenSubKey(L"Record", false))
  2314. {
  2315. Console->PrintLine(L"Value types:");
  2316. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2317. Storage->GetSubKeyNames(KeyNames.get());
  2318. int Found = 0;
  2319. for (int Index = 0; Index < KeyNames->Count; Index++)
  2320. {
  2321. UnicodeString KeyName = KeyNames->Strings[Index];
  2322. if (Storage->OpenSubKey(KeyName, false))
  2323. {
  2324. std::unique_ptr<TStringList> Versions(new TStringList());
  2325. Storage->GetSubKeyNames(Versions.get());
  2326. UnicodeString VersionsStr;
  2327. std::unique_ptr<TStringList> Classes(CreateSortedStringList());
  2328. for (int Index2 = 0; Index2 < Versions->Count; Index2++)
  2329. {
  2330. UnicodeString Version = Versions->Strings[Index2];
  2331. if (Storage->OpenSubKey(Version, false))
  2332. {
  2333. UnicodeString Class = Storage->ReadString(L"Class", UnicodeString());
  2334. Classes->Add(Class);
  2335. if (StartsStr(NamespacePrefix, Class))
  2336. {
  2337. AddToList(VersionsStr, Version, L", ");
  2338. }
  2339. Storage->CloseSubKey();
  2340. }
  2341. }
  2342. if (!VersionsStr.IsEmpty())
  2343. {
  2344. if (Classes->Count != 1)
  2345. {
  2346. Console->PrintLine(FORMAT(L"Warning: Different class names for the same value type %s: %s", (KeyName, Classes->CommaText)));
  2347. }
  2348. else
  2349. {
  2350. Keys->Add(ExcludeTrailingBackslash(Storage->CurrentSubKey));
  2351. Console->PrintLine(FORMAT(L"%s - %s (%s)", (Classes->Strings[0], KeyName, VersionsStr)));
  2352. Found++;
  2353. }
  2354. }
  2355. Storage->CloseSubKey();
  2356. }
  2357. }
  2358. if (Found == 0)
  2359. {
  2360. Console->PrintLine(L"No value types found.");
  2361. }
  2362. Storage->CloseSubKey();
  2363. Console->PrintLine();
  2364. }
  2365. }
  2366. }
  2367. //---------------------------------------------------------------------------
  2368. bool DoUnregisterChoice(TConsole * Console)
  2369. {
  2370. return (Console->Choice(L"U", -1, -1, -1, 0, 0, 0, UnicodeString()) == 1);
  2371. }
  2372. //---------------------------------------------------------------------------
  2373. typedef HRESULT WINAPI (* RegDeleteTreeProc)(HKEY Key, LPCWSTR SubKey);
  2374. static RegDeleteTreeProc ARegDeleteTree = NULL;
  2375. //---------------------------------------------------------------------------
  2376. void DoDeleteKey(TConsole * Console, TRegistry * Registry, const UnicodeString & Key, int Platform, bool & AnyDeleted, bool & AllDeleted)
  2377. {
  2378. UnicodeString ParentKey = ExtractFileDir(Key);
  2379. UnicodeString ChildKey = ExtractFileName(Key);
  2380. bool Result = Registry->OpenKey(ParentKey, false);
  2381. if (Result)
  2382. {
  2383. if (DebugAlwaysFalse(ARegDeleteTree == NULL))
  2384. {
  2385. Result = false;
  2386. }
  2387. else
  2388. {
  2389. Result = (ARegDeleteTree(Registry->CurrentKey, ChildKey.c_str()) == 0);
  2390. }
  2391. Registry->CloseKey();
  2392. }
  2393. UnicodeString Status;
  2394. if (Result)
  2395. {
  2396. Status = L"removed";
  2397. AnyDeleted = true;
  2398. }
  2399. else
  2400. {
  2401. AllDeleted = false;
  2402. Status = L"NOT removed";
  2403. }
  2404. Console->PrintLine(FORMAT(L"%s [%s] - %s", (Key, PlatformStr(Platform), Status)));
  2405. }
  2406. //---------------------------------------------------------------------------
  2407. int ComRegistration(TConsole * Console)
  2408. {
  2409. int Result = RESULT_SUCCESS;
  2410. try
  2411. {
  2412. if (ARegDeleteTree == NULL)
  2413. {
  2414. HINSTANCE AdvapiLibrary = LoadLibrary(L"advapi32.dll");
  2415. if (DebugAlwaysTrue(AdvapiLibrary != NULL))
  2416. {
  2417. ARegDeleteTree = reinterpret_cast<RegDeleteTreeProc>(GetProcAddress(AdvapiLibrary, "RegDeleteTreeW"));
  2418. }
  2419. }
  2420. if (ARegDeleteTree == NULL)
  2421. {
  2422. throw Exception(FORMAT(L"Not supported on %s", (GetOSInfo())));
  2423. }
  2424. Console->PrintLine(GetEnvironmentInfo());
  2425. Console->PrintLine();
  2426. std::unique_ptr<TStrings> Keys(new TStringList());
  2427. DoCollectComRegistration(Console, Keys.get());
  2428. if (Keys->Count == 0)
  2429. {
  2430. Console->PrintLine(L"No registration found.");
  2431. Console->WaitBeforeExit();
  2432. }
  2433. else
  2434. {
  2435. Console->PrintLine(L"Press (U) to unregister or Esc to exit...");
  2436. if (DoUnregisterChoice(Console))
  2437. {
  2438. Console->PrintLine();
  2439. Console->PrintLine(L"The following registry keys will be removed from HKCR registry hive:");
  2440. for (int Index = 0; Index < Keys->Count; Index++)
  2441. {
  2442. Console->PrintLine(FORMAT(L"%s [%s]", (Keys->Strings[Index], PlatformStr(reinterpret_cast<int>(Keys->Objects[Index])))));
  2443. }
  2444. Console->PrintLine();
  2445. Console->PrintLine(L"You need Administrator privileges to remove the keys.");
  2446. Console->PrintLine(L"Press (U) again to proceed with unregistration or Esc to abort...");
  2447. if (DoUnregisterChoice(Console))
  2448. {
  2449. std::unique_ptr<TRegistry> Registry64(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_64KEY));
  2450. Registry64->RootKey = HKEY_CLASSES_ROOT;
  2451. std::unique_ptr<TRegistry> Registry32(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_32KEY));
  2452. Registry32->RootKey = HKEY_CLASSES_ROOT;
  2453. bool AnyDeleted = false;
  2454. bool AllDeleted = true;
  2455. for (int Index = 0; Index < Keys->Count; Index++)
  2456. {
  2457. UnicodeString Key = Keys->Strings[Index];
  2458. int PlatformSet = reinterpret_cast<int>(Keys->Objects[Index]);
  2459. if (PlatformSet == 0)
  2460. {
  2461. DoDeleteKey(Console, Registry32.get(), Key, 0, AnyDeleted, AllDeleted);
  2462. }
  2463. else
  2464. {
  2465. if (FLAGSET(PlatformSet, 32))
  2466. {
  2467. DoDeleteKey(Console, Registry32.get(), Key, 32, AnyDeleted, AllDeleted);
  2468. }
  2469. if (FLAGSET(PlatformSet, 64))
  2470. {
  2471. DoDeleteKey(Console, Registry64.get(), Key, 64, AnyDeleted, AllDeleted);
  2472. }
  2473. }
  2474. }
  2475. Console->PrintLine();
  2476. if (!AnyDeleted)
  2477. {
  2478. Console->PrintLine(L"No keys were removed. Make sure you have Administrator privileges.");
  2479. }
  2480. else if (!AllDeleted)
  2481. {
  2482. Console->PrintLine(L"Some keys were not removed. Make sure you have Administrator privileges.");
  2483. }
  2484. else
  2485. {
  2486. Console->PrintLine(L"All keys were removed. Unregistration succeeded.");
  2487. }
  2488. Console->WaitBeforeExit();
  2489. }
  2490. }
  2491. }
  2492. }
  2493. catch (Exception & E)
  2494. {
  2495. Result = HandleException(Console, E);
  2496. Console->WaitBeforeExit();
  2497. }
  2498. return Result;
  2499. }