Setup.cpp 96 KB

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