Setup.cpp 99 KB

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