Setup.cpp 99 KB

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