1
0

Setup.cpp 98 KB

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