diff --git a/.gitmodules b/.gitmodules index 6c6fd723..547993f9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,6 +6,3 @@ path = Dependencies/Steamworks.NET url = https://github.com/marchc1/Steamworks.NET branch = 1-64 -[submodule "Dependencies/CEF"] - path = Dependencies/CEF - url = https://github.com/SourceDotNet/CEF-SDK.git diff --git a/.vscode/launch.json b/.vscode/launch.json index 3392cdbe..5794ece5 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,8 +6,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Debug/Source.Launcher.exe", - "linux": { "program": "${workspaceFolder}/Build/Debug/Source.Launcher" }, + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", "cwd": "${workspaceFolder}/Build/Debug", // "args": ["-noworkshop", "-noaddons"], "stopAtEntry": false @@ -17,23 +16,11 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Debug/Source.Launcher.exe", - "linux": { "program": "${workspaceFolder}/Build/Debug/Source.Launcher" }, + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", "cwd": "${workspaceFolder}/Build/Debug", "stopAtEntry": false, "console": "externalTerminal" }, - { - "name": "Source.LauncherMain (no sandbox)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Debug/Source.LauncherMain.dll", - "linux": { "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll" }, - "cwd": "${workspaceFolder}/Build/Debug", - "args": ["-nochromiumsandbox"], - "stopAtEntry": false - }, { "name": "Source.Dedicated", "type": "coreclr", diff --git a/Dependencies/CEF b/Dependencies/CEF deleted file mode 160000 index c1194733..00000000 --- a/Dependencies/CEF +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c1194733f6f36d52e3b4ee3152fe2db74cd85a2b diff --git a/HTML.CEF.Process/HTML.CEF.Process.csproj b/HTML.CEF.Process/HTML.CEF.Process.csproj new file mode 100644 index 00000000..5f26724b --- /dev/null +++ b/HTML.CEF.Process/HTML.CEF.Process.csproj @@ -0,0 +1,16 @@ + + + + WinExe + net10.0 + enable + enable + Debug;Release;Debug (Dedicated);Release (Dedicated) + true + + + + + + + diff --git a/HTML.CEF.Process/ProcessLockdown.cs b/HTML.CEF.Process/ProcessLockdown.cs new file mode 100644 index 00000000..1edc4fda --- /dev/null +++ b/HTML.CEF.Process/ProcessLockdown.cs @@ -0,0 +1,176 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace HTML.CEF.Process; + +[SupportedOSPlatform("windows")] +static unsafe partial class ProcessLockdown +{ + const string LowIntegritySid = "S-1-16-4096"; + + const uint TokenQuery = 0x0008; + const uint TokenAdjustPrivileges = 0x0020; + const uint TokenAdjustDefault = 0x0080; + const int TokenIntegrityLevel = 25; + const uint SeGroupIntegrity = 0x00000020; + + const int JobObjectBasicUIRestrictions = 4; + const int JobObjectExtendedLimitInformation = 9; + const uint JobObjectLimitActiveProcess = 0x00000008; + const uint JobObjectUILimitAll = 0x000000FF; + + const int ProcessStrictHandleCheckPolicy = 3; + const int ProcessExtensionPointDisablePolicy = 6; + const int ProcessFontDisablePolicy = 9; + const int ProcessImageLoadPolicy = 10; + + const uint StrictHandleCheckRaiseAndPermanent = 0x3; + const uint ExtensionPointsDisabled = 0x1; + const uint NonSystemFontsDisabled = 0x1; + const uint NoRemoteAndLowLabelImages = 0x3; + + [StructLayout(LayoutKind.Sequential)] + struct JobObjectBasicLimitInformation + { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public nuint MinimumWorkingSetSize; + public nuint MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public nuint Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + struct IoCounters + { + public ulong ReadOperationCount; + public ulong WriteOperationCount; + public ulong OtherOperationCount; + public ulong ReadTransferCount; + public ulong WriteTransferCount; + public ulong OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + struct JobObjectExtendedLimitInformationData + { + public JobObjectBasicLimitInformation BasicLimitInformation; + public IoCounters IoInfo; + public nuint ProcessMemoryLimit; + public nuint JobMemoryLimit; + public nuint PeakProcessMemoryUsed; + public nuint PeakJobMemoryUsed; + } + + [StructLayout(LayoutKind.Sequential)] + struct TokenMandatoryLabel + { + public nint Sid; + public uint Attributes; + } + + [LibraryImport("kernel32.dll")] + private static partial nint GetCurrentProcess(); + + [LibraryImport("kernel32.dll")] + private static partial int CloseHandle(nint handle); + + [LibraryImport("kernel32.dll")] + private static partial nint LocalFree(nint mem); + + [LibraryImport("kernel32.dll", EntryPoint = "CreateJobObjectW")] + private static partial nint CreateJobObject(nint jobAttributes, nint name); + + [LibraryImport("kernel32.dll")] + private static partial int SetInformationJobObject(nint job, int infoClass, void* info, uint infoLength); + + [LibraryImport("kernel32.dll")] + private static partial int AssignProcessToJobObject(nint job, nint process); + + [LibraryImport("kernel32.dll")] + private static partial int SetProcessMitigationPolicy(int policy, void* buffer, nuint length); + + [LibraryImport("advapi32.dll")] + private static partial int OpenProcessToken(nint process, uint desiredAccess, out nint token); + + [LibraryImport("advapi32.dll")] + private static partial int AdjustTokenPrivileges(nint token, int disableAllPrivileges, nint newState, uint bufferLength, nint previousState, nint returnLength); + + [LibraryImport("advapi32.dll", EntryPoint = "ConvertStringSidToSidW", StringMarshalling = StringMarshalling.Utf16)] + private static partial int ConvertStringSidToSid(string stringSid, out nint sid); + + [LibraryImport("advapi32.dll")] + private static partial uint GetLengthSid(nint sid); + + [LibraryImport("advapi32.dll")] + private static partial int SetTokenInformation(nint token, int infoClass, void* info, uint infoLength); + + public static bool Apply(ReadOnlySpan processType) { + bool isRenderer = processType.SequenceEqual("renderer"); + + if (!SetMitigation(ProcessExtensionPointDisablePolicy, ExtensionPointsDisabled)) + return false; + if (!SetMitigation(ProcessImageLoadPolicy, NoRemoteAndLowLabelImages)) + return false; + if (!RestrictJob(isRenderer)) + return false; + + if (isRenderer) { + if (!SetMitigation(ProcessStrictHandleCheckPolicy, StrictHandleCheckRaiseAndPermanent)) + return false; + if (!SetMitigation(ProcessFontDisablePolicy, NonSystemFontsDisabled)) + return false; + } + + return LowerToken(); + } + + static bool SetMitigation(int policy, uint flags) => SetProcessMitigationPolicy(policy, &flags, sizeof(uint)) != 0; + + static bool RestrictJob(bool restrictUI) { + nint job = CreateJobObject(0, 0); + if (job == 0) + return false; + + JobObjectExtendedLimitInformationData limits = default; + limits.BasicLimitInformation.LimitFlags = JobObjectLimitActiveProcess; + limits.BasicLimitInformation.ActiveProcessLimit = 1; + if (SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, (uint)sizeof(JobObjectExtendedLimitInformationData)) == 0) + return false; + + if (restrictUI) { + uint uiRestrictions = JobObjectUILimitAll; + if (SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uint)) == 0) + return false; + } + + return AssignProcessToJobObject(job, GetCurrentProcess()) != 0; + } + + static bool LowerToken() { + if (OpenProcessToken(GetCurrentProcess(), TokenQuery | TokenAdjustPrivileges | TokenAdjustDefault, out nint token) == 0) + return false; + + try { + if (AdjustTokenPrivileges(token, 1, 0, 0, 0, 0) == 0) + return false; + + if (ConvertStringSidToSid(LowIntegritySid, out nint sid) == 0) + return false; + + try { + TokenMandatoryLabel label = new() { Sid = sid, Attributes = SeGroupIntegrity }; + return SetTokenInformation(token, TokenIntegrityLevel, &label, (uint)sizeof(TokenMandatoryLabel) + GetLengthSid(sid)) != 0; + } + finally { + LocalFree(sid); + } + } + finally { + CloseHandle(token); + } + } +} diff --git a/HTML.CEF.Process/Program.cs b/HTML.CEF.Process/Program.cs new file mode 100644 index 00000000..6418ad61 --- /dev/null +++ b/HTML.CEF.Process/Program.cs @@ -0,0 +1,51 @@ +using System.Runtime.InteropServices; + +using Xilium.CefGlue; + +namespace HTML.CEF.Process; + +static partial class Program +{ + const int MainThreadStackSize = 8 * 1024 * 1024; + const int PrSetPdeathsig = 1; + const int SigKill = 9; + const string ProcessTypeSwitch = "--type="; + + [LibraryImport("libc", EntryPoint = "prctl")] + private static partial int Prctl(int option, nuint arg2); + + static ReadOnlySpan GetProcessType(string[] args) { + foreach (string arg in args) { + if (arg.StartsWith(ProcessTypeSwitch, StringComparison.Ordinal)) + return arg.AsSpan(ProcessTypeSwitch.Length); + } + return []; + } + + static int Main() { + if (OperatingSystem.IsLinux()) + Prctl(PrSetPdeathsig, SigKill); + + if (OperatingSystem.IsWindows()) + CefRuntime.Load(AppContext.BaseDirectory); + else + CefRuntime.Load(); + + string[] args = Environment.GetCommandLineArgs(); + + if (OperatingSystem.IsWindows() && !ProcessLockdown.Apply(GetProcessType(args))) + return 1; + + CefMainArgs mainArgs = new(args); + SubprocessApp app = new(); + + if (!OperatingSystem.IsWindows()) + return CefRuntime.ExecuteProcess(mainArgs, app, 0); + + int exitCode = 0; + Thread thread = new(() => exitCode = CefRuntime.ExecuteProcess(mainArgs, app, 0), MainThreadStackSize); + thread.Start(); + thread.Join(); + return exitCode; + } +} diff --git a/HTML.CEF.Process/RenderProcessHandler.cs b/HTML.CEF.Process/RenderProcessHandler.cs new file mode 100644 index 00000000..56000d76 --- /dev/null +++ b/HTML.CEF.Process/RenderProcessHandler.cs @@ -0,0 +1,367 @@ +using Xilium.CefGlue; + +namespace HTML.CEF.Process; + +sealed class RenderProcessHandler : CefRenderProcessHandler +{ + readonly record struct Callback(int BrowserId, CefV8Context Context, CefV8Value Function); + + sealed class FunctionHandler(RenderProcessHandler owner) : CefV8Handler + { + protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { + returnValue = null!; + exception = null!; + return owner.Execute(name, arguments, ref exception); + } + } + + const int MaxDepth = 16; + const int MaxCallbacks = 16384; + + readonly FunctionHandler Handler; + readonly Dictionary> Functions = []; + readonly Dictionary Synced = []; + readonly Dictionary Callbacks = []; + int NextCallbackId; + + public RenderProcessHandler() { + Handler = new(this); + } + + static bool V8ValueToCefValue(CefValue outValue, CefV8Value? inValue, int depth = 0) { + if (depth > MaxDepth) + return false; + + if (inValue == null || inValue.IsNull || inValue.IsUndefined) { + outValue.SetNull(); + } + else if (inValue.IsBool) { + outValue.SetBool(inValue.GetBoolValue()); + } + else if (inValue.IsInt || inValue.IsUInt || inValue.IsDouble) { + outValue.SetDouble(inValue.GetDoubleValue()); + } + else if (inValue.IsString) { + outValue.SetString(inValue.GetStringValue()); + } + else if (inValue.IsArray) { + int arrayLen = inValue.GetArrayLength(); + CefListValue newList = CefListValue.Create(); + newList.SetSize(arrayLen); + + for (int i = 0; i < arrayLen; i++) { + CefValue newValue = CefValue.Create(); + if (!V8ValueToCefValue(newValue, inValue.GetValue(i), depth + 1)) + return false; + newList.SetValue(i, newValue); + } + + outValue.SetList(newList); + } + else if (inValue.IsObject) { + CefDictionaryValue newMap = CefDictionaryValue.Create(); + + foreach (string key in inValue.GetKeys()) { + CefValue newValue = CefValue.Create(); + if (!V8ValueToCefValue(newValue, inValue.GetValue(key), depth + 1)) + return false; + newMap.SetValue(key, newValue); + } + + outValue.SetDictionary(newMap); + } + else { + outValue.SetNull(); + } + + return true; + } + + static bool V8ValuesToCefList(CefListValue outList, CefV8Value[] inList) { + outList.SetSize(inList.Length); + + for (int i = 0; i < inList.Length; i++) { + CefValue newValue = CefValue.Create(); + if (!V8ValueToCefValue(newValue, inList[i])) + return false; + outList.SetValue(i, newValue); + } + + return true; + } + + static bool CefValueToV8Value(out CefV8Value outValue, CefValue inValue, int depth = 0) { + outValue = null!; + + if (depth > MaxDepth) + return false; + + switch (inValue.GetValueType()) { + case CefValueType.Bool: + outValue = CefV8Value.CreateBool(inValue.GetBool()); + break; + case CefValueType.Int: + outValue = CefV8Value.CreateInt(inValue.GetInt()); + break; + case CefValueType.Double: + outValue = CefV8Value.CreateDouble(inValue.GetDouble()); + break; + case CefValueType.String: + outValue = CefV8Value.CreateString(inValue.GetString()); + break; + case CefValueType.List: { + CefListValue inList = inValue.GetList(); + outValue = CefV8Value.CreateArray(inList.Count); + + for (int i = 0; i < inList.Count; i++) { + if (!CefValueToV8Value(out CefV8Value entry, inList.GetValue(i), depth + 1)) + return false; + outValue.SetValue(i, entry); + } + break; + } + case CefValueType.Dictionary: { + CefDictionaryValue inMap = inValue.GetDictionary(); + outValue = CefV8Value.CreateObject(); + + foreach (string key in inMap.GetKeys()) { + if (!CefValueToV8Value(out CefV8Value value, inMap.GetValue(key), depth + 1)) + return false; + outValue.SetValue(key, value, CefV8PropertyAttribute.None); + } + break; + } + default: + outValue = CefV8Value.CreateUndefined(); + break; + } + + return true; + } + + static bool CefListToV8Values(out CefV8Value[] outList, ICefListValue inList) { + outList = new CefV8Value[inList.Count]; + + for (int i = 0; i < outList.Length; i++) { + if (!CefValueToV8Value(out outList[i], inList.GetValue(i))) + return false; + } + + return true; + } + + List<(string ObjName, string FuncName)> GetFunctions(int browserId) { + if (!Functions.TryGetValue(browserId, out List<(string ObjName, string FuncName)>? functions)) { + functions = []; + Functions[browserId] = functions; + } + return functions; + } + + protected override void OnBrowserCreated(CefBrowser browser, CefDictionaryValue? extraInfo) { + List<(string ObjName, string FuncName)> functions = GetFunctions(browser.Identifier); + + if (extraInfo != null && extraInfo.GetValueType("functions") == CefValueType.List) { + ICefListValue list = extraInfo.GetList("functions"); + for (int i = 0; i < list.Count; i++) { + if (list.GetValueType(i) != CefValueType.List) + continue; + + ICefListValue pair = list.GetList(i); + if (pair.Count == 2 && pair.GetValueType(0) == CefValueType.String && pair.GetValueType(1) == CefValueType.String) + functions.Add((pair.GetString(0), pair.GetString(1))); + } + } + + RequestFunctions(browser); + } + + protected override void OnBrowserDestroyed(CefBrowser browser) { + int browserId = browser.Identifier; + Functions.Remove(browserId); + Synced.Remove(browserId); + + foreach (KeyValuePair pair in Callbacks.ToArray()) { + if (pair.Value.BrowserId == browserId) + Callbacks.Remove(pair.Key); + } + } + + void RequestFunctions(CefBrowser browser) { + int browserId = browser.Identifier; + if (Synced.TryGetValue(browserId, out bool synced) && synced) + return; + + CefFrame? mainFrame = browser.GetMainFrame(); + if (mainFrame == null) + return; + + mainFrame.SendProcessMessage(CefProcessId.Browser, CefProcessMessage.Create("SyncFunctions")); + Synced[browserId] = true; + } + + protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { + context.Enter(); + { + context.GetGlobal().DeleteValue("print"); + context.GetGlobal().DeleteValue("openDatabase"); + } + context.Exit(); + + if (browser == null) + return; + + RequestFunctions(browser); + + if (!Functions.TryGetValue(browser.Identifier, out List<(string ObjName, string FuncName)>? functions)) + return; + + foreach ((string objName, string funcName) in functions) + RegisterFunctionInFrame(frame, objName, funcName); + } + + protected override bool OnProcessMessageReceived(CefBrowser browser, CefFrame frame, CefProcessId sourceProcess, CefProcessMessage message) { + if (sourceProcess != CefProcessId.Browser) + return false; + + string name = message.Name; + CefListValue args = message.Arguments!; + + switch (name) { + case "RegisterFunction": + RegisterFunction(browser, args); + return true; + case "ExecuteCallback": + ExecuteCallback(args); + return true; + case "ForgetCallback": + ForgetCallback(args); + return true; + } + + return false; + } + + bool Execute(string name, CefV8Value[] arguments, ref string exception) { + CefV8Context context = CefV8Context.GetCurrentContext(); + CefBrowser? browser = context.GetBrowser(); + CefFrame? frame = context.GetFrame(); + + if (browser == null || frame == null) { + exception = "CefV8Context::GetBrowser == nullptr"; + return true; + } + + int delimPos = name.IndexOf('#'); + if (delimPos == -1) { + exception = "SourceApp::Execute couldn't parse this function's name"; + return true; + } + + string objName = name[..delimPos]; + string funcName = name[(delimPos + 1)..]; + + CefListValue argsList = CefListValue.Create(); + if (!V8ValuesToCefList(argsList, arguments)) { + exception = "failed to serialize parameters (did you return a deeply nested structure?)"; + return true; + } + + CefProcessMessage message = CefProcessMessage.Create("ExecuteFunction"); + CefListValue args = message.Arguments!; + + args.SetString(0, objName); + args.SetString(1, funcName); + + if (arguments.Length == 0 || !arguments[^1].IsFunction) { + args.SetInt(2, -1); + } + else { + args.SetInt(2, CreateCallback(browser.Identifier, context, arguments[^1])); + argsList.Remove(argsList.Count - 1); + } + + args.SetList(3, argsList); + + frame.SendProcessMessage(CefProcessId.Browser, message); + return true; + } + + int CreateCallback(int browserId, CefV8Context context, CefV8Value func) { + if (Callbacks.ContainsKey(NextCallbackId)) + return -1; + + CefObjectTracker.Untrack(context); + CefObjectTracker.Untrack(func); + + int callbackId = NextCallbackId; + Callbacks.Add(callbackId, new Callback(browserId, context, func)); + + NextCallbackId++; + if (NextCallbackId >= MaxCallbacks) + NextCallbackId = 0; + + return callbackId; + } + + void RegisterFunctionInFrame(CefFrame? frame, string objName, string funcName) { + if (frame == null) + return; + + CefV8Context? context = frame.V8Context; + if (context == null || !context.IsValid) + return; + + string fullName = objName + "#" + funcName; + + context.Enter(); + { + CefV8Value window = context.GetGlobal(); + CefV8Value? obj = window.GetValue(objName); + + if (obj == null || !obj.IsObject) { + obj = CefV8Value.CreateObject(); + window.SetValue(objName, obj, CefV8PropertyAttribute.None); + } + + obj.SetValue(funcName, CefV8Value.CreateFunction(fullName, Handler), CefV8PropertyAttribute.None); + } + context.Exit(); + } + + void RegisterFunction(CefBrowser browser, CefListValue args) { + string objName = args.GetString(0); + string funcName = args.GetString(1); + + List<(string ObjName, string FuncName)> functions = GetFunctions(browser.Identifier); + foreach ((string ObjName, string FuncName) pair in functions) { + if (pair.ObjName == objName && pair.FuncName == funcName) + return; + } + functions.Add((objName, funcName)); + + foreach (string frameId in browser.GetFrameIdentifiers()) + RegisterFunctionInFrame(browser.GetFrameByIdentifier(frameId), objName, funcName); + } + + void ExecuteCallback(CefListValue args) { + if (!Callbacks.Remove(args.GetInt(0), out Callback callback)) + return; + + if (!callback.Context.IsValid) + return; + + ICefListValue argList = args.GetList(1); + + callback.Context.Enter(); + { + if (CefListToV8Values(out CefV8Value[] arguments, argList)) + callback.Function.ExecuteFunction(null!, arguments); + } + callback.Context.Exit(); + } + + void ForgetCallback(CefListValue args) { + Callbacks.Remove(args.GetInt(0)); + } +} diff --git a/HTML.CEF.Process/SubprocessApp.cs b/HTML.CEF.Process/SubprocessApp.cs new file mode 100644 index 00000000..31466cb4 --- /dev/null +++ b/HTML.CEF.Process/SubprocessApp.cs @@ -0,0 +1,14 @@ +using Xilium.CefGlue; + +namespace HTML.CEF.Process; + +sealed class SubprocessApp : CefApp +{ + readonly RenderProcessHandler RenderHandler = new(); + + protected override void OnRegisterCustomSchemes(CefSchemeRegistrar registrar) { + registrar.AddCustomScheme("asset", CefSchemeOptions.Standard | CefSchemeOptions.CspBypassing); + } + + protected override CefRenderProcessHandler GetRenderProcessHandler() => RenderHandler; +} diff --git a/HTML.CEF/CefApplication.cs b/HTML.CEF/CefApplication.cs index b58c190f..47d1f6ea 100644 --- a/HTML.CEF/CefApplication.cs +++ b/HTML.CEF/CefApplication.cs @@ -8,6 +8,9 @@ protected override void OnBeforeCommandLineProcessing(string processType, CefCom if (!string.IsNullOrEmpty(processType)) return; + if (OperatingSystem.IsLinux()) + commandLine.AppendSwitch("no-zygote"); + commandLine.AppendSwitch("disable-gpu"); commandLine.AppendSwitch("disable-gpu-compositing"); commandLine.AppendSwitch("disable-smooth-scrolling"); diff --git a/HTML.CEF/CefSystem.cs b/HTML.CEF/CefSystem.cs index 5bd37288..ac26bb6f 100644 --- a/HTML.CEF/CefSystem.cs +++ b/HTML.CEF/CefSystem.cs @@ -1,7 +1,5 @@ using Source.Common.GarrysMod; -using System.Globalization; - using Xilium.CefGlue; namespace HTML.CEF; @@ -11,9 +9,6 @@ public class CefSystem : IHtmlSystem public static readonly CefSystem g_CefSystem = new(); public static readonly IHtmlSystem g_pHtmlSystem = g_CefSystem; - const string SandboxInfoProperty = "SN_CEF_SANDBOX_INFO"; - const string NoSandboxParm = "-nochromiumsandbox"; - readonly IHtmlSystem Fallback = HTML.Stub.StubSystem.g_pHtmlSystem; bool Initialized; @@ -22,39 +17,15 @@ public class CefSystem : IHtmlSystem readonly Lock RequestsLock = new(); List Requests = []; - static bool HasParm(string parm) { - foreach (string arg in Environment.GetCommandLineArgs()) - if (string.Equals(arg, parm, StringComparison.OrdinalIgnoreCase)) - return true; - return false; - } - - static nint GetSandboxInfo() { - if (AppContext.GetData(SandboxInfoProperty) is not string hex) - return 0; - return long.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long value) ? (nint)value : 0; - } - public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandler) { ResourceHandler.g_pHtmlResourceHandler = resourceHandler; string baseDir = new(pBaseDir); string chromiumDir = AppContext.BaseDirectory; + string rootCachePath = Path.Combine(baseDir, "cache", "chromium"); - nint sandboxInfo = 0; - bool noSandbox = false; - if (OperatingSystem.IsWindows()) { - sandboxInfo = GetSandboxInfo(); - if (sandboxInfo == 0) { - if (!HasParm(NoSandboxParm)) { - resourceHandler.Message("Chromium: not started through Source.Launcher.exe, so there is no sandbox. Refusing to start Chromium unsandboxed (use -nochromiumsandbox to override for debugging).\n"); - return false; - } - - resourceHandler.Message("Chromium: WARNING - running WITHOUT the Chromium sandbox (-nochromiumsandbox). Web content runs with full user privileges!\n"); - noSandbox = true; - } - } + if (OperatingSystem.IsWindows() && !LowIntegrityLabel.Apply(rootCachePath)) + resourceHandler.Message($"Chromium: failed to set a low integrity label on {rootCachePath}, cookies and storage will not persist.\n"); try { if (OperatingSystem.IsWindows()) @@ -69,26 +40,22 @@ public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandl CefSettings settings = new() { WindowlessRenderingEnabled = true, - NoSandbox = noSandbox, + NoSandbox = true, MultiThreadedMessageLoop = OperatingSystem.IsWindows(), ExternalMessagePump = false, CommandLineArgsDisabled = true, RemoteDebuggingPort = 0, LogSeverity = CefLogSeverity.Default, LogFile = Path.Combine(baseDir, "chromium.log"), - RootCachePath = Path.Combine(baseDir, "cache", "chromium"), + RootCachePath = rootCachePath, UserAgent = "Mozilla/5.0 (Windows NT; Valve Source Client) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 GMod/13", ResourcesDirPath = chromiumDir, LocalesDirPath = Path.Combine(chromiumDir, "locales"), + BrowserSubprocessPath = Path.Combine(chromiumDir, OperatingSystem.IsWindows() ? "HTML.CEF.Process.exe" : "HTML.CEF.Process"), }; - if (!OperatingSystem.IsWindows()) - settings.BrowserSubprocessPath = Path.Combine(chromiumDir, "Source.Launcher.CEF"); - else if (noSandbox) - settings.BrowserSubprocessPath = Path.Combine(chromiumDir, "Source.Launcher.exe"); - try { - CefRuntime.Initialize(new CefMainArgs([]), settings, new CefApplication(), sandboxInfo); + CefRuntime.Initialize(new CefMainArgs([]), settings, new CefApplication(), 0); } catch (Exception e) { resourceHandler.Message($"Chromium failed to initialize: {e.Message}\n"); @@ -99,7 +66,7 @@ public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandl RegisterScheme("mapimage", new ResourceHandlerFactory()); RegisterScheme("html", new HtmlResourceHandlerFactory()); - resourceHandler.Message($"Chromium {CefRuntime.ChromeVersion} initialized ({(noSandbox ? "UNSANDBOXED" : "sandboxed")}).\n"); + resourceHandler.Message($"Chromium {CefRuntime.ChromeVersion} initialized.\n"); Initialized = true; return true; } diff --git a/HTML.CEF/LowIntegrityLabel.cs b/HTML.CEF/LowIntegrityLabel.cs new file mode 100644 index 00000000..f0cb6eb8 --- /dev/null +++ b/HTML.CEF/LowIntegrityLabel.cs @@ -0,0 +1,71 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace HTML.CEF; + +[SupportedOSPlatform("windows")] +static partial class LowIntegrityLabel +{ + const string LowIntegrityInheritedSddl = "S:(ML;OICI;NW;;;LW)"; + const uint SddlRevision1 = 1; + const int SeFileObject = 1; + const uint LabelSecurityInformation = 0x00000010; + + [LibraryImport("advapi32.dll", EntryPoint = "ConvertStringSecurityDescriptorToSecurityDescriptorW", StringMarshalling = StringMarshalling.Utf16)] + private static partial int ConvertStringSecurityDescriptorToSecurityDescriptor(string stringSecurityDescriptor, uint revision, out nint securityDescriptor, nint securityDescriptorSize); + + [LibraryImport("advapi32.dll", EntryPoint = "ConvertSecurityDescriptorToStringSecurityDescriptorW")] + private static partial int ConvertSecurityDescriptorToStringSecurityDescriptor(nint securityDescriptor, uint revision, uint securityInformation, out nint stringSecurityDescriptor, nint stringSecurityDescriptorLen); + + [LibraryImport("advapi32.dll")] + private static partial int GetSecurityDescriptorSacl(nint securityDescriptor, out int saclPresent, out nint sacl, out int saclDefaulted); + + [LibraryImport("advapi32.dll", EntryPoint = "GetNamedSecurityInfoW", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint GetNamedSecurityInfo(string objectName, int objectType, uint securityInfo, nint owner, nint group, nint dacl, out nint sacl, out nint securityDescriptor); + + [LibraryImport("advapi32.dll", EntryPoint = "SetNamedSecurityInfoW", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint SetNamedSecurityInfo(string objectName, int objectType, uint securityInfo, nint owner, nint group, nint dacl, nint sacl); + + [LibraryImport("kernel32.dll")] + private static partial nint LocalFree(nint mem); + + static bool IsApplied(string directory) { + if (GetNamedSecurityInfo(directory, SeFileObject, LabelSecurityInformation, 0, 0, 0, out _, out nint securityDescriptor) != 0) + return false; + + try { + if (ConvertSecurityDescriptorToStringSecurityDescriptor(securityDescriptor, SddlRevision1, LabelSecurityInformation, out nint sddl, 0) == 0) + return false; + + try { + return Marshal.PtrToStringUni(sddl) == LowIntegrityInheritedSddl; + } + finally { + LocalFree(sddl); + } + } + finally { + LocalFree(securityDescriptor); + } + } + + public static bool Apply(string directory) { + Directory.CreateDirectory(directory); + + if (IsApplied(directory)) + return true; + + if (ConvertStringSecurityDescriptorToSecurityDescriptor(LowIntegrityInheritedSddl, SddlRevision1, out nint securityDescriptor, 0) == 0) + return false; + + try { + if (GetSecurityDescriptorSacl(securityDescriptor, out int saclPresent, out nint sacl, out _) == 0 || saclPresent == 0) + return false; + + return SetNamedSecurityInfo(directory, SeFileObject, LabelSecurityInformation, 0, 0, 0, sacl) == 0; + } + finally { + LocalFree(securityDescriptor); + } + } +} diff --git a/Source.Launcher.Native/App.cpp b/Source.Launcher.Native/App.cpp deleted file mode 100644 index 5fefe01b..00000000 --- a/Source.Launcher.Native/App.cpp +++ /dev/null @@ -1,379 +0,0 @@ -#include "App.h" - -#include "include/cef_process_message.h" -#include "include/cef_values.h" - -static bool V8ValueToCefValue(CefRefPtr outValue, const CefRefPtr& inValue, int depth = 0) -{ - if (depth > 16) - return false; - - if (!inValue || inValue->IsNull() || inValue->IsUndefined()) { - outValue->SetNull(); - } - else if (inValue->IsBool()) { - outValue->SetBool(inValue->GetBoolValue()); - } - else if (inValue->IsInt() || inValue->IsUInt() || inValue->IsDouble()) { - outValue->SetDouble(inValue->GetDoubleValue()); - } - else if (inValue->IsString()) { - outValue->SetString(inValue->GetStringValue()); - } - else if (inValue->IsArray()) { - int arrayLen = inValue->GetArrayLength(); - CefRefPtr newList = CefListValue::Create(); - newList->SetSize(arrayLen); - - for (int i = 0; i < arrayLen; i++) { - CefRefPtr newValue = CefValue::Create(); - if (!V8ValueToCefValue(newValue, inValue->GetValue(i), depth + 1)) - return false; - newList->SetValue(i, newValue); - } - - outValue->SetList(newList); - } - else if (inValue->IsObject()) { - CefRefPtr newMap = CefDictionaryValue::Create(); - std::vector keys; - inValue->GetKeys(keys); - - for (const CefString& key : keys) { - CefRefPtr newValue = CefValue::Create(); - if (!V8ValueToCefValue(newValue, inValue->GetValue(key), depth + 1)) - return false; - newMap->SetValue(key, newValue); - } - - outValue->SetDictionary(newMap); - } - else { - outValue->SetNull(); - } - - return true; -} - -static bool V8ValuesToCefList(CefRefPtr& outList, const CefV8ValueList& inList) -{ - outList->SetSize(inList.size()); - - size_t index = 0; - for (const CefRefPtr& x : inList) { - CefRefPtr newValue = CefValue::Create(); - if (!V8ValueToCefValue(newValue, x)) - return false; - outList->SetValue(index, newValue); - index++; - } - - return true; -} - -static bool CefValueToV8Value(CefRefPtr& outValue, const CefRefPtr& inValue, int depth = 0) -{ - if (depth > 16) - return false; - - switch (inValue->GetType()) { - case VTYPE_BOOL: - outValue = CefV8Value::CreateBool(inValue->GetBool()); - break; - case VTYPE_INT: - outValue = CefV8Value::CreateInt(inValue->GetInt()); - break; - case VTYPE_DOUBLE: - outValue = CefV8Value::CreateDouble(inValue->GetDouble()); - break; - case VTYPE_STRING: - outValue = CefV8Value::CreateString(inValue->GetString()); - break; - case VTYPE_LIST: { - CefRefPtr inList = inValue->GetList(); - outValue = CefV8Value::CreateArray(static_cast(inList->GetSize())); - - for (size_t i = 0; i < inList->GetSize(); i++) { - CefRefPtr entry; - if (!CefValueToV8Value(entry, inList->GetValue(i), depth + 1)) - return false; - outValue->SetValue(static_cast(i), entry); - } - break; - } - case VTYPE_DICTIONARY: { - CefRefPtr inMap = inValue->GetDictionary(); - outValue = CefV8Value::CreateObject(nullptr, nullptr); - - CefDictionaryValue::KeyList keys; - inMap->GetKeys(keys); - - for (const CefString& key : keys) { - CefRefPtr value; - if (!CefValueToV8Value(value, inMap->GetValue(key), depth + 1)) - return false; - outValue->SetValue(key, value, V8_PROPERTY_ATTRIBUTE_NONE); - } - break; - } - default: - outValue = CefV8Value::CreateUndefined(); - break; - } - - return true; -} - -static bool CefListToV8Values(CefV8ValueList& outList, const CefRefPtr& inList) -{ - outList.reserve(inList->GetSize()); - - for (size_t i = 0; i < inList->GetSize(); i++) { - CefRefPtr entry; - if (!CefValueToV8Value(entry, inList->GetValue(i))) - return false; - outList.emplace_back(entry); - } - - return true; -} - -void SourceApp::OnRegisterCustomSchemes(CefRawPtr registrar) -{ - registrar->AddCustomScheme("asset", CEF_SCHEME_OPTION_STANDARD | CEF_SCHEME_OPTION_CSP_BYPASSING); -} - -CefRefPtr SourceApp::GetRenderProcessHandler() -{ - return this; -} - -void SourceApp::OnBrowserCreated(CefRefPtr browser, CefRefPtr extra_info) -{ - FunctionList& functions = m_Functions[browser->GetIdentifier()]; - - if (extra_info && extra_info->GetType("functions") == VTYPE_LIST) { - CefRefPtr list = extra_info->GetList("functions"); - for (size_t i = 0; i < list->GetSize(); i++) { - if (list->GetType(i) != VTYPE_LIST) - continue; - - CefRefPtr pair = list->GetList(i); - if (pair->GetSize() == 2 && pair->GetType(0) == VTYPE_STRING && pair->GetType(1) == VTYPE_STRING) - functions.emplace_back(pair->GetString(0), pair->GetString(1)); - } - } - - RequestFunctions(browser); -} - -void SourceApp::OnBrowserDestroyed(CefRefPtr browser) -{ - int browserId = browser->GetIdentifier(); - m_Functions.erase(browserId); - m_Synced.erase(browserId); - - for (auto it = m_Callbacks.begin(); it != m_Callbacks.end();) { - if (it->second.BrowserId == browserId) - it = m_Callbacks.erase(it); - else - ++it; - } -} - -void SourceApp::RequestFunctions(CefRefPtr browser) -{ - int browserId = browser->GetIdentifier(); - if (m_Synced[browserId]) - return; - - CefRefPtr mainFrame = browser->GetMainFrame(); - if (!mainFrame) - return; - - mainFrame->SendProcessMessage(PID_BROWSER, CefProcessMessage::Create("SyncFunctions")); - m_Synced[browserId] = true; -} - -void SourceApp::OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context) -{ - context->Enter(); - { - context->GetGlobal()->DeleteValue("print"); - context->GetGlobal()->DeleteValue("openDatabase"); - } - context->Exit(); - - if (!browser) - return; - - RequestFunctions(browser); - - auto it = m_Functions.find(browser->GetIdentifier()); - if (it == m_Functions.end()) - return; - - for (const auto& pair : it->second) - RegisterFunctionInFrame(frame, pair.first, pair.second); -} - -bool SourceApp::OnProcessMessageReceived(CefRefPtr browser, CefRefPtr frame, CefProcessId source_process, CefRefPtr message) -{ - if (source_process != PID_BROWSER) - return false; - - CefString name = message->GetName(); - CefRefPtr args = message->GetArgumentList(); - - if (name == "RegisterFunction") { - RegisterFunction(browser, args); - return true; - } - - if (name == "ExecuteCallback") { - ExecuteCallback(args); - return true; - } - - if (name == "ForgetCallback") { - ForgetCallback(args); - return true; - } - - return false; -} - -bool SourceApp::Execute(const CefString& name, CefRefPtr object, const CefV8ValueList& arguments, CefRefPtr& retval, CefString& exception) -{ - CefRefPtr context = CefV8Context::GetCurrentContext(); - CefRefPtr browser = context->GetBrowser(); - CefRefPtr frame = context->GetFrame(); - - if (!browser || !frame) { - exception = "CefV8Context::GetBrowser == nullptr"; - return true; - } - - std::string fullName = name.ToString(); - size_t delimPos = fullName.find('#'); - if (delimPos == std::string::npos) { - exception = "SourceApp::Execute couldn't parse this function's name"; - return true; - } - - std::string objName = fullName.substr(0, delimPos); - std::string funcName = fullName.substr(delimPos + 1); - - CefRefPtr argsList = CefListValue::Create(); - if (!V8ValuesToCefList(argsList, arguments)) { - exception = "failed to serialize parameters (did you return a deeply nested structure?)"; - return true; - } - - CefRefPtr message = CefProcessMessage::Create("ExecuteFunction"); - CefRefPtr args = message->GetArgumentList(); - - args->SetString(0, objName); - args->SetString(1, funcName); - - if (arguments.empty() || !arguments.back()->IsFunction()) { - args->SetInt(2, -1); - } - else { - args->SetInt(2, CreateCallback(browser->GetIdentifier(), context, arguments.back())); - argsList->Remove(argsList->GetSize() - 1); - } - - args->SetList(3, argsList); - - frame->SendProcessMessage(PID_BROWSER, message); - return true; -} - -int SourceApp::CreateCallback(int browserId, CefRefPtr context, CefRefPtr func) -{ - if (m_Callbacks.find(m_NextCallbackId) != m_Callbacks.end()) - return -1; - - int callbackId = m_NextCallbackId; - m_Callbacks.emplace(callbackId, Callback{ browserId, context, func }); - - m_NextCallbackId++; - if (m_NextCallbackId >= 16384) - m_NextCallbackId = 0; - - return callbackId; -} - -void SourceApp::RegisterFunctionInFrame(CefRefPtr frame, const CefString& objName, const CefString& funcName) -{ - if (!frame) - return; - - CefRefPtr context = frame->GetV8Context(); - if (!context || !context->IsValid()) - return; - - CefString fullName(objName.ToString() + "#" + funcName.ToString()); - - context->Enter(); - { - CefRefPtr window = context->GetGlobal(); - CefRefPtr obj = window->GetValue(objName); - - if (!obj || !obj->IsObject()) { - obj = CefV8Value::CreateObject(nullptr, nullptr); - window->SetValue(objName, obj, V8_PROPERTY_ATTRIBUTE_NONE); - } - - obj->SetValue(funcName, CefV8Value::CreateFunction(fullName, this), V8_PROPERTY_ATTRIBUTE_NONE); - } - context->Exit(); -} - -void SourceApp::RegisterFunction(CefRefPtr browser, CefRefPtr args) -{ - CefString objName = args->GetString(0); - CefString funcName = args->GetString(1); - - FunctionList& functions = m_Functions[browser->GetIdentifier()]; - for (const auto& pair : functions) { - if (pair.first == objName && pair.second == funcName) - return; - } - functions.emplace_back(objName, funcName); - - std::vector frameIds; - browser->GetFrameIdentifiers(frameIds); - for (const CefString& frameId : frameIds) - RegisterFunctionInFrame(browser->GetFrameByIdentifier(frameId), objName, funcName); -} - -void SourceApp::ExecuteCallback(CefRefPtr args) -{ - auto it = m_Callbacks.find(args->GetInt(0)); - if (it == m_Callbacks.end()) - return; - - CefRefPtr context = it->second.Context; - CefRefPtr func = it->second.Function; - m_Callbacks.erase(it); - - if (!context->IsValid()) - return; - - CefRefPtr argList = args->GetList(1); - - context->Enter(); - { - CefV8ValueList arguments; - if (CefListToV8Values(arguments, argList)) - func->ExecuteFunction(nullptr, arguments); - } - context->Exit(); -} - -void SourceApp::ForgetCallback(CefRefPtr args) -{ - m_Callbacks.erase(args->GetInt(0)); -} diff --git a/Source.Launcher.Native/App.h b/Source.Launcher.Native/App.h deleted file mode 100644 index 3c78731b..00000000 --- a/Source.Launcher.Native/App.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "include/cef_app.h" - -#include -#include -#include - -class SourceApp - : public CefApp - , public CefRenderProcessHandler - , public CefV8Handler -{ -public: - void OnRegisterCustomSchemes(CefRawPtr registrar) override; - CefRefPtr GetRenderProcessHandler() override; - - void OnBrowserCreated(CefRefPtr browser, CefRefPtr extra_info) override; - void OnBrowserDestroyed(CefRefPtr browser) override; - void OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context) override; - bool OnProcessMessageReceived(CefRefPtr browser, CefRefPtr frame, CefProcessId source_process, CefRefPtr message) override; - - bool Execute(const CefString& name, CefRefPtr object, const CefV8ValueList& arguments, CefRefPtr& retval, CefString& exception) override; - -private: - using FunctionList = std::vector>; - - struct Callback - { - int BrowserId; - CefRefPtr Context; - CefRefPtr Function; - }; - - int CreateCallback(int browserId, CefRefPtr context, CefRefPtr func); - void RegisterFunctionInFrame(CefRefPtr frame, const CefString& objName, const CefString& funcName); - void RequestFunctions(CefRefPtr browser); - - void RegisterFunction(CefRefPtr browser, CefRefPtr args); - void ExecuteCallback(CefRefPtr args); - void ForgetCallback(CefRefPtr args); - - std::unordered_map m_Functions; - std::unordered_map m_Synced; - std::unordered_map m_Callbacks; - int m_NextCallbackId = 0; - - IMPLEMENT_REFCOUNTING(SourceApp); -}; diff --git a/Source.Launcher.Native/CMakeLists.txt b/Source.Launcher.Native/CMakeLists.txt deleted file mode 100644 index e14057ce..00000000 --- a/Source.Launcher.Native/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -cmake_minimum_required(VERSION 3.21) - -project(SourceLauncherNative C CXX) - -if(WIN32) - set(SN_CEF_PLATFORM windows64) -else() - set(SN_CEF_PLATFORM linux64) -endif() -set(CEF_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../Dependencies/CEF/154.0.34/${SN_CEF_PLATFORM}" CACHE PATH "CEF binary distribution root") -list(APPEND CMAKE_MODULE_PATH "${CEF_ROOT}/cmake") - -find_package(CEF REQUIRED) - -add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper) - -set(SN_SOURCES App.cpp App.h) - -if(OS_WINDOWS) - set(NETHOST_DIR "" CACHE PATH "Directory containing nethost.h, hostfxr.h and nethost.lib") - if(NOT EXISTS "${NETHOST_DIR}/nethost.h") - message(FATAL_ERROR "NETHOST_DIR must point at the .NET apphost pack native directory (got '${NETHOST_DIR}')") - endif() - - add_library(Source.Launcher SHARED ${SN_SOURCES} MainWin.cpp) - SET_LIBRARY_TARGET_PROPERTIES(Source.Launcher) - add_dependencies(Source.Launcher libcef_dll_wrapper) - - ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_RELEASE}" "${CEF_LIB_RELEASE}") - target_include_directories(Source.Launcher PRIVATE "${NETHOST_DIR}") - target_link_libraries(Source.Launcher libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS} "${NETHOST_DIR}/nethost.lib" delayimp.lib) - target_link_options(Source.Launcher PRIVATE "/DELAYLOAD:libcef.dll") -elseif(OS_LINUX) - set(CEF_LIBCEF_SO "" CACHE FILEPATH "Path to libcef.so to link against") - if(NOT EXISTS "${CEF_LIBCEF_SO}") - message(FATAL_ERROR "CEF_LIBCEF_SO must point at libcef.so (got '${CEF_LIBCEF_SO}')") - endif() - - add_executable(Source.Launcher.CEF ${SN_SOURCES} MainLinux.cpp) - SET_EXECUTABLE_TARGET_PROPERTIES(Source.Launcher.CEF) - add_dependencies(Source.Launcher.CEF libcef_dll_wrapper) - - ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIBCEF_SO}" "${CEF_LIBCEF_SO}") - # CEF_STANDARD_LIBS is just X11 on Linux, which only CEF's sample apps use. Skipping it avoids needing libx11-dev to build. - target_link_libraries(Source.Launcher.CEF libcef_lib libcef_dll_wrapper) - set_target_properties(Source.Launcher.CEF PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") -else() - message(FATAL_ERROR "Source.Launcher.Native supports Windows and Linux only") -endif() diff --git a/Source.Launcher.Native/MainLinux.cpp b/Source.Launcher.Native/MainLinux.cpp deleted file mode 100644 index 5e2cfec4..00000000 --- a/Source.Launcher.Native/MainLinux.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include -#include - -#include "include/cef_app.h" - -#include "App.h" - -int main(int argc, char* argv[]) -{ - prctl(PR_SET_PDEATHSIG, SIGKILL); - - CefMainArgs mainArgs(argc, argv); - CefRefPtr app(new SourceApp); - return CefExecuteProcess(mainArgs, app, nullptr); -} diff --git a/Source.Launcher.Native/MainWin.cpp b/Source.Launcher.Native/MainWin.cpp deleted file mode 100644 index aa425bad..00000000 --- a/Source.Launcher.Native/MainWin.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include -#include - -#include -#include -#include - -#include "include/cef_app.h" -#include "include/cef_sandbox_win.h" - -#include -#include - -#include "App.h" - -static const wchar_t* const ManagedAssembly = L"Source.LauncherMain.dll"; - -static std::wstring GetExeDirectory() -{ - std::wstring path(MAX_PATH, L'\0'); - for (;;) { - DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); - if (length == 0) - return L""; - if (length < path.size()) { - path.resize(length); - break; - } - path.resize(path.size() * 2); - } - - size_t slash = path.find_last_of(L"\\/"); - return slash == std::wstring::npos ? L"" : path.substr(0, slash + 1); -} - -static bool IsSubprocess() -{ - return wcsstr(GetCommandLineW(), L"--type=") != nullptr; -} - -static void Fail(const wchar_t* message) -{ - fwprintf(stderr, L"%s\n", message); - MessageBoxW(nullptr, message, L"Source.NET", MB_OK | MB_ICONERROR); -} - -static int RunSubprocess(void* sandboxInfo) -{ - CefMainArgs mainArgs(GetModuleHandleW(nullptr)); - CefRefPtr app(new SourceApp); - return CefExecuteProcess(mainArgs, app, sandboxInfo); -} - -static int RunManaged(void* sandboxInfo) -{ - std::wstring exeDir = GetExeDirectory(); - std::wstring assemblyPath = exeDir + ManagedAssembly; - - get_hostfxr_parameters params{ sizeof(get_hostfxr_parameters), assemblyPath.c_str(), nullptr }; - wchar_t hostfxrPath[MAX_PATH]; - size_t hostfxrPathSize = MAX_PATH; - if (get_hostfxr_path(hostfxrPath, &hostfxrPathSize, ¶ms) != 0) { - Fail(L"Could not locate the .NET runtime (hostfxr). Is the .NET 10 runtime installed?"); - return 1; - } - - HMODULE hostfxr = LoadLibraryW(hostfxrPath); - if (!hostfxr) { - Fail(L"Could not load hostfxr."); - return 1; - } - - auto initialize = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_initialize_for_dotnet_command_line")); - auto setProperty = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_set_runtime_property_value")); - auto runApp = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_run_app")); - auto close = reinterpret_cast(GetProcAddress(hostfxr, "hostfxr_close")); - if (!initialize || !setProperty || !runApp || !close) { - Fail(L"hostfxr is missing required exports."); - return 1; - } - - int argc = 0; - wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); - std::vector managedArgv; - managedArgv.push_back(assemblyPath.c_str()); - for (int i = 1; i < argc; i++) - managedArgv.push_back(argv[i]); - - hostfxr_handle handle = nullptr; - int rc = initialize(static_cast(managedArgv.size()), managedArgv.data(), nullptr, &handle); - if (rc != 0 || !handle) { - LocalFree(argv); - wchar_t message[256]; - swprintf(message, 256, L"Failed to initialize the .NET runtime for %s (0x%08X).", ManagedAssembly, static_cast(rc)); - Fail(message); - if (handle) - close(handle); - return 1; - } - - wchar_t sandboxHex[32]; - swprintf(sandboxHex, 32, L"%llX", static_cast(reinterpret_cast(sandboxInfo))); - setProperty(handle, L"SN_CEF_SANDBOX_INFO", sandboxHex); - - rc = runApp(handle); - close(handle); - LocalFree(argv); - return rc; -} - -static int Run(void* sandboxInfo) -{ - if (IsSubprocess()) - return RunSubprocess(sandboxInfo); - return RunManaged(sandboxInfo); -} - -CEF_BOOTSTRAP_EXPORT int RunWinMain(HINSTANCE hInstance, LPWSTR lpCmdLine, int nCmdShow, void* sandbox_info, cef_version_info_t* version_info) -{ - return Run(sandbox_info); -} - -CEF_BOOTSTRAP_EXPORT int RunConsoleMain(int argc, char* argv[], void* sandbox_info, cef_version_info_t* version_info) -{ - return Run(sandbox_info); -} diff --git a/Source.Launcher.Native/Source.Launcher.Native.targets b/Source.Launcher.Native/Source.Launcher.Native.targets deleted file mode 100644 index c839e1d7..00000000 --- a/Source.Launcher.Native/Source.Launcher.Native.targets +++ /dev/null @@ -1,62 +0,0 @@ - - - - 154.0.34 - $(MSBuildThisFileDirectory) - $(MSBuildProjectDirectory)\obj\native\ - $(MSBuildThisFileDirectory)..\Dependencies\CEF\$(SNCefVersion)\windows64\ - $(MSBuildThisFileDirectory)../Dependencies/CEF/$(SNCefVersion)/linux64/ - $(NetCoreTargetingPackRoot)\Microsoft.NETCore.App.Host.win-x64\$(BundledNETCoreAppPackageVersion)\runtimes\win-x64\native\ - $(NuGetPackageRoot)cef.runtime.linux-x64\$(SNCefVersion)\CEF\linux-x64\ - - - - - - - - - <_SNVsWhere>$(MSBuildProgramFiles32)\Microsoft Visual Studio\Installer\vswhere.exe - - - - - - <_SNVsCMake>$(_SNVsInstall)\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe - $(_SNVsCMake) - cmake - - - - - - - - - - - - - - - - - - - - - - - - - <_SNCefLinuxRuntime Include="$(SNCefLinuxRuntimeDir)*" /> - <_SNCefLinuxResources Include="$(SNCefLinuxRuntimeDir)Resources\**\*" /> - - - - - - - diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index 2f881eb1..23ec1476 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -10,10 +10,6 @@ true - - Source.LauncherMain - false - $(DefineConstants);DBGFLAG_ASSERT @@ -52,11 +48,14 @@ - + + - + + + diff --git a/Source.NET.slnx b/Source.NET.slnx index 3b030d3e..710e0558 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -116,6 +116,9 @@ + + +