1
0

Setup.cpp 97 KB

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