Setup.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946
  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. AppLog(L"Registering as default program");
  635. RegisterForDefaultPrograms();
  636. AppLog(L"Registering for non-browser protocols with prefix");
  637. RegisterAsNonBrowserUrlHandler(WinSCPProtocolPrefix);
  638. AppLog(L"Registering for browser protocols with prefix");
  639. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase());
  640. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase());
  641. RegisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase());
  642. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase());
  643. RegisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase());
  644. RegisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase());
  645. AppLog(L"Notifying about changes");
  646. NotifyChangedAssociations();
  647. AppLog(L"Registration done");
  648. }
  649. //---------------------------------------------------------------------------
  650. void __fastcall UnregisterForProtocols()
  651. {
  652. AppLog(L"Unregistering from handling protocol URL addresses");
  653. UnregisterAsUrlHandlers(UnicodeString(), false);
  654. UnregisterAsUrlHandlers(WinSCPProtocolPrefix, true);
  655. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpProtocol.UpperCase(), true);
  656. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpsProtocol.UpperCase(), true);
  657. UnregisterAsUrlHandler(WinSCPProtocolPrefix + FtpesProtocol.UpperCase(), true);
  658. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpProtocol.UpperCase(), true);
  659. UnregisterAsUrlHandler(WinSCPProtocolPrefix + HttpsProtocol.UpperCase(), true);
  660. UnregisterAsUrlHandler(WinSCPProtocolPrefix + SshProtocol.UpperCase(), true);
  661. UnregisterProtocolsForDefaultPrograms(HKEY_CURRENT_USER, false);
  662. UnregisterProtocolsForDefaultPrograms(HKEY_LOCAL_MACHINE, false);
  663. AppLog(L"Notifying about changes");
  664. NotifyChangedAssociations();
  665. AppLog(L"Unregistration done");
  666. }
  667. //---------------------------------------------------------------------------
  668. void __fastcall LaunchAdvancedAssociationUI()
  669. {
  670. RegisterForDefaultPrograms();
  671. NotifyChangedAssociations();
  672. // sleep recommended by https://learn.microsoft.com/en-us/windows/win32/shell/default-programs#becoming-the-default-browser
  673. Sleep(1000);
  674. if (IsWin10())
  675. {
  676. // WORKAROUND: On Windows 10, the IApplicationAssociationRegistrationUI::LaunchAdvancedAssociationUI does not work.
  677. // https://stackoverflow.com/q/32178986/850848
  678. // This approach (IOpenControlPanel::Open) works on Windows 7 too, but not on Windows Vista.
  679. IOpenControlPanel * OpenControlPanel;
  680. HRESULT Result =
  681. CoCreateInstance(CLSID_OpenControlPanel,
  682. NULL, CLSCTX_INPROC, __uuidof(IOpenControlPanel), (void**)&OpenControlPanel);
  683. if (SUCCEEDED(Result))
  684. {
  685. // This does not work anymore since April 2018 Update, it now has the same effect as mere "pageDefaultProgram".
  686. UnicodeString Page = FORMAT(L"pageDefaultProgram\\pageAdvancedSettings?pszAppName=%s", (AppNameString()));
  687. OpenControlPanel->Open(L"Microsoft.DefaultPrograms", Page.c_str(), NULL);
  688. OpenControlPanel->Release();
  689. }
  690. }
  691. else
  692. {
  693. IApplicationAssociationRegistrationUI * AppAssocRegUI;
  694. HRESULT Result =
  695. CoCreateInstance(CLSID_ApplicationAssociationRegistrationUI,
  696. NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistrationUI), (void**)&AppAssocRegUI);
  697. if (SUCCEEDED(Result))
  698. {
  699. AppAssocRegUI->LaunchAdvancedAssociationUI(AppNameString().c_str());
  700. AppAssocRegUI->Release();
  701. }
  702. }
  703. }
  704. //---------------------------------------------------------------------------
  705. void __fastcall TemporaryDirectoryCleanup()
  706. {
  707. std::unique_ptr<TStrings> Folders(WinConfiguration->FindTemporaryFolders());
  708. if (Folders.get() != NULL)
  709. {
  710. bool Continue = true;
  711. if (WinConfiguration->ConfirmTemporaryDirectoryCleanup)
  712. {
  713. Configuration->Usage->Inc(L"TemporaryDirectoryCleanupConfirmations");
  714. TQueryButtonAlias Aliases[1];
  715. Aliases[0].Button = qaRetry;
  716. Aliases[0].Alias = LoadStr(OPEN_BUTTON);
  717. TMessageParams Params(mpNeverAskAgainCheck);
  718. Params.Aliases = Aliases;
  719. Params.AliasesCount = LENOF(Aliases);
  720. unsigned int Answer = MoreMessageDialog(
  721. FMTLOAD(CLEANTEMP_CONFIRM2, (Folders->Count)), Folders.get(),
  722. qtConfirmation, qaYes | qaNo | qaRetry, HELP_CLEAN_TEMP_CONFIRM, &Params);
  723. if (Answer == qaNeverAskAgain)
  724. {
  725. WinConfiguration->ConfirmTemporaryDirectoryCleanup = false;
  726. Answer = qaYes;
  727. }
  728. else if (Answer == qaRetry)
  729. {
  730. for (int Index = 0; Index < Folders->Count; Index++)
  731. {
  732. ShellExecute(Application->Handle, NULL,
  733. Folders->Strings[Index].c_str(), NULL, NULL, SW_SHOWNORMAL);
  734. }
  735. }
  736. Continue = (Answer == qaYes);
  737. }
  738. if (Continue)
  739. {
  740. try
  741. {
  742. WinConfiguration->CleanupTemporaryFolders(Folders.get());
  743. }
  744. catch (Exception &E)
  745. {
  746. ShowExtendedException(&E);
  747. }
  748. }
  749. }
  750. }
  751. //-------------------------------------------- -------------------------------
  752. UnicodeString __fastcall VersionStrFromCompoundVersion(int Version)
  753. {
  754. int MajorVer = Version / (10000*100*100);
  755. int MinorVer = (Version % (10000*100*100)) / (10000*100);
  756. int Release = (Version % (10000*100)) / (10000);
  757. UnicodeString Result;
  758. if (Release > 0)
  759. {
  760. Result = FORMAT(L"%d.%d.%d", (MajorVer, MinorVer, Release));
  761. }
  762. else
  763. {
  764. Result = FORMAT(L"%d.%d", (MajorVer, MinorVer));
  765. }
  766. return Result;
  767. }
  768. //---------------------------------------------------------------------------
  769. UnicodeString __fastcall CampaignUrl(UnicodeString URL)
  770. {
  771. int CurrentCompoundVer = Configuration->CompoundVersion;
  772. UnicodeString Version = VersionStrFromCompoundVersion(CurrentCompoundVer);
  773. UnicodeString Medium = IsUWP() ? L"uwp" : L"app";
  774. // Beware that these parameters may get truncated if URL is too long,
  775. // such as with ERROR_REPORT_URL2
  776. UnicodeString Params = FORMAT(L"utm_source=winscp&utm_medium=%s&utm_campaign=%s", (Medium, Version));
  777. return AppendUrlParams(URL, Params);
  778. }
  779. //---------------------------------------------------------------------------
  780. UnicodeString __fastcall ProgramUrl(UnicodeString URL)
  781. {
  782. TVSFixedFileInfo * FileInfo = Configuration->FixedApplicationInfo;
  783. UnicodeString CurrentVersionStr =
  784. FORMAT(L"%d.%d.%d.%d",
  785. (HIWORD(FileInfo->dwFileVersionMS), LOWORD(FileInfo->dwFileVersionMS),
  786. HIWORD(FileInfo->dwFileVersionLS), LOWORD(FileInfo->dwFileVersionLS)));
  787. int IsInstalledFlag = (IsInstalled() ? 1 : (IsInstalledMsi() ? 2 : 0));
  788. UnicodeString Params =
  789. FORMAT(L"v=%s&lang=%s&isinstalled=%d",
  790. (CurrentVersionStr,
  791. GUIConfiguration->AppliedLocaleHex,
  792. IsInstalledFlag));
  793. if (Configuration->IsUnofficial)
  794. {
  795. Params += L"&unofficial=1";
  796. }
  797. return AppendUrlParams(URL, Params);
  798. }
  799. //---------------------------------------------------------------------------
  800. static UnicodeString __fastcall WantBetaUrl(UnicodeString URL, bool Force)
  801. {
  802. bool Beta;
  803. if (WinConfiguration->IsBeta)
  804. {
  805. Beta = true;
  806. }
  807. else
  808. {
  809. switch (WinConfiguration->Updates.BetaVersions)
  810. {
  811. case asAuto:
  812. Beta = WinConfiguration->AnyBetaInVersionHistory;
  813. break;
  814. case asOn:
  815. Beta = true;
  816. break;
  817. default:
  818. Beta = false;
  819. break;
  820. }
  821. }
  822. if (Beta || Force)
  823. {
  824. URL = AppendUrlParams(URL, FORMAT(L"beta=%d", (Beta ? 1 : 0)));
  825. }
  826. return URL;
  827. }
  828. //---------------------------------------------------------------------------
  829. static THttp * __fastcall CreateHttp(const TUpdatesConfiguration & Updates)
  830. {
  831. std::unique_ptr<THttp> Http(new THttp());
  832. UnicodeString ProxyHost;
  833. int ProxyPort = 0;
  834. switch (Updates.ConnectionType)
  835. {
  836. case ctAuto:
  837. if (AutodetectProxy(ProxyHost, ProxyPort))
  838. {
  839. Configuration->Usage->Inc(L"UpdateProxyAutodetected");
  840. }
  841. break;
  842. case ctProxy:
  843. ProxyHost = Updates.ProxyHost;
  844. ProxyPort = Updates.ProxyPort;
  845. Configuration->Usage->Inc(L"UpdateProxyManual");
  846. break;
  847. }
  848. if (!ProxyHost.IsEmpty())
  849. {
  850. AppLogFmt("Using proxy: %s:%d", (ProxyHost, ProxyPort));
  851. }
  852. Http->ProxyHost = ProxyHost;
  853. Http->ProxyPort = ProxyPort;
  854. return Http.release();
  855. }
  856. //---------------------------------------------------------------------------
  857. THttp * __fastcall CreateHttp()
  858. {
  859. return CreateHttp(WinConfiguration->Updates);
  860. }
  861. //---------------------------------------------------------------------------
  862. UnicodeString GetUpdatesCertificate()
  863. {
  864. UnicodeString Result = ReadResource(L"UPDATES_ROOT_CA");
  865. Result = ReplaceStr(Result, L"-----BEGIN CERTIFICATE-----", EmptyStr);
  866. Result = ReplaceStr(Result, L"-----END CERTIFICATE-----", EmptyStr);
  867. Result = ReplaceStr(Result, L"\n", EmptyStr);
  868. Result = ReplaceStr(Result, L"\r", EmptyStr);
  869. return Result;
  870. }
  871. //---------------------------------------------------------------------------
  872. static bool __fastcall DoQueryUpdates(TUpdatesConfiguration & Updates, bool CollectUsage)
  873. {
  874. bool Complete = false;
  875. UnicodeString Response;
  876. THttp * CheckForUpdatesHTTP = CreateHttp(Updates);
  877. try
  878. {
  879. UnicodeString URL = ProgramUrl(LoadStr(UPDATES_URL));
  880. URL = WantBetaUrl(URL, false);
  881. URL += L"&dotnet=" + Updates.DotNetVersion;
  882. URL += L"&console=" + Updates.ConsoleVersion;
  883. UnicodeString LocaleVersion = WinConfiguration->AppliedLocaleVersion();
  884. if (!LocaleVersion.IsEmpty())
  885. {
  886. URL += L"&localever=" + LocaleVersion;
  887. URL += L"&localecompl=" + LoadStr(TRANSLATION_COMPLETENESS);
  888. }
  889. URL += L"&firstrun=" + EncodeUrlString(WinConfiguration->FirstRun);
  890. if (!IsUWP())
  891. {
  892. // Even if donor email is inherited from normal installation,
  893. // do not use it as this all is merely to report usage statistics, not to check for updates, in UWP.
  894. if (!Updates.AuthenticationEmail.IsEmpty())
  895. {
  896. RawByteString AuthenticationEmailBuf = RawByteString(UTF8String(Updates.AuthenticationEmail.LowerCase()));
  897. URL += L"&authentication=" + Sha256(AuthenticationEmailBuf.c_str(), AuthenticationEmailBuf.Length()).LowerCase();
  898. }
  899. }
  900. else
  901. {
  902. URL += L"&package=" + EncodeUrlString(GetPackageName());
  903. }
  904. if (!Updates.Mode.IsEmpty())
  905. {
  906. URL += L"&mode=" + EncodeUrlString(Updates.Mode);
  907. }
  908. AppLogFmt(L"Updates check URL: %s", (URL));
  909. CheckForUpdatesHTTP->URL = URL;
  910. // sanity check
  911. CheckForUpdatesHTTP->ResponseLimit = BasicHttpResponseLimit;
  912. CheckForUpdatesHTTP->Certificate = GetUpdatesCertificate();
  913. try
  914. {
  915. if (CollectUsage)
  916. {
  917. UnicodeString Usage = Configuration->Usage->Serialize();
  918. CheckForUpdatesHTTP->Post(Usage);
  919. }
  920. else
  921. {
  922. CheckForUpdatesHTTP->Get();
  923. }
  924. }
  925. catch (...)
  926. {
  927. if (CheckForUpdatesHTTP->IsCertificateError())
  928. {
  929. AppLog(L"Certificate error detected.");
  930. Configuration->Usage->Inc(L"UpdateCertificateErrors");
  931. }
  932. throw;
  933. }
  934. Response = CheckForUpdatesHTTP->Response;
  935. AppLogFmt(L"Updates check response: %s", (Response));
  936. }
  937. __finally
  938. {
  939. delete CheckForUpdatesHTTP;
  940. }
  941. int CurrentCompoundVer = Configuration->CompoundVersion;
  942. bool Changed = !Updates.HaveResults;
  943. Updates.LastCheck = Now();
  944. Updates.HaveResults = true;
  945. TUpdatesData PrevResults = Updates.Results;
  946. Updates.Results.Reset();
  947. Updates.Results.ForVersion = CurrentCompoundVer;
  948. while (!Response.IsEmpty())
  949. {
  950. UnicodeString Line = CutToChar(Response, L'\n', false);
  951. UnicodeString Name = CutToChar(Line, L'=', false);
  952. if (SameText(Name, "Version"))
  953. {
  954. int NewVersion = StrToCompoundVersion(Line);
  955. Changed |= (NewVersion != PrevResults.Version);
  956. if (NewVersion <= CurrentCompoundVer)
  957. {
  958. NewVersion = 0;
  959. }
  960. Updates.Results.Version = NewVersion;
  961. Complete = true;
  962. }
  963. else if (SameText(Name, L"Message"))
  964. {
  965. Changed |= (PrevResults.Message != Line);
  966. Updates.Results.Message = Line;
  967. }
  968. else if (SameText(Name, L"Critical"))
  969. {
  970. bool NewCritical = (StrToIntDef(Line, 0) != 0);
  971. Changed |= (PrevResults.Critical != NewCritical);
  972. Updates.Results.Critical = NewCritical;
  973. }
  974. else if (SameText(Name, L"Release"))
  975. {
  976. Changed |= (PrevResults.Release != Line);
  977. Updates.Results.Release = Line;
  978. }
  979. else if (SameText(Name, L"Disabled"))
  980. {
  981. bool NewDisabled = (StrToIntDef(Line, 0) != 0);
  982. Changed |= (PrevResults.Disabled != NewDisabled);
  983. Updates.Results.Disabled = NewDisabled;
  984. Complete = true;
  985. }
  986. else if (SameText(Name, L"Url"))
  987. {
  988. Changed |= (PrevResults.Url != Line);
  989. Updates.Results.Url = Line;
  990. }
  991. else if (SameText(Name, L"UrlButton"))
  992. {
  993. Changed |= (PrevResults.UrlButton != Line);
  994. Updates.Results.UrlButton = Line;
  995. }
  996. else if (SameText(Name, L"NewsUrl"))
  997. {
  998. Changed |= (PrevResults.NewsUrl != Line);
  999. Updates.Results.NewsUrl = Line;
  1000. }
  1001. else if (SameText(Name, L"NewsSize"))
  1002. {
  1003. TSize NewsSize;
  1004. NewsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  1005. NewsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  1006. Changed |= (PrevResults.NewsSize != NewsSize);
  1007. Updates.Results.NewsSize = NewsSize;
  1008. }
  1009. else if (SameText(Name, L"DownloadUrl"))
  1010. {
  1011. Changed |= (PrevResults.DownloadUrl != Line);
  1012. Updates.Results.DownloadUrl = Line;
  1013. }
  1014. else if (SameText(Name, L"DownloadSize"))
  1015. {
  1016. Updates.Results.DownloadSize = StrToInt64Def(Line, 0);
  1017. }
  1018. else if (SameText(Name, L"DownloadSha256"))
  1019. {
  1020. Updates.Results.DownloadSha256 = Line;
  1021. }
  1022. else if (SameText(Name, L"AuthenticationError"))
  1023. {
  1024. Changed |= (PrevResults.AuthenticationError != Line);
  1025. Updates.Results.AuthenticationError = Line;
  1026. }
  1027. else if (SameText(Name, L"OpenGettingStarted"))
  1028. {
  1029. Updates.Results.OpenGettingStarted = (StrToIntDef(Line, 0) != 0);
  1030. }
  1031. else if (SameText(Name, L"DownloadingUrl"))
  1032. {
  1033. Updates.Results.DownloadingUrl = Line;
  1034. }
  1035. else if (SameText(Name, L"TipsSize"))
  1036. {
  1037. TSize TipsSize;
  1038. TipsSize.Width = StrToIntDef(CutToChar(Line, L',', true), 0);
  1039. TipsSize.Height = StrToIntDef(CutToChar(Line, L',', true), 0);
  1040. Updates.Results.TipsSize = TipsSize;
  1041. }
  1042. else if (SameText(Name, L"TipsUrl"))
  1043. {
  1044. Updates.Results.TipsUrl = Line;
  1045. }
  1046. else if (SameText(Name, L"Tips"))
  1047. {
  1048. Updates.Results.Tips = Line;
  1049. }
  1050. else if (SameText(Name, L"TipsIntervalDays"))
  1051. {
  1052. int TipsIntervalDays = StrToIntDef(Line, Updates.Results.TipsIntervalDays);
  1053. if (TipsIntervalDays < 0)
  1054. {
  1055. TipsIntervalDays = Updates.Results.TipsIntervalDays;
  1056. }
  1057. Updates.Results.TipsIntervalDays = TipsIntervalDays;
  1058. }
  1059. else if (SameText(Name, L"TipsIntervalRuns"))
  1060. {
  1061. int TipsIntervalRuns = StrToIntDef(Line, Updates.Results.TipsIntervalRuns);
  1062. if (TipsIntervalRuns < 0)
  1063. {
  1064. TipsIntervalRuns = Updates.Results.TipsIntervalRuns;
  1065. }
  1066. Updates.Results.TipsIntervalRuns = TipsIntervalRuns;
  1067. }
  1068. }
  1069. if (Changed)
  1070. {
  1071. Updates.ShownResults = false;
  1072. }
  1073. return Complete;
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. bool __fastcall QueryUpdates(TUpdatesConfiguration & Updates)
  1077. {
  1078. return DoQueryUpdates(Updates, false);
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. static void __fastcall DoQueryUpdates(bool CollectUsage)
  1082. {
  1083. try
  1084. {
  1085. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1086. bool Complete = DoQueryUpdates(Updates, CollectUsage);
  1087. WinConfiguration->Updates = Updates;
  1088. if (!Complete)
  1089. {
  1090. EXCEPTION;
  1091. }
  1092. Configuration->Usage->Reset();
  1093. Configuration->Usage->Inc(L"UpdateChecksSucceeded");
  1094. }
  1095. catch(Exception & E)
  1096. {
  1097. Configuration->Usage->Inc(L"UpdateChecksFailed");
  1098. UnicodeString Message;
  1099. if (DebugAlwaysTrue(ExceptionFullMessage(&E, Message)))
  1100. {
  1101. Configuration->Usage->Set(LastUpdateExceptionCounter, Message);
  1102. }
  1103. throw ExtException(&E, MainInstructions(LoadStr(CHECK_FOR_UPDATES_ERROR)));
  1104. }
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. void FormatUpdatesMessage(
  1108. UnicodeString & UpdatesMessage, const UnicodeString & AMessage, const TUpdatesConfiguration & Updates)
  1109. {
  1110. UnicodeString Message = AMessage;
  1111. Message = ReplaceStr(Message, "%UPDATE_UNAUTHORIZED%", LoadStr(UPDATE_UNAUTHORIZED));
  1112. Message = ReplaceStr(Message, "%UPDATE_EXPIRED%", LoadStr(UPDATE_EXPIRED));
  1113. Message = ReplaceStr(Message, "%UPDATE_TOO_MANY%", LoadStr(UPDATE_TOO_MANY));
  1114. UnicodeString Buf = LoadStr(UPDATE_MISSING_ADDRESS2);
  1115. if (!Updates.AuthenticationEmail.IsEmpty())
  1116. {
  1117. Buf += L"\n\n" + FMTLOAD(UPDATE_MISSING_ADDRESS3, (Updates.AuthenticationEmail, L"WinSCP donation receipt"));
  1118. }
  1119. Message = ReplaceStr(Message, "%UPDATE_MISSING_ADDRESS%", Buf);
  1120. Message = ReplaceStr(Message, "%UPDATE_TOO_LOW%", LoadStr(UPDATE_TOO_LOW));
  1121. Message = ReplaceStr(Message, L"|", L"\n");
  1122. if (!Message.IsEmpty())
  1123. {
  1124. UpdatesMessage = TrimRight(UpdatesMessage);
  1125. if (!UpdatesMessage.IsEmpty())
  1126. {
  1127. UpdatesMessage += L"\n \n";
  1128. }
  1129. UpdatesMessage += Message;
  1130. }
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. void __fastcall GetUpdatesMessage(UnicodeString & Message, bool & New,
  1134. TQueryType & Type, bool Force)
  1135. {
  1136. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1137. DebugAssert(Updates.HaveResults);
  1138. if (Updates.HaveResults)
  1139. {
  1140. if (Updates.Results.Disabled)
  1141. {
  1142. New = false;
  1143. if (Force)
  1144. {
  1145. Message = LoadStr(UPDATE_DISABLED);
  1146. }
  1147. }
  1148. else
  1149. {
  1150. if (IsUWP())
  1151. {
  1152. New = false;
  1153. }
  1154. else
  1155. {
  1156. New = (Updates.Results.Version > 0);
  1157. if (New)
  1158. {
  1159. UnicodeString Version = VersionStrFromCompoundVersion(Updates.Results.Version);
  1160. if (!Updates.Results.Release.IsEmpty())
  1161. {
  1162. Version = FORMAT(L"%s %s", (Version, Updates.Results.Release));
  1163. }
  1164. Message = FMTLOAD(NEW_VERSION4, (Version));
  1165. }
  1166. else
  1167. {
  1168. Message = LoadStr(NO_NEW_VERSION);
  1169. }
  1170. }
  1171. }
  1172. if (!Message.IsEmpty())
  1173. {
  1174. Message = MainInstructions(Message);
  1175. }
  1176. if (!Updates.Results.Message.IsEmpty())
  1177. {
  1178. FormatUpdatesMessage(Message, Updates.Results.Message, Updates);
  1179. }
  1180. if (!Updates.Results.AuthenticationError.IsEmpty() && !IsUWP())
  1181. {
  1182. FormatUpdatesMessage(Message, Updates.Results.AuthenticationError, Updates);
  1183. }
  1184. Type = (Updates.Results.Critical ? qtWarning : qtInformation);
  1185. }
  1186. else
  1187. {
  1188. New = false;
  1189. }
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. void __fastcall EnableAutomaticUpdates()
  1193. {
  1194. ShowHelp(HELP_AUTOMATIC_UPDATE);
  1195. }
  1196. //---------------------------------------------------------------------------
  1197. static void __fastcall OpenHistory(void * /*Data*/, TObject * /*Sender*/, unsigned int & /*Answer*/)
  1198. {
  1199. Configuration->Usage->Inc(L"UpdateHistoryOpens");
  1200. OpenBrowser(LoadStr(HISTORY_URL));
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. static int __fastcall DownloadSizeToProgress(__int64 Size)
  1204. {
  1205. return static_cast<int>(Size / 1024);
  1206. }
  1207. //---------------------------------------------------------------------------
  1208. static UnicodeString GetInstallationPath(HKEY RootKey)
  1209. {
  1210. std::unique_ptr<TRegistry> Registry(new TRegistry(KEY_READ));
  1211. Registry->RootKey = RootKey;
  1212. UnicodeString Result;
  1213. if (Registry->OpenKey(L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\winscp3_is1", false))
  1214. {
  1215. Result = ExcludeTrailingBackslash(Registry->ReadString(L"Inno Setup: App Path"));
  1216. }
  1217. return Result;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. static bool DoIsPathToExe(const UnicodeString & Path)
  1221. {
  1222. UnicodeString ExePath = ExcludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  1223. return IsPathToSameFile(ExePath, Path);
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. static bool DoIsInstalled(HKEY RootKey)
  1227. {
  1228. UnicodeString InstallPath = GetInstallationPath(RootKey);
  1229. bool Result =
  1230. !InstallPath.IsEmpty() &&
  1231. DoIsPathToExe(InstallPath);
  1232. return Result;
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. class TUpdateDownloadThread : public TCompThread
  1236. {
  1237. public:
  1238. __fastcall TUpdateDownloadThread(TProgressBar * ProgressBar);
  1239. virtual __fastcall ~TUpdateDownloadThread();
  1240. void __fastcall CancelClicked(TObject * Sender);
  1241. bool __fastcall CancelDownload();
  1242. __property bool Done = { read = FDone };
  1243. protected:
  1244. virtual void __fastcall Execute();
  1245. void __fastcall UpdateDownloaded();
  1246. void __fastcall HttpDownload(THttp * Sender, __int64 Size, bool & Cancel);
  1247. void __fastcall UpdateProgress();
  1248. void __fastcall ShowException();
  1249. void __fastcall DownloadNotVerified();
  1250. void __fastcall CancelForm();
  1251. private:
  1252. TCustomForm * FForm;
  1253. TProgressBar * FProgressBar;
  1254. __int64 FDownloaded;
  1255. std::unique_ptr<Exception> FException;
  1256. std::unique_ptr<THttp> FHttp;
  1257. TUpdatesConfiguration FUpdates;
  1258. bool FDone;
  1259. };
  1260. //---------------------------------------------------------------------------
  1261. __fastcall TUpdateDownloadThread::TUpdateDownloadThread(TProgressBar * ProgressBar) :
  1262. TCompThread(true)
  1263. {
  1264. // cache, as the progress bar miht be destroyed already when
  1265. // we need the form at the end of Execute()
  1266. FForm = GetParentForm(ProgressBar);
  1267. FProgressBar = ProgressBar;
  1268. // cache to prevent concurrency
  1269. FUpdates = WinConfiguration->Updates;
  1270. FDone = false;
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. __fastcall TUpdateDownloadThread::~TUpdateDownloadThread()
  1274. {
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. void __fastcall TUpdateDownloadThread::Execute()
  1278. {
  1279. try
  1280. {
  1281. bool Retried = false;
  1282. bool Retry;
  1283. do
  1284. {
  1285. Retry = false;
  1286. try
  1287. {
  1288. FDownloaded = 0;
  1289. FHttp.reset(CreateHttp(FUpdates));
  1290. FHttp->URL = FUpdates.Results.DownloadUrl;
  1291. FHttp->OnDownload = HttpDownload;
  1292. FHttp->Get();
  1293. }
  1294. catch (EAbort &)
  1295. {
  1296. throw;
  1297. }
  1298. catch (Exception & E)
  1299. {
  1300. // The original URL failed, try to get a fresh one and retry
  1301. if (!Retried)
  1302. {
  1303. try
  1304. {
  1305. // Check if new update data (URL particlarly) is available
  1306. if (QueryUpdates(FUpdates) &&
  1307. !FUpdates.Results.DownloadUrl.IsEmpty())
  1308. {
  1309. Retry = true;
  1310. Retried = true;
  1311. }
  1312. }
  1313. catch (...)
  1314. {
  1315. }
  1316. }
  1317. if (!Retry)
  1318. {
  1319. Configuration->Usage->Inc(L"UpdateFailuresDownload");
  1320. throw ExtException(&E, MainInstructions(LoadStr(UPDATE_DOWNLOAD_ERROR)));
  1321. }
  1322. }
  1323. }
  1324. while (Retry);
  1325. Synchronize(UpdateDownloaded);
  1326. }
  1327. catch (EAbort &)
  1328. {
  1329. // noop
  1330. }
  1331. catch (Exception & E)
  1332. {
  1333. Configuration->Usage->Inc(L"UpdateFailures");
  1334. FException.reset(CloneException(&E));
  1335. Synchronize(ShowException);
  1336. }
  1337. FDone = true;
  1338. Synchronize(CancelForm);
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. void __fastcall TUpdateDownloadThread::CancelForm()
  1342. {
  1343. FForm->ModalResult = mrCancel;
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. void __fastcall TUpdateDownloadThread::UpdateDownloaded()
  1347. {
  1348. size_t Size = static_cast<size_t>(FHttp->ResponseLength);
  1349. const char * Buffer = FHttp->ResponseRaw.c_str();
  1350. if (FHttp->ResponseLength != FUpdates.Results.DownloadSize)
  1351. {
  1352. DownloadNotVerified();
  1353. }
  1354. UnicodeString Digest = Sha256(Buffer, Size);
  1355. if (!SameText(FUpdates.Results.DownloadSha256, Digest))
  1356. {
  1357. DownloadNotVerified();
  1358. }
  1359. UnicodeString FileName = ExtractFileNameFromUrl(FUpdates.Results.DownloadUrl);
  1360. UnicodeString TemporaryDirectory = WinConfiguration->ExpandedTemporaryDirectory();
  1361. UnicodeString SetupPathBase = IncludeTrailingBackslash(TemporaryDirectory) + FileName;
  1362. UnicodeString SetupPath = SetupPathBase;
  1363. int Index = 0;
  1364. while (FileExists(SetupPath))
  1365. {
  1366. Index++;
  1367. SetupPath =
  1368. ExtractFilePath(SetupPathBase) + ExtractFileNameOnly(SetupPathBase) +
  1369. FORMAT(".%d", (Index)) + ExtractFileExt(SetupPathBase);
  1370. }
  1371. std::unique_ptr<TFileStream> FileStream(new TFileStream(SetupPath, fmCreate));
  1372. FileStream->Write(Buffer, Size);
  1373. FileStream.reset(NULL);
  1374. UnicodeString Params = L"/SILENT /NORESTART /AutomaticUpdate";
  1375. if (FUpdates.Results.OpenGettingStarted)
  1376. {
  1377. Params += L" /OpenGettingStarted";
  1378. }
  1379. if (ApplicationLog->Logging)
  1380. {
  1381. Params += FORMAT(" /LOG=\"%s\"", (ApplicationLog->Path + L".setup"));
  1382. }
  1383. // This condition is not necessary, it's here to reduce an impact of the change only
  1384. if (!GetInstallationPath(HKEY_LOCAL_MACHINE).IsEmpty() &&
  1385. !GetInstallationPath(HKEY_CURRENT_USER).IsEmpty())
  1386. {
  1387. UnicodeString Mode;
  1388. if (DoIsInstalled(HKEY_LOCAL_MACHINE))
  1389. {
  1390. Mode = L" /ALLUSERS";
  1391. }
  1392. else if (DebugAlwaysTrue(DoIsInstalled(HKEY_CURRENT_USER)))
  1393. {
  1394. Mode = L" /CURRENTUSER";
  1395. }
  1396. AppLogFmt(L"Both administrative and non-administrative installation found, explicitly requesting this installation mode:%s", (Mode));
  1397. Params += Mode;
  1398. }
  1399. ExecuteShellChecked(SetupPath, Params);
  1400. Configuration->Usage->Inc(L"UpdateRuns");
  1401. AppLog(L"Terminating to allow installation...");
  1402. TerminateApplication();
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. void __fastcall TUpdateDownloadThread::DownloadNotVerified()
  1406. {
  1407. throw Exception(MainInstructions(LoadStr(UPDATE_VERIFY_ERROR)));
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TUpdateDownloadThread::HttpDownload(THttp * /*Sender*/, __int64 Size, bool & Cancel)
  1411. {
  1412. FDownloaded = Size;
  1413. Synchronize(UpdateProgress);
  1414. // Do not waste bandwidth, if something goes wrong
  1415. if (FDownloaded > FUpdates.Results.DownloadSize)
  1416. {
  1417. DownloadNotVerified();
  1418. }
  1419. if (Terminated)
  1420. {
  1421. Cancel = true;
  1422. }
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. void __fastcall TUpdateDownloadThread::UpdateProgress()
  1426. {
  1427. FProgressBar->Position = DownloadSizeToProgress(FDownloaded);
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. void __fastcall TUpdateDownloadThread::ShowException()
  1431. {
  1432. DebugAssert(FException.get() != NULL);
  1433. ShowExtendedException(FException.get());
  1434. }
  1435. //---------------------------------------------------------------------------
  1436. bool __fastcall TUpdateDownloadThread::CancelDownload()
  1437. {
  1438. bool Result = !Terminated;
  1439. if (Result)
  1440. {
  1441. Configuration->Usage->Inc(L"UpdateDownloadCancels");
  1442. Terminate();
  1443. }
  1444. return Result;
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall TUpdateDownloadThread::CancelClicked(TObject * /*Sender*/)
  1448. {
  1449. if (CancelDownload())
  1450. {
  1451. WaitFor();
  1452. }
  1453. }
  1454. //---------------------------------------------------------------------------
  1455. //---------------------------------------------------------------------------
  1456. class TUpdateDownloadData : public TComponent
  1457. {
  1458. public:
  1459. TUpdateDownloadThread * Thread;
  1460. __fastcall TUpdateDownloadData() :
  1461. TComponent(NULL)
  1462. {
  1463. }
  1464. virtual __fastcall ~TUpdateDownloadData()
  1465. {
  1466. // will stop the thread
  1467. delete Thread;
  1468. }
  1469. static TUpdateDownloadData * __fastcall Retrieve(TObject * Object)
  1470. {
  1471. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1472. TComponent * UpdateDownloadDataComponent = Component->FindComponent(QualifiedClassName());
  1473. return DebugNotNull(dynamic_cast<TUpdateDownloadData *>(UpdateDownloadDataComponent));
  1474. }
  1475. };
  1476. //---------------------------------------------------------------------------
  1477. static void __fastcall DownloadClose(void * /*Data*/, TObject * Sender, TCloseAction & Action)
  1478. {
  1479. TUpdateDownloadData * UpdateDownloadData = TUpdateDownloadData::Retrieve(Sender);
  1480. // If the form was closed by CancelForm at the end of the thread, do nothing
  1481. if (!UpdateDownloadData->Thread->Done)
  1482. {
  1483. // Otherwise the form is closing because X was clicked (or maybe Cancel).
  1484. // May this should actually call CancelClicked?
  1485. if (UpdateDownloadData->Thread->CancelDownload())
  1486. {
  1487. Action = caNone;
  1488. }
  1489. }
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. static void __fastcall DownloadUpdate(void * /*Data*/, TObject * Sender, unsigned int & /*Answer*/)
  1493. {
  1494. Configuration->Usage->Inc(L"UpdateDownloadStarts");
  1495. TButton * Button = DebugNotNull(dynamic_cast<TButton *>(Sender));
  1496. TForm * Form = DebugNotNull(dynamic_cast<TForm *>(GetParentForm(Button)));
  1497. TPanel * Panel = CreateBlankPanel(Form);
  1498. TProgressBar * ProgressBar = new TProgressBar(Panel);
  1499. ProgressBar->Anchors = TAnchors() << akLeft << akTop << akRight;
  1500. ProgressBar->Top = 0;
  1501. ProgressBar->Left = 0;
  1502. ProgressBar->Width = Panel->Width;
  1503. ProgressBar->Parent = Panel;
  1504. ProgressBar->Max = DownloadSizeToProgress(WinConfiguration->Updates.Results.DownloadSize);
  1505. Panel->Height = ProgressBar->Height;
  1506. InsertPanelToMessageDialog(Form, Panel);
  1507. Button->Enabled = false;
  1508. TButton * CancelButton = dynamic_cast<TButton *>(Form->FindComponent(L"Cancel"));
  1509. CancelButton->Caption = Vcl_Consts_SMsgDlgCancel;
  1510. TUpdateDownloadThread * Thread = new TUpdateDownloadThread(ProgressBar);
  1511. // The form becomes owner of the thread (via TUpdateDownloadData),
  1512. // so the thread is automatically stopped when the form closes, if the "cancel" is pressed.
  1513. // But it gets done only after the form controls are gone, and the thread
  1514. // might try to access them meanwhile. So we stop the thread explicitly.
  1515. CancelButton->OnClick = Thread->CancelClicked;
  1516. TUpdateDownloadData * Data = new TUpdateDownloadData();
  1517. Data->Name = TUpdateDownloadData::QualifiedClassName();
  1518. Data->Thread = Thread;
  1519. Form->InsertComponent(Data);
  1520. UnicodeString DownloadingUrl = WinConfiguration->Updates.Results.DownloadingUrl;
  1521. if (!DownloadingUrl.IsEmpty())
  1522. {
  1523. NavigateMessageDialogToUrl(Form, DownloadingUrl);
  1524. }
  1525. DebugAssert(Form->OnClose == NULL);
  1526. Form->OnClose = MakeMethod<TCloseEvent>(NULL, DownloadClose);
  1527. Thread->Resume();
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. static void __fastcall UpdatesDonateClick(void * /*Data*/, TObject * /*Sender*/)
  1531. {
  1532. EnableAutomaticUpdates();
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. static void __fastcall InsertDonateLink(void * /*Data*/, TObject * Sender)
  1536. {
  1537. const UnicodeString DonatePanelName = L"DonatePanel";
  1538. TForm * Dialog = DebugNotNull(dynamic_cast<TForm *>(Sender));
  1539. // OnShow can happen multiple times, for example when showing dialog on start up (being main window)
  1540. if (FindComponentRecursively(Dialog, DonatePanelName) == NULL)
  1541. {
  1542. UnicodeString DocumentBody = LoadStr(UPDATES_DONATE_HTML);
  1543. DocumentBody = ReplaceStr(DocumentBody, L"%DONATE_URL%", AppendUrlParams(LoadStr(DONATE_URL), L"automaticupdates=1"));
  1544. UnicodeString AboutStoreUrl = LoadStr(ABOUT_STORE_URL);
  1545. DocumentBody = ReplaceStr(DocumentBody, L"%STORE_URL%", AboutStoreUrl);
  1546. UnicodeString StoreButtonUrl = ProgramUrl(LoadStr(STORE_GET_IMG_URL));
  1547. StoreButtonUrl = HTMLEscape(StoreButtonUrl);
  1548. UnicodeString StoreButton =
  1549. FORMAT(L"<img src=\"%s\" style=\"height: 1.8em; vertical-align: -0.4em; padding-top: 0.2em; border: 0;\">", (StoreButtonUrl));
  1550. UnicodeString StoreUrl = FMTLOAD(STORE_URL, (L"update"));
  1551. UnicodeString StoreLink = FORMAT(L"<a href=\"%s\">%s</a>", (StoreUrl, StoreButton));
  1552. UnicodeString PlainBody = TNetEncoding::HTML->Decode(DocumentBody);
  1553. int P1, P2;
  1554. while (((P1 = PlainBody.Pos(L"<")) > 0) && ((P2 = PlainBody.Pos(L">")) > 0) && (P1 < P2))
  1555. {
  1556. PlainBody.Delete(P1, P2 - P1 + 1);
  1557. }
  1558. while ((P1 = PlainBody.Pos(L" ")) > 0)
  1559. {
  1560. PlainBody.Delete(P1, 1);
  1561. }
  1562. DocumentBody = ReplaceStr(DocumentBody, L"%GET_IMG% ", FORMAT(L"%s&nbsp;", (StoreLink)));
  1563. DocumentBody = FORMAT(L"<p>%s</p>", (DocumentBody));
  1564. TPanel * Panel = CreateBlankPanel(Dialog);
  1565. Panel->Name = DonatePanelName;
  1566. Panel->Caption = UnicodeString(); // override default use of Name
  1567. TWebBrowserEx * DonateBrowser = CreateBrowserViewer(Panel, UnicodeString());
  1568. ReadyBrowserForStreaming(DonateBrowser);
  1569. WaitBrowserToIdle(DonateBrowser);
  1570. int Height = 36;
  1571. int TextWidth = Dialog->Canvas->TextWidth(PlainBody);
  1572. int ContentLimit = (GetMessageDialogContentWidth(Dialog) * 5 / 3);
  1573. if (TextWidth > ContentLimit)
  1574. {
  1575. Height = Height * 3 / 2;
  1576. }
  1577. DonateBrowser->Height = ScaleByTextHeight(Dialog, Height);
  1578. DonateBrowser->Top = 0;
  1579. DonateBrowser->Left = 0;
  1580. Panel->Height = DonateBrowser->Height;
  1581. // Currently this is noop (will fail assertion), if MoreMessagesUrl is not set
  1582. // (what should not happen)
  1583. InsertPanelToMessageDialog(Dialog, Panel);
  1584. UnicodeString Document = GenerateAppHtmlPage(Dialog->Font, Panel, DocumentBody, true);
  1585. LoadBrowserDocument(DonateBrowser, Document);
  1586. HideBrowserScrollbars(DonateBrowser);
  1587. }
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. bool __fastcall CheckForUpdates(bool CachedResults)
  1591. {
  1592. bool Result = false;
  1593. TOperationVisualizer Visualizer;
  1594. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1595. bool Cached =
  1596. Updates.HaveValidResultsForVersion(Configuration->CompoundVersion) &&
  1597. CachedResults;
  1598. if (!Cached)
  1599. {
  1600. DoQueryUpdates(WinConfiguration->CollectUsage);
  1601. // reread new data
  1602. Updates = WinConfiguration->Updates;
  1603. }
  1604. if (!Updates.ShownResults)
  1605. {
  1606. Updates.ShownResults = true;
  1607. WinConfiguration->Updates = Updates;
  1608. }
  1609. DebugAssert(Updates.HaveResults);
  1610. UnicodeString Message;
  1611. bool New;
  1612. TQueryType Type;
  1613. GetUpdatesMessage(Message, New, Type, true);
  1614. Configuration->Usage->Inc(L"UpdateDisplays");
  1615. if (New)
  1616. {
  1617. Configuration->Usage->Inc(L"UpdateDisplaysNew");
  1618. }
  1619. if ((double(Updates.Period) > 0) &&
  1620. // do not show next check time, if we have new version info
  1621. !New)
  1622. {
  1623. Message += L"\n\n" +
  1624. FMTLOAD(UPDATE_NEXT, (FormatDateTime("ddddd", Updates.LastCheck + Updates.Period)));
  1625. }
  1626. else if (New)
  1627. {
  1628. UnicodeString Version = Configuration->GetVersionStrHuman();
  1629. Message += L"\n\n" + FMTLOAD(UPDATE_CURRENT, (Version));
  1630. }
  1631. int Answers = qaOK |
  1632. // show "what's new" button only when change list URL was not provided in results
  1633. FLAGMASK(New && Updates.Results.NewsUrl.IsEmpty(), qaAll) |
  1634. FLAGMASK(New, qaCancel) |
  1635. FLAGMASK(!Updates.Results.Url.IsEmpty(), qaYes);
  1636. TQueryButtonAlias Aliases[4];
  1637. Aliases[0].Button = qaYes;
  1638. if (Updates.Results.UrlButton.IsEmpty())
  1639. {
  1640. Aliases[0].Alias = LoadStr(UPDATE_URL_BUTTON);
  1641. }
  1642. else
  1643. {
  1644. Aliases[0].Alias = Updates.Results.UrlButton;
  1645. }
  1646. Aliases[1].Button = qaAll;
  1647. Aliases[1].Alias = LoadStr(WHATS_NEW_BUTTON);
  1648. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, OpenHistory);
  1649. Aliases[2].Button = qaCancel;
  1650. Aliases[2].Alias = Vcl_Consts_SMsgDlgClose;
  1651. // Used only when New == true, see AliasesCount below
  1652. Aliases[3].Button = qaOK;
  1653. Aliases[3].Alias = LoadStr(UPGRADE_BUTTON);
  1654. if (!Updates.Results.DownloadUrl.IsEmpty())
  1655. {
  1656. Aliases[3].OnSubmit = MakeMethod<TButtonSubmitEvent>(NULL, DownloadUpdate);
  1657. Aliases[3].ElevationRequired = DoIsInstalled(HKEY_LOCAL_MACHINE);
  1658. }
  1659. TMessageParams Params;
  1660. Params.Aliases = Aliases;
  1661. Params.MoreMessagesUrl = Updates.Results.NewsUrl;
  1662. Params.MoreMessagesSize = Updates.Results.NewsSize;
  1663. // alias "ok" button to "upgrade" only if we have new version
  1664. Params.AliasesCount = LENOF(Aliases) - (New ? 0 : 1);
  1665. Params.CustomCaption = LoadStr(CHECK_FOR_UPDATES_TITLE);
  1666. if (New)
  1667. {
  1668. Params.ImageName = L"Installer";
  1669. }
  1670. std::unique_ptr<TForm> Dialog(
  1671. CreateMoreMessageDialogEx(Message, NULL, Type, Answers, HELP_UPDATES, &Params));
  1672. if (New)
  1673. {
  1674. if (Updates.Results.DownloadUrl.IsEmpty() && IsInstalled())
  1675. {
  1676. DebugAssert(Dialog->OnShow == NULL);
  1677. // InsertDonateLink need to be called only after MessageBrowser is created
  1678. Dialog->OnShow = MakeMethod<TNotifyEvent>(NULL, InsertDonateLink);
  1679. }
  1680. }
  1681. unsigned int Answer = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  1682. switch (Answer)
  1683. {
  1684. case qaOK:
  1685. if (New)
  1686. {
  1687. Configuration->Usage->Inc(L"UpdateDownloadOpens");
  1688. UnicodeString UpgradeUrl = ProgramUrl(LoadStr(UPGRADE_URL));
  1689. UpgradeUrl = WantBetaUrl(UpgradeUrl, true);
  1690. UpgradeUrl = AppendUrlParams(UpgradeUrl, FORMAT(L"to=%s", (VersionStrFromCompoundVersion(Updates.Results.Version))));
  1691. OpenBrowser(UpgradeUrl);
  1692. Result = true;
  1693. }
  1694. break;
  1695. case qaYes:
  1696. OpenBrowser(Updates.Results.Url);
  1697. break;
  1698. case qaAll:
  1699. DebugFail();
  1700. break;
  1701. }
  1702. return Result;
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. class TUpdateThread : public TCompThread
  1706. {
  1707. public:
  1708. __fastcall TUpdateThread(TThreadMethod OnUpdatesChecked);
  1709. protected:
  1710. virtual void __fastcall Execute();
  1711. TThreadMethod FOnUpdatesChecked;
  1712. };
  1713. //---------------------------------------------------------------------------
  1714. TUpdateThread * UpdateThread = NULL;
  1715. //---------------------------------------------------------------------------
  1716. __fastcall TUpdateThread::TUpdateThread(TThreadMethod OnUpdatesChecked) :
  1717. TCompThread(false),
  1718. FOnUpdatesChecked(OnUpdatesChecked)
  1719. {
  1720. }
  1721. //---------------------------------------------------------------------------
  1722. void __fastcall TUpdateThread::Execute()
  1723. {
  1724. try
  1725. {
  1726. DoQueryUpdates(WinConfiguration->CollectUsage);
  1727. if (FOnUpdatesChecked != NULL)
  1728. {
  1729. Synchronize(FOnUpdatesChecked);
  1730. }
  1731. }
  1732. catch(...)
  1733. {
  1734. // ignore errors
  1735. }
  1736. }
  1737. //---------------------------------------------------------------------------
  1738. void __fastcall StartUpdateThread(TThreadMethod OnUpdatesChecked)
  1739. {
  1740. DebugAssert(UpdateThread == NULL);
  1741. UpdateThread = new TUpdateThread(OnUpdatesChecked);
  1742. }
  1743. //---------------------------------------------------------------------------
  1744. void __fastcall StopUpdateThread()
  1745. {
  1746. if (UpdateThread != NULL)
  1747. {
  1748. SAFE_DESTROY(UpdateThread);
  1749. }
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. void __fastcall SetupInitialize()
  1753. {
  1754. try
  1755. {
  1756. WinConfiguration->UpdateJumpList();
  1757. }
  1758. catch (Exception & E)
  1759. {
  1760. ShowExtendedException(&E);
  1761. }
  1762. }
  1763. //---------------------------------------------------------------------------
  1764. static bool __fastcall AddJumpListCategory(TStrings * Names,
  1765. UnicodeString AdditionalParams, TStringList * Removed,
  1766. ICustomDestinationList * DestinationList, UnicodeString CategoryName,
  1767. int IconIndex)
  1768. {
  1769. bool Result = false;
  1770. IObjectCollection * Collection = NULL;
  1771. if (SUCCEEDED(CoCreateInstance(CLSID_EnumerableObjectCollection, NULL,
  1772. CLSCTX_INPROC_SERVER, IID_IObjectCollection, (void**)&Collection)))
  1773. {
  1774. try
  1775. {
  1776. AddToList(AdditionalParams, TProgramParams::FormatSwitch(JUMPLIST_SWITCH), L" ");
  1777. int Count = 0;
  1778. for (int Index = 0; Index < Names->Count; Index++)
  1779. {
  1780. IShellLink * Link =
  1781. CreateDesktopSessionShortCut(
  1782. Names->Strings[Index], L"", AdditionalParams, -1, IconIndex, true);
  1783. wchar_t Desc[2048];
  1784. if (SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1785. {
  1786. if (Removed->IndexOf(Desc) < 0)
  1787. {
  1788. try
  1789. {
  1790. DebugCheck(SUCCEEDED(Collection->AddObject(Link)));
  1791. Count++;
  1792. }
  1793. __finally
  1794. {
  1795. Link->Release();
  1796. }
  1797. }
  1798. else
  1799. {
  1800. Names->Delete(Index);
  1801. Index--;
  1802. }
  1803. }
  1804. }
  1805. if (Count > 0)
  1806. {
  1807. IObjectArray * Array;
  1808. if (SUCCEEDED(Collection->QueryInterface(IID_IObjectArray, (void**)&Array)))
  1809. {
  1810. try
  1811. {
  1812. Result = SUCCEEDED(
  1813. DestinationList->AppendCategory(CategoryName.c_str(), Array));
  1814. }
  1815. __finally
  1816. {
  1817. Array->Release();
  1818. }
  1819. }
  1820. }
  1821. }
  1822. __finally
  1823. {
  1824. Collection->Release();
  1825. }
  1826. }
  1827. return Result;
  1828. }
  1829. //---------------------------------------------------------------------------
  1830. void __fastcall UpdateJumpList(TStrings * SessionNames, TStrings * WorkspaceNames)
  1831. {
  1832. ICustomDestinationList * DestinationList = NULL;
  1833. IObjectArray * RemovedArray;
  1834. TStringList * Removed = NULL;
  1835. int OldErrMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  1836. try
  1837. {
  1838. if (SUCCEEDED(CoCreateInstance(CLSID_DestinationList, NULL,
  1839. CLSCTX_INPROC_SERVER, IID_ICustomDestinationList, (void**)&DestinationList)))
  1840. {
  1841. unsigned int MinSlots;
  1842. HRESULT Result = DestinationListBeginList(DestinationList, MinSlots, IID_IObjectArray, reinterpret_cast<void *>(RemovedArray), 50000);
  1843. if (SUCCEEDED(Result) && DebugAlwaysTrue(RemovedArray != NULL))
  1844. {
  1845. Removed = new TStringList();
  1846. unsigned int RemovedCount;
  1847. if (FAILED(RemovedArray->GetCount(&RemovedCount)))
  1848. {
  1849. RemovedCount = 0;
  1850. }
  1851. for (unsigned int Index = 0; Index < RemovedCount; Index++)
  1852. {
  1853. IShellLink * Link;
  1854. wchar_t Desc[2048];
  1855. if (SUCCEEDED(RemovedArray->GetAt(Index, IID_IShellLink, (void**)&Link)) &&
  1856. SUCCEEDED(Link->GetDescription(Desc, LENOF(Desc) - 1)))
  1857. {
  1858. Removed->Add(Desc);
  1859. }
  1860. }
  1861. AddJumpListCategory(
  1862. WorkspaceNames, L"", Removed, DestinationList,
  1863. LoadStr(JUMPLIST_WORKSPACES), WORKSPACE_ICON);
  1864. AddJumpListCategory(
  1865. SessionNames, TProgramParams::FormatSwitch(UPLOAD_IF_ANY_SWITCH), Removed, DestinationList,
  1866. LoadStr(JUMPLIST_RECENT), SITE_ICON);
  1867. if (DestinationList != NULL)
  1868. {
  1869. DestinationList->CommitList();
  1870. }
  1871. }
  1872. }
  1873. }
  1874. __finally
  1875. {
  1876. SetErrorMode(OldErrMode);
  1877. if (DestinationList != NULL)
  1878. {
  1879. DestinationList->Release();
  1880. }
  1881. delete Removed;
  1882. }
  1883. }
  1884. //---------------------------------------------------------------------------
  1885. bool __fastcall AnyOtherInstanceOfSelf()
  1886. {
  1887. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
  1888. bool Result = false;
  1889. try
  1890. {
  1891. unsigned int Process = GetCurrentProcessId();
  1892. UnicodeString ExeBaseName = ExtractFileBaseName(Application->ExeName);
  1893. PROCESSENTRY32 ProcessEntry;
  1894. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  1895. if (Process32First(Snapshot, &ProcessEntry))
  1896. {
  1897. while (!Result && Process32Next(Snapshot, &ProcessEntry))
  1898. {
  1899. // we should check if the process is running in the same session,
  1900. // but for that we probably need some special privileges
  1901. if ((Process != ProcessEntry.th32ProcessID) &&
  1902. SameText(ExtractFileBaseName(ProcessEntry.szExeFile), ExeBaseName))
  1903. {
  1904. Result = true;
  1905. }
  1906. }
  1907. }
  1908. }
  1909. __finally
  1910. {
  1911. CloseHandle(Snapshot);
  1912. }
  1913. return Result;
  1914. }
  1915. //---------------------------------------------------------------------------
  1916. bool IsInstalled()
  1917. {
  1918. return
  1919. DoIsInstalled(HKEY_LOCAL_MACHINE) ||
  1920. DoIsInstalled(HKEY_CURRENT_USER);
  1921. }
  1922. //---------------------------------------------------------------------------
  1923. static int GIsInstalledMsi = -1;
  1924. bool IsInstalledMsi()
  1925. {
  1926. if (GIsInstalledMsi < 0)
  1927. {
  1928. GIsInstalledMsi = 0;
  1929. wchar_t ProductCode[MAX_GUID_CHARS + 1];
  1930. if (MsiEnumRelatedProducts(L"{029F9450-CFEF-4408-A2BB-B69ECE29EB18}", 0, 0, ProductCode) == ERROR_SUCCESS)
  1931. {
  1932. UnicodeString InstallPath;
  1933. InstallPath.SetLength(MAX_PATH);
  1934. unsigned long Size = InstallPath.Length() + 1;
  1935. int ErrorCode = MsiGetProductInfo(ProductCode, INSTALLPROPERTY_INSTALLLOCATION, InstallPath.c_str(), &Size);
  1936. if (ErrorCode == ERROR_MORE_DATA)
  1937. {
  1938. InstallPath.SetLength(Size);
  1939. Size++;
  1940. ErrorCode = MsiGetProductInfo(ProductCode, INSTALLPROPERTY_INSTALLLOCATION, InstallPath.c_str(), &Size);
  1941. }
  1942. if (ErrorCode == ERROR_SUCCESS)
  1943. {
  1944. InstallPath.SetLength(Size);
  1945. if (DoIsPathToExe(InstallPath))
  1946. {
  1947. GIsInstalledMsi = 1;
  1948. }
  1949. }
  1950. }
  1951. }
  1952. return (GIsInstalledMsi > 0);
  1953. }
  1954. //---------------------------------------------------------------------------
  1955. UnicodeString __fastcall FirstUnshownTip()
  1956. {
  1957. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  1958. std::unique_ptr<TStringList> Tips(CommaTextToStringList(Updates.Results.Tips));
  1959. Tips->CaseSensitive = false;
  1960. std::unique_ptr<TStringList> TipsSeen(CommaTextToStringList(WinConfiguration->TipsSeen));
  1961. TipsSeen->CaseSensitive = false;
  1962. int LastTipSeen = -1;
  1963. for (int Index = 0; Index < TipsSeen->Count; Index++)
  1964. {
  1965. int TipIndex = Tips->IndexOf(TipsSeen->Names[Index]);
  1966. if (TipIndex >= 0)
  1967. {
  1968. LastTipSeen = TipIndex;
  1969. }
  1970. }
  1971. UnicodeString Result;
  1972. if (LastTipSeen < Tips->Count - 1)
  1973. {
  1974. Result = Tips->Strings[LastTipSeen + 1];
  1975. }
  1976. return Result;
  1977. }
  1978. //---------------------------------------------------------------------------
  1979. class TTipsData : public TComponent
  1980. {
  1981. public:
  1982. __fastcall TTipsData() :
  1983. TComponent(NULL)
  1984. {
  1985. }
  1986. int Index;
  1987. TStringList * Tips;
  1988. static TTipsData * __fastcall Retrieve(TObject * Object)
  1989. {
  1990. TComponent * Component = DebugNotNull(dynamic_cast<TComponent *>(Object));
  1991. TComponent * TipsDataComponent = Component->FindComponent(QualifiedClassName());
  1992. return DebugNotNull(dynamic_cast<TTipsData *>(TipsDataComponent));
  1993. }
  1994. };
  1995. //---------------------------------------------------------------------------
  1996. static UnicodeString __fastcall TipsMessage(TTipsData * TipsData)
  1997. {
  1998. return FMTLOAD(TIPS_MESSAGE, (TipsData->Index + 1, TipsData->Tips->Count));
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. static void __fastcall UpdateTipsForm(TCustomForm * Form)
  2002. {
  2003. TTipsData * TipsData = TTipsData::Retrieve(Form);
  2004. TButton * PrevButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(YesButtonName)));
  2005. PrevButton->Enabled = (TipsData->Index > 0);
  2006. TButton * NextButton = DebugNotNull(dynamic_cast<TButton *>(Form->FindComponent(L"No")));
  2007. NextButton->Enabled = (TipsData->Index < TipsData->Tips->Count - 1);
  2008. TLabel * MessageLabel = DebugNotNull(dynamic_cast<TLabel *>(FindComponentRecursively(Form, MainMessageLabelName)));
  2009. MessageLabel->Caption = TipsMessage(TipsData);
  2010. }
  2011. //---------------------------------------------------------------------------
  2012. static UnicodeString __fastcall TipUrl(TTipsData * TipsData)
  2013. {
  2014. UnicodeString Tip = TipsData->Tips->Strings[TipsData->Index];
  2015. UnicodeString TipParams = FORMAT(L"tip=%s", (Tip));
  2016. return AppendUrlParams(WinConfiguration->Updates.Results.TipsUrl, TipParams);
  2017. }
  2018. //---------------------------------------------------------------------------
  2019. static void __fastcall TipSeen(const UnicodeString & Tip)
  2020. {
  2021. std::unique_ptr<TStringList> TipsSeen(CommaTextToStringList(WinConfiguration->TipsSeen));
  2022. TipsSeen->Values[Tip] = FormatDateTime(L"yyyy-mm-dd", Now());
  2023. WinConfiguration->TipsSeen = TipsSeen->CommaText;
  2024. WinConfiguration->TipsShown = Now();
  2025. WinConfiguration->RunsSinceLastTip = 0;
  2026. // prevent parallel app instances showing the same tip
  2027. WinConfiguration->Save();
  2028. }
  2029. //---------------------------------------------------------------------------
  2030. static void __fastcall PrevNextTipClick(void * Data, TObject * Sender, unsigned int & /*Answer*/)
  2031. {
  2032. TCustomForm * Form = GetParentForm(dynamic_cast<TControl *>(Sender));
  2033. TTipsData * TipsData = TTipsData::Retrieve(Form);
  2034. TipsData->Index += reinterpret_cast<int>(Data);
  2035. UpdateTipsForm(Form);
  2036. TipSeen(TipsData->Tips->Strings[TipsData->Index]);
  2037. UnicodeString Url = TipUrl(TipsData);
  2038. NavigateMessageDialogToUrl(Form, Url);
  2039. }
  2040. //---------------------------------------------------------------------------
  2041. static void __fastcall ShowTip(bool AutoShow)
  2042. {
  2043. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  2044. UnicodeString Tip = FirstUnshownTip();
  2045. std::unique_ptr<TStringList> Tips(CommaTextToStringList(Updates.Results.Tips));
  2046. Tips->CaseSensitive = false;
  2047. int Index;
  2048. if (Tip.IsEmpty())
  2049. {
  2050. Index = Tips->Count - 1;
  2051. Tip = Tips->Strings[Index];
  2052. }
  2053. else
  2054. {
  2055. Index = Tips->IndexOf(Tip);
  2056. }
  2057. std::unique_ptr<TTipsData> TipsData(new TTipsData());
  2058. TipsData->Name = TTipsData::QualifiedClassName();
  2059. TipsData->Index = Index;
  2060. TipsData->Tips = Tips.get();
  2061. UnicodeString Message = MainInstructions(TipsMessage(TipsData.get()));
  2062. TQueryButtonAlias Aliases[3];
  2063. Aliases[0].Button = qaYes;
  2064. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2065. Aliases[0].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(-1), PrevNextTipClick);
  2066. Aliases[1].Button = qaNo;
  2067. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2068. Aliases[1].OnSubmit = MakeMethod<TButtonSubmitEvent>(reinterpret_cast<void *>(+1), PrevNextTipClick);
  2069. Aliases[2].Button = qaCancel;
  2070. Aliases[2].Alias = LoadStr(CLOSE_BUTTON);
  2071. TMessageParams Params;
  2072. Params.CustomCaption = LoadStr(TIPS_TITLE);
  2073. Params.MoreMessagesSize = Updates.Results.TipsSize;
  2074. Params.MoreMessagesUrl = TipUrl(TipsData.get());
  2075. Params.Aliases = Aliases;
  2076. Params.AliasesCount = LENOF(Aliases);
  2077. Params.ImageName = L"Bulb On";
  2078. if (AutoShow)
  2079. {
  2080. // Won't be used automatically as we have more than the "OK" button
  2081. Params.NeverAskAgainTitle = LoadStr(NEVER_SHOW_AGAIN);
  2082. Params.NeverAskAgainAnswer = qaCancel;
  2083. Params.Params |= mpNeverAskAgainCheck;
  2084. }
  2085. int Answers = qaYes | qaNo | qaCancel;
  2086. std::unique_ptr<TForm> Dialog(CreateMoreMessageDialogEx(Message, NULL, qtInformation, Answers, HELP_TIPS, &Params));
  2087. Dialog->InsertComponent(TipsData.release());
  2088. UpdateTipsForm(Dialog.get());
  2089. TipSeen(Tip);
  2090. unsigned int Result = ExecuteMessageDialog(Dialog.get(), Answers, &Params);
  2091. if ((Result == qaNeverAskAgain) && DebugAlwaysTrue(AutoShow))
  2092. {
  2093. WinConfiguration->ShowTips = false;
  2094. }
  2095. WinConfiguration->Updates = Updates;
  2096. }
  2097. //---------------------------------------------------------------------------
  2098. void __fastcall AutoShowNewTip()
  2099. {
  2100. Configuration->Usage->Inc(L"TipsShownAuto");
  2101. ShowTip(true);
  2102. }
  2103. //---------------------------------------------------------------------------
  2104. bool __fastcall AnyTips()
  2105. {
  2106. return !WinConfiguration->Updates.Results.Tips.IsEmpty();
  2107. }
  2108. //---------------------------------------------------------------------------
  2109. void __fastcall ShowTips()
  2110. {
  2111. {
  2112. TOperationVisualizer Visualizer;
  2113. DoQueryUpdates(false);
  2114. }
  2115. if (!AnyTips())
  2116. {
  2117. throw Exception(MainInstructions(LoadStr(TIPS_NONE)));
  2118. }
  2119. Configuration->Usage->Inc(L"TipsShownCommand");
  2120. ShowTip(false);
  2121. }
  2122. //---------------------------------------------------------------------------
  2123. void __fastcall TipsUpdateStaticUsage()
  2124. {
  2125. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  2126. std::unique_ptr<TStringList> Tips(CommaTextToStringList(Updates.Results.Tips));
  2127. Configuration->Usage->Set(L"TipsCount", Tips->Count);
  2128. std::unique_ptr<TStringList> TipsSeen(CommaTextToStringList(WinConfiguration->TipsSeen));
  2129. Configuration->Usage->Set(L"TipsSeen", TipsSeen->Count);
  2130. }
  2131. //---------------------------------------------------------------------------
  2132. static void ReadNetVersion(TRegistryStorage * Registry)
  2133. {
  2134. UnicodeString VersionStr = Registry->ReadString(L"Version", L"");
  2135. if (CompareVersion(VersionStr, NetVersionStr) > 0)
  2136. {
  2137. NetVersionStr = VersionStr;
  2138. }
  2139. }
  2140. //---------------------------------------------------------------------------
  2141. UnicodeString GetNetVersionStr()
  2142. {
  2143. if (NetVersionStr.IsEmpty())
  2144. {
  2145. NetVersionStr = L"0"; // not to retry on failure
  2146. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP", HKEY_LOCAL_MACHINE));
  2147. if (Registry->OpenRootKey(false))
  2148. {
  2149. std::unique_ptr<TStringList> Keys(new TStringList());
  2150. Registry->GetSubKeyNames(Keys.get());
  2151. for (int Index = 0; Index < Keys->Count; Index++)
  2152. {
  2153. UnicodeString Key = Keys->Strings[Index];
  2154. if (Registry->OpenSubKey(Key, false))
  2155. {
  2156. ReadNetVersion(Registry.get());
  2157. if (Registry->OpenSubKey(L"Full", false))
  2158. {
  2159. ReadNetVersion(Registry.get());
  2160. Registry->CloseSubKey();
  2161. }
  2162. if (Registry->OpenSubKey(L"Client", false))
  2163. {
  2164. ReadNetVersion(Registry.get());
  2165. Registry->CloseSubKey();
  2166. }
  2167. Registry->CloseSubKey();
  2168. }
  2169. }
  2170. }
  2171. }
  2172. return NetVersionStr;
  2173. }
  2174. //---------------------------------------------------------------------------
  2175. UnicodeString GetNetCoreVersionStr()
  2176. {
  2177. if (NetCoreVersionStr.IsEmpty())
  2178. {
  2179. NetCoreVersionStr = L"0"; // not to retry on failure
  2180. UnicodeString ProgramsFolder = DefaultStr(GetEnvironmentVariable(L"ProgramW6432"), GetEnvironmentVariable(L"ProgramFiles"));
  2181. if (ProgramsFolder.IsEmpty())
  2182. {
  2183. ::SpecialFolderLocation(CSIDL_PROGRAM_FILES, ProgramsFolder);
  2184. }
  2185. UnicodeString RuntimeFolder = L"shared\\Microsoft.NETCore.App";
  2186. UnicodeString DotNetPath = CombinePaths(CombinePaths(ProgramsFolder, L"dotnet"), RuntimeFolder);
  2187. if (!DirectoryExistsFix(DotNetPath))
  2188. {
  2189. UnicodeString DotNetExe = L"dotnet.exe";
  2190. if (FindFile(DotNetExe))
  2191. {
  2192. DotNetPath = CombinePaths(ExtractFilePath(DotNetExe), RuntimeFolder);
  2193. }
  2194. }
  2195. if (DirectoryExistsFix(DotNetPath))
  2196. {
  2197. TSearchRecChecked SearchRec;
  2198. DotNetPath = CombinePaths(DotNetPath, L"*.*");
  2199. if (FindFirstUnchecked(ApiPath(DotNetPath), faDirectory, SearchRec) == 0)
  2200. {
  2201. do
  2202. {
  2203. if (SearchRec.IsRealFile())
  2204. {
  2205. UnicodeString Name = SearchRec.Name;
  2206. // 1.0.0-preview2-003131
  2207. UnicodeString VersionStr = CutToChar(Name, L'-', true);
  2208. if (!VersionStr.IsEmpty() && IsDigit(VersionStr[1]) && (VersionStr.Pos(L".") >= 2))
  2209. {
  2210. for (int I = 1; I <= VersionStr.Length(); I++)
  2211. {
  2212. if (!IsDigit(VersionStr[I]) && (VersionStr[I] != L'.'))
  2213. {
  2214. VersionStr = EmptyStr;
  2215. }
  2216. }
  2217. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, NetCoreVersionStr) > 0))
  2218. {
  2219. NetCoreVersionStr = VersionStr;
  2220. }
  2221. }
  2222. }
  2223. }
  2224. while (FindNextUnchecked(SearchRec) == 0);
  2225. }
  2226. }
  2227. }
  2228. return NetCoreVersionStr;
  2229. }
  2230. //---------------------------------------------------------------------------
  2231. UnicodeString GetPowerShellVersionStr()
  2232. {
  2233. if (PowerShellVersionStr.IsEmpty())
  2234. {
  2235. PowerShellVersionStr = L"0"; // not to retry on failure
  2236. std::unique_ptr<TRegistryStorage> Registry(new TRegistryStorage(L"SOFTWARE\\Microsoft\\PowerShell", HKEY_LOCAL_MACHINE));
  2237. if (Registry->OpenRootKey(false))
  2238. {
  2239. std::unique_ptr<TStringList> Keys(new TStringList());
  2240. Registry->GetSubKeyNames(Keys.get());
  2241. for (int Index = 0; Index < Keys->Count; Index++)
  2242. {
  2243. UnicodeString Key = Keys->Strings[Index];
  2244. if (Registry->OpenSubKeyPath(Key + L"\\PowerShellEngine", false))
  2245. {
  2246. UnicodeString VersionStr = Registry->ReadString(L"PowerShellVersion", L"");
  2247. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellVersionStr) > 0))
  2248. {
  2249. PowerShellVersionStr = VersionStr;
  2250. }
  2251. Registry->CloseSubKeyPath();
  2252. }
  2253. }
  2254. }
  2255. }
  2256. return PowerShellVersionStr;
  2257. }
  2258. //---------------------------------------------------------------------------
  2259. UnicodeString GetPowerShellCoreVersionStr()
  2260. {
  2261. if (PowerShellCoreVersionStr.IsEmpty())
  2262. {
  2263. PowerShellCoreVersionStr = L"0"; // not to retry on failure
  2264. // TRegistryStorage does not support KEY_WOW64_64KEY
  2265. unsigned int Access = KEY_READ | FLAGMASK(IsWin64(), KEY_WOW64_64KEY);
  2266. std::unique_ptr<TRegistry> Registry(new TRegistry(Access));
  2267. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2268. UnicodeString RootKey(L"SOFTWARE\\Microsoft\\PowerShellCore\\InstalledVersions");
  2269. if (Registry->OpenKeyReadOnly(RootKey))
  2270. {
  2271. std::unique_ptr<TStringList> Keys(new TStringList());
  2272. Registry->GetKeyNames(Keys.get());
  2273. Registry->CloseKey();
  2274. for (int Index = 0; Index < Keys->Count; Index++)
  2275. {
  2276. UnicodeString Key = RootKey + L"\\" + Keys->Strings[Index];
  2277. if (Registry->OpenKeyReadOnly(Key))
  2278. {
  2279. UnicodeString VersionStr = Registry->ReadString(L"SemanticVersion");
  2280. if (!VersionStr.IsEmpty() && (CompareVersion(VersionStr, PowerShellCoreVersionStr) > 0))
  2281. {
  2282. PowerShellCoreVersionStr = VersionStr;
  2283. }
  2284. Registry->CloseKey();
  2285. }
  2286. }
  2287. }
  2288. }
  2289. return PowerShellCoreVersionStr;
  2290. }
  2291. //---------------------------------------------------------------------------
  2292. //---------------------------------------------------------------------------
  2293. static void CollectCLSIDKey(
  2294. TConsole * Console, TStrings * Keys, int PlatformSet, TRegistryStorage * Storage, const UnicodeString & CLSID,
  2295. UnicodeString & CommonCodeBase, const UnicodeString & Platform, UnicodeString & Platforms)
  2296. {
  2297. UnicodeString CLSIDKey = FORMAT(L"CLSID\\%s", (CLSID));
  2298. if (Storage->OpenSubKeyPath(CLSIDKey, false))
  2299. {
  2300. int Index = Keys->IndexOf(CLSIDKey);
  2301. if (Index >= 0)
  2302. {
  2303. Keys->Objects[Index] = reinterpret_cast<TObject *>(PlatformSet | reinterpret_cast<int>(Keys->Objects[Index]));
  2304. }
  2305. else
  2306. {
  2307. Keys->AddObject(CLSIDKey, reinterpret_cast<TObject *>(PlatformSet));
  2308. }
  2309. UnicodeString CodeBase;
  2310. if (Storage->OpenSubKey(L"InprocServer32", false))
  2311. {
  2312. CodeBase = Storage->ReadString(L"CodeBase", UnicodeString());
  2313. UnicodeString Assembly = Storage->ReadString(L"Assembly", UnicodeString());
  2314. UnicodeString Version;
  2315. if (!Assembly.IsEmpty())
  2316. {
  2317. UnicodeString VersionPrefix = L"Version=";
  2318. int P = Assembly.UpperCase().Pos(VersionPrefix.UpperCase());
  2319. if (P > 0)
  2320. {
  2321. Assembly.Delete(1, P + VersionPrefix.Length() - 1);
  2322. Version = CutToChar(Assembly, L',', true);
  2323. }
  2324. }
  2325. if (CodeBase.IsEmpty() || Version.IsEmpty())
  2326. {
  2327. Console->PrintLine(FORMAT(L"Warning: Could not find codebase and version for %s.", (CLSID)));
  2328. CodeBase = UnicodeString();
  2329. }
  2330. else
  2331. {
  2332. CodeBase = FORMAT(L"%s (%s)", (CodeBase, Version));
  2333. if (CommonCodeBase.IsEmpty())
  2334. {
  2335. Console->PrintLine(FORMAT(L"Codebase %s, unless stated otherwise", (CodeBase)));
  2336. CommonCodeBase = CodeBase;
  2337. }
  2338. if (SameText(CommonCodeBase, CodeBase))
  2339. {
  2340. CodeBase = L"";
  2341. }
  2342. }
  2343. Storage->CloseSubKey();
  2344. }
  2345. Storage->CloseSubKeyPath();
  2346. UnicodeString Buf = Platform;
  2347. AddToList(Buf, CodeBase, L" - ");
  2348. AddToList(Platforms, Buf, ", ");
  2349. }
  2350. }
  2351. //---------------------------------------------------------------------------
  2352. static UnicodeString PlatformStr(int PlatformSet)
  2353. {
  2354. UnicodeString Result;
  2355. if (PlatformSet == 0)
  2356. {
  2357. Result = L"shared";
  2358. }
  2359. else
  2360. {
  2361. if (FLAGSET(PlatformSet, 32))
  2362. {
  2363. Result = L"32-bit";
  2364. }
  2365. if (FLAGSET(PlatformSet, 64))
  2366. {
  2367. AddToList(Result, L"64-bit", L", ");
  2368. }
  2369. }
  2370. return Result;
  2371. }
  2372. //---------------------------------------------------------------------------
  2373. static void DoCollectComRegistration(TConsole * Console, TStrings * Keys)
  2374. {
  2375. UnicodeString TypeLib = L"{A0B93468-D98A-4845-A234-8076229AD93F}"; // Duplicated in AssemblyInfo.cs
  2376. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT));
  2377. Storage->MungeStringValues = false;
  2378. Storage->AccessMode = smRead;
  2379. std::unique_ptr<TRegistryStorage> Storage64;
  2380. if (IsWin64())
  2381. {
  2382. Storage64.reset(new TRegistryStorage(UnicodeString(), HKEY_CLASSES_ROOT, KEY_WOW64_64KEY));
  2383. Storage64->MungeStringValues = false;
  2384. Storage64->AccessMode = smRead;
  2385. }
  2386. // Classes, TypeLib and Record are shared between 32-bit and 64-bit registry view.
  2387. // 32-bit and 64-bit version of regasm adds CLSID keys to its respective view.
  2388. // Both 32-bit and 64-bit version of regasm seem to add Interface keys to both 32-bit and 64-bit views.
  2389. // On Vista, Interface keys are reflected (so when 32-bit keys is deleted, it's also deleted from 64-bit key,
  2390. // and we show an error, trying to delete the 64-bit key).
  2391. if (Storage->OpenRootKey(false))
  2392. {
  2393. Console->PrintLine(FORMAT(L"Versions of type library %s:", (TypeLib)));
  2394. UnicodeString TypeLibKey = FORMAT(L"TypeLib\\%s", (TypeLib));
  2395. if (Storage->OpenSubKeyPath(TypeLibKey, false))
  2396. {
  2397. Keys->Add(TypeLibKey);
  2398. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2399. Storage->GetSubKeyNames(KeyNames.get());
  2400. if (KeyNames->Count == 0)
  2401. {
  2402. Console->PrintLine(L"Warning: The type library key exists, but no type libraries are present.");
  2403. }
  2404. else
  2405. {
  2406. for (int Index = 0; Index < KeyNames->Count; Index++)
  2407. {
  2408. UnicodeString Version = KeyNames->Strings[Index];
  2409. if (!Storage->OpenSubKeyPath(FORMAT(L"%s\\0", (Version)), false))
  2410. {
  2411. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" cannot be opened.", (Version)));
  2412. }
  2413. else
  2414. {
  2415. std::unique_ptr<TStringList> Platforms(new TStringList());
  2416. Storage->GetSubKeyNames(Platforms.get());
  2417. if (Platforms->Count == 0)
  2418. {
  2419. Console->PrintLine(FORMAT(L"Warning: Subkey \"0\" for type library \"%s\" exists, but platforms are present.", (Version)));
  2420. }
  2421. else
  2422. {
  2423. for (int Index2 = 0; Index2 < Platforms->Count; Index2++)
  2424. {
  2425. UnicodeString Platform = Platforms->Strings[Index2];
  2426. if (!Storage->OpenSubKey(Platform, false))
  2427. {
  2428. Console->PrintLine(FORMAT(L"Warning: Platform \"%s\" for type library \"%s\" cannot be opened.", (Platform, Version)));
  2429. }
  2430. else
  2431. {
  2432. UnicodeString TypeLibraryPath = Storage->ReadString(UnicodeString(), UnicodeString());
  2433. UnicodeString Exists = FileExists(TypeLibraryPath) ? L"exists" : L"does not exist";
  2434. Console->PrintLine(FORMAT(L"%s (%s): %s (%s)", (Version, Platform, TypeLibraryPath, Exists)));
  2435. Storage->CloseSubKey();
  2436. }
  2437. }
  2438. }
  2439. Storage->CloseSubKeyPath();
  2440. }
  2441. }
  2442. }
  2443. Storage->CloseSubKeyPath();
  2444. }
  2445. else
  2446. {
  2447. Console->PrintLine(L"Type library not registered.");
  2448. }
  2449. Console->PrintLine();
  2450. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2451. Storage->GetSubKeyNames(KeyNames.get());
  2452. UnicodeString NamespacePrefix = L"WinSCP.";
  2453. Console->PrintLine(L"Classes:");
  2454. UnicodeString CommonCodeBase;
  2455. int Found = 0;
  2456. for (int Index = 0; Index < KeyNames->Count; Index++)
  2457. {
  2458. UnicodeString KeyName = KeyNames->Strings[Index];
  2459. if (StartsText(NamespacePrefix, KeyName))
  2460. {
  2461. if (Storage->OpenSubKeyPath(FORMAT(L"%s\\%s", (KeyName, L"CLSID")), false))
  2462. {
  2463. UnicodeString Class = KeyName;
  2464. UnicodeString CLSID = Trim(Storage->ReadString(UnicodeString(), UnicodeString()));
  2465. Storage->CloseSubKeyPath();
  2466. if (!CLSID.IsEmpty())
  2467. {
  2468. Keys->Add(KeyName);
  2469. UnicodeString Platforms;
  2470. CollectCLSIDKey(Console, Keys, 32, Storage.get(), CLSID, CommonCodeBase, L"32-bit", Platforms);
  2471. if (Storage64.get() != NULL)
  2472. {
  2473. CollectCLSIDKey(Console, Keys, 64, Storage64.get(), CLSID, CommonCodeBase, L"64-bit", Platforms);
  2474. }
  2475. UnicodeString Line = FORMAT(L"%s - %s", (Class, CLSID));
  2476. if (Platforms.IsEmpty())
  2477. {
  2478. Console->PrintLine(FORMAT(L"Warning: Could not find CLSID %s for class %s.", (CLSID, Class)));
  2479. }
  2480. else
  2481. {
  2482. Line += FORMAT(L" [%s]", (Platforms));
  2483. }
  2484. Console->PrintLine(Line);
  2485. Found++;
  2486. }
  2487. }
  2488. }
  2489. }
  2490. if (Found == 0)
  2491. {
  2492. Console->PrintLine(L"No classes found.");
  2493. }
  2494. Console->PrintLine();
  2495. UnicodeString InterfaceKey = L"Interface";
  2496. if (Storage->OpenSubKey(InterfaceKey, false) &&
  2497. ((Storage64.get() == NULL) || Storage64->OpenSubKey(InterfaceKey, false)))
  2498. {
  2499. Console->PrintLine(L"Interfaces:");
  2500. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2501. Storage->GetSubKeyNames(KeyNames.get());
  2502. KeyNames->Sorted = true;
  2503. for (int Index = 0; Index < KeyNames->Count; Index++)
  2504. {
  2505. KeyNames->Objects[Index] = reinterpret_cast<TObject *>(32);
  2506. }
  2507. if (Storage64.get() != NULL)
  2508. {
  2509. std::unique_ptr<TStringList> KeyNames64(new TStringList());
  2510. Storage64->GetSubKeyNames(KeyNames64.get());
  2511. for (int Index = 0; Index < KeyNames64->Count; Index++)
  2512. {
  2513. UnicodeString Key64 = KeyNames64->Strings[Index];
  2514. int Index32 = KeyNames->IndexOf(Key64);
  2515. if (Index32 >= 0)
  2516. {
  2517. KeyNames->Objects[Index32] = reinterpret_cast<TObject *>(32 | 64);
  2518. }
  2519. else
  2520. {
  2521. KeyNames->AddObject(Key64, reinterpret_cast<TObject *>(64));
  2522. }
  2523. }
  2524. }
  2525. int Found = 0;
  2526. for (int Index = 0; Index < KeyNames->Count; Index++)
  2527. {
  2528. UnicodeString KeyName = KeyNames->Strings[Index];
  2529. // Open sub key first, to check if we are interested in the interface, as an optimization
  2530. int PlatformSet = reinterpret_cast<int>(KeyNames->Objects[Index]);
  2531. THierarchicalStorage * KeyStorage = FLAGSET(PlatformSet, 32) ? Storage.get() : Storage64.get();
  2532. if (KeyStorage->OpenSubKeyPath(FORMAT(L"%s\\TypeLib", (KeyName)), false))
  2533. {
  2534. UnicodeString InterfaceTypeLib = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2535. UnicodeString Version = KeyStorage->ReadString(L"Version", UnicodeString());
  2536. KeyStorage->CloseSubKeyPath();
  2537. if (SameText(InterfaceTypeLib, TypeLib))
  2538. {
  2539. if (KeyStorage->OpenSubKey(KeyName, false))
  2540. {
  2541. UnicodeString Key = ExcludeTrailingBackslash(KeyStorage->CurrentSubKey);
  2542. UnicodeString Interface = KeyStorage->ReadString(UnicodeString(), UnicodeString());
  2543. KeyStorage->CloseSubKey();
  2544. Keys->AddObject(Key, reinterpret_cast<TObject *>(PlatformSet));
  2545. Console->PrintLine(FORMAT(L"%s - %s (%s) [%s]", (Interface, KeyName, Version, PlatformStr(PlatformSet))));
  2546. Found++;
  2547. }
  2548. }
  2549. }
  2550. }
  2551. if (Found == 0)
  2552. {
  2553. Console->PrintLine(L"No interfaces found.");
  2554. }
  2555. Storage->CloseSubKey();
  2556. Console->PrintLine();
  2557. }
  2558. if (Storage->OpenSubKey(L"Record", false))
  2559. {
  2560. Console->PrintLine(L"Value types:");
  2561. std::unique_ptr<TStringList> KeyNames(new TStringList());
  2562. Storage->GetSubKeyNames(KeyNames.get());
  2563. int Found = 0;
  2564. for (int Index = 0; Index < KeyNames->Count; Index++)
  2565. {
  2566. UnicodeString KeyName = KeyNames->Strings[Index];
  2567. if (Storage->OpenSubKey(KeyName, false))
  2568. {
  2569. std::unique_ptr<TStringList> Versions(new TStringList());
  2570. Storage->GetSubKeyNames(Versions.get());
  2571. UnicodeString VersionsStr;
  2572. std::unique_ptr<TStringList> Classes(CreateSortedStringList());
  2573. for (int Index2 = 0; Index2 < Versions->Count; Index2++)
  2574. {
  2575. UnicodeString Version = Versions->Strings[Index2];
  2576. if (Storage->OpenSubKey(Version, false))
  2577. {
  2578. UnicodeString Class = Storage->ReadString(L"Class", UnicodeString());
  2579. Classes->Add(Class);
  2580. if (StartsStr(NamespacePrefix, Class))
  2581. {
  2582. AddToList(VersionsStr, Version, L", ");
  2583. }
  2584. Storage->CloseSubKey();
  2585. }
  2586. }
  2587. if (!VersionsStr.IsEmpty())
  2588. {
  2589. if (Classes->Count != 1)
  2590. {
  2591. Console->PrintLine(FORMAT(L"Warning: Different class names for the same value type %s: %s", (KeyName, Classes->CommaText)));
  2592. }
  2593. else
  2594. {
  2595. Keys->Add(ExcludeTrailingBackslash(Storage->CurrentSubKey));
  2596. Console->PrintLine(FORMAT(L"%s - %s (%s)", (Classes->Strings[0], KeyName, VersionsStr)));
  2597. Found++;
  2598. }
  2599. }
  2600. Storage->CloseSubKey();
  2601. }
  2602. }
  2603. if (Found == 0)
  2604. {
  2605. Console->PrintLine(L"No value types found.");
  2606. }
  2607. Storage->CloseSubKey();
  2608. Console->PrintLine();
  2609. }
  2610. }
  2611. }
  2612. //---------------------------------------------------------------------------
  2613. bool DoUnregisterChoice(TConsole * Console)
  2614. {
  2615. return (Console->Choice(L"U", -1, -1, -1, 0, 0, 0, UnicodeString()) == 1);
  2616. }
  2617. //---------------------------------------------------------------------------
  2618. typedef HRESULT WINAPI (* RegDeleteTreeProc)(HKEY Key, LPCWSTR SubKey);
  2619. static RegDeleteTreeProc ARegDeleteTree = NULL;
  2620. //---------------------------------------------------------------------------
  2621. void DoDeleteKey(TConsole * Console, TRegistry * Registry, const UnicodeString & Key, int Platform, bool & AnyDeleted, bool & AllDeleted)
  2622. {
  2623. UnicodeString ParentKey = ExtractFileDir(Key);
  2624. UnicodeString ChildKey = ExtractFileName(Key);
  2625. bool Result = Registry->OpenKey(ParentKey, false);
  2626. if (Result)
  2627. {
  2628. if (DebugAlwaysFalse(ARegDeleteTree == NULL))
  2629. {
  2630. Result = false;
  2631. }
  2632. else
  2633. {
  2634. Result = (ARegDeleteTree(Registry->CurrentKey, ChildKey.c_str()) == 0);
  2635. }
  2636. Registry->CloseKey();
  2637. }
  2638. UnicodeString Status;
  2639. if (Result)
  2640. {
  2641. Status = L"removed";
  2642. AnyDeleted = true;
  2643. }
  2644. else
  2645. {
  2646. AllDeleted = false;
  2647. Status = L"NOT removed";
  2648. }
  2649. Console->PrintLine(FORMAT(L"%s [%s] - %s", (Key, PlatformStr(Platform), Status)));
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. int ComRegistration(TConsole * Console)
  2653. {
  2654. int Result = RESULT_SUCCESS;
  2655. try
  2656. {
  2657. if (ARegDeleteTree == NULL)
  2658. {
  2659. HINSTANCE AdvapiLibrary = LoadLibrary(L"advapi32.dll");
  2660. if (DebugAlwaysTrue(AdvapiLibrary != NULL))
  2661. {
  2662. ARegDeleteTree = reinterpret_cast<RegDeleteTreeProc>(GetProcAddress(AdvapiLibrary, "RegDeleteTreeW"));
  2663. }
  2664. }
  2665. if (ARegDeleteTree == NULL)
  2666. {
  2667. throw Exception(FORMAT(L"Not supported on %s", (GetOSInfo())));
  2668. }
  2669. Console->PrintLine(GetEnvironmentInfo());
  2670. Console->PrintLine();
  2671. std::unique_ptr<TStrings> Keys(new TStringList());
  2672. DoCollectComRegistration(Console, Keys.get());
  2673. if (Keys->Count == 0)
  2674. {
  2675. Console->PrintLine(L"No registration found.");
  2676. Console->WaitBeforeExit();
  2677. }
  2678. else
  2679. {
  2680. Console->PrintLine(L"Press (U) to unregister or Esc to exit...");
  2681. if (DoUnregisterChoice(Console))
  2682. {
  2683. Console->PrintLine();
  2684. Console->PrintLine(L"The following registry keys will be removed from HKCR registry hive:");
  2685. for (int Index = 0; Index < Keys->Count; Index++)
  2686. {
  2687. Console->PrintLine(FORMAT(L"%s [%s]", (Keys->Strings[Index], PlatformStr(reinterpret_cast<int>(Keys->Objects[Index])))));
  2688. }
  2689. Console->PrintLine();
  2690. Console->PrintLine(L"You need Administrator privileges to remove the keys.");
  2691. Console->PrintLine(L"Press (U) again to proceed with unregistration or Esc to abort...");
  2692. if (DoUnregisterChoice(Console))
  2693. {
  2694. std::unique_ptr<TRegistry> Registry64(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_64KEY));
  2695. Registry64->RootKey = HKEY_CLASSES_ROOT;
  2696. std::unique_ptr<TRegistry> Registry32(new TRegistry(KEY_READ | KEY_WRITE | KEY_WOW64_32KEY));
  2697. Registry32->RootKey = HKEY_CLASSES_ROOT;
  2698. bool AnyDeleted = false;
  2699. bool AllDeleted = true;
  2700. for (int Index = 0; Index < Keys->Count; Index++)
  2701. {
  2702. UnicodeString Key = Keys->Strings[Index];
  2703. int PlatformSet = reinterpret_cast<int>(Keys->Objects[Index]);
  2704. if (PlatformSet == 0)
  2705. {
  2706. DoDeleteKey(Console, Registry32.get(), Key, 0, AnyDeleted, AllDeleted);
  2707. }
  2708. else
  2709. {
  2710. if (FLAGSET(PlatformSet, 32))
  2711. {
  2712. DoDeleteKey(Console, Registry32.get(), Key, 32, AnyDeleted, AllDeleted);
  2713. }
  2714. if (FLAGSET(PlatformSet, 64))
  2715. {
  2716. DoDeleteKey(Console, Registry64.get(), Key, 64, AnyDeleted, AllDeleted);
  2717. }
  2718. }
  2719. }
  2720. Console->PrintLine();
  2721. if (!AnyDeleted)
  2722. {
  2723. Console->PrintLine(L"No keys were removed. Make sure you have Administrator privileges.");
  2724. }
  2725. else if (!AllDeleted)
  2726. {
  2727. Console->PrintLine(L"Some keys were not removed. Make sure you have Administrator privileges.");
  2728. }
  2729. else
  2730. {
  2731. Console->PrintLine(L"All keys were removed. Unregistration succeeded.");
  2732. }
  2733. Console->WaitBeforeExit();
  2734. }
  2735. }
  2736. }
  2737. }
  2738. catch (Exception & E)
  2739. {
  2740. Result = HandleException(Console, E);
  2741. Console->WaitBeforeExit();
  2742. }
  2743. return Result;
  2744. }