Setup.cpp 104 KB

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