Setup.cpp 100 KB

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