1
0

Setup.cpp 95 KB

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