Setup.cpp 99 KB

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