Setup.cpp 95 KB

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