mirror of
https://github.com/MikuLeaks/MikuSB.git
synced 2026-06-04 14:03:57 +00:00
Compare commits
19 Commits
233419eba3
...
v2.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
933ba097f9 | ||
|
|
c10d380e11 | ||
|
|
6c5d546026 | ||
|
|
9e518edb8e | ||
|
|
79fad7df2e | ||
|
|
68a7d6cc61 | ||
|
|
548c77850e | ||
|
|
d8c356a01f | ||
|
|
26991c9706 | ||
|
|
a555dd2930 | ||
|
|
85605a786c | ||
|
|
f3d6ff3873 | ||
|
|
41df375e21 | ||
|
|
5332d5fe1a | ||
|
|
da61f1e929 | ||
|
|
d9b16fb55d | ||
|
|
e92b214161 | ||
|
|
6740b8ecf7 | ||
|
|
4ee11618be |
@@ -9,6 +9,7 @@ public class ConfigContainer
|
|||||||
public PathConfig Path { get; set; } = new();
|
public PathConfig Path { get; set; } = new();
|
||||||
public ServerOption ServerOption { get; set; } = new();
|
public ServerOption ServerOption { get; set; } = new();
|
||||||
public ProxyOptions Proxy { get; set; } = new();
|
public ProxyOptions Proxy { get; set; } = new();
|
||||||
|
public LoaderOptions Loader { get; set; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
public class HttpServerConfig
|
public class HttpServerConfig
|
||||||
@@ -86,10 +87,13 @@ public class ServerProfile
|
|||||||
public class ProxyOptions
|
public class ProxyOptions
|
||||||
{
|
{
|
||||||
public bool Enabled { get; set; } = true;
|
public bool Enabled { get; set; } = true;
|
||||||
public int Port { get; set; } = 8888;
|
public int Port { get; set; } = 18888;
|
||||||
public int ServerHttpPort { get; set; } = 21500;
|
}
|
||||||
public bool InstallRootCertificate { get; set; } = true;
|
|
||||||
public bool ManageSystemProxy { get; set; } = true;
|
public class LoaderOptions
|
||||||
public bool RestoreSystemProxyOnStop { get; set; } = true;
|
{
|
||||||
public string ProxyOverride { get; set; } = "localhost;127.*;10.*;192.168.*;<local>";
|
public string GamePath { get; set; } = "";
|
||||||
|
public string[] PatchPaths { get; set; } = [@"Patch\MikuSB-Patch.dll"];
|
||||||
|
public string[] Arguments { get; set; } = ["-FeatureLevelES31", "-channelid=seasun", "-NoSplash"];
|
||||||
|
public bool SetAllProxy { get; set; } = true;
|
||||||
}
|
}
|
||||||
|
|||||||
21
Common/Data/Excel/DormGiftExcel.cs
Normal file
21
Common/Data/Excel/DormGiftExcel.cs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
namespace MikuSB.Data.Excel;
|
||||||
|
|
||||||
|
[ResourceEntity("item/templates/dorm_gift.json")]
|
||||||
|
public class DormGiftExcel : ExcelResource
|
||||||
|
{
|
||||||
|
public uint Genre { get; set; }
|
||||||
|
public uint Detail { get; set; }
|
||||||
|
public uint Particular { get; set; }
|
||||||
|
public uint Level { get; set; }
|
||||||
|
public string I18n { get; set; } = "";
|
||||||
|
|
||||||
|
public override uint GetId()
|
||||||
|
{
|
||||||
|
return (Genre << 24) | (Detail << 16) | (Particular << 8) | Level;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Loaded()
|
||||||
|
{
|
||||||
|
GameData.DormGiftData.Add(GetId(), this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ public static class GameData
|
|||||||
public static Dictionary<uint, CallItemExcel> CallItemData { get; private set; } = [];
|
public static Dictionary<uint, CallItemExcel> CallItemData { get; private set; } = [];
|
||||||
public static Dictionary<uint, WeaponPartsExcel> WeaponPartsData { get; private set; } = [];
|
public static Dictionary<uint, WeaponPartsExcel> WeaponPartsData { get; private set; } = [];
|
||||||
public static Dictionary<uint, GuideExcel> GuideData { get; private set; } = [];
|
public static Dictionary<uint, GuideExcel> GuideData { get; private set; } = [];
|
||||||
|
public static Dictionary<uint, DormGiftExcel> DormGiftData { get; private set; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class GameResourceTemplateId
|
public static class GameResourceTemplateId
|
||||||
|
|||||||
@@ -26,11 +26,14 @@ public class AccountData : BaseDatabaseDataHelper
|
|||||||
AccountData? result = null;
|
AccountData? result = null;
|
||||||
DatabaseHelper.GetAllInstance<AccountData>()?.ForEach(account =>
|
DatabaseHelper.GetAllInstance<AccountData>()?.ForEach(account =>
|
||||||
{
|
{
|
||||||
if (account.Username == username) result = account;
|
if (string.Equals(account.Username, username, StringComparison.OrdinalIgnoreCase)) result = account;
|
||||||
});
|
});
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static AccountData? GetAccountByEmail(string email)
|
||||||
|
=> GetAccountByUserName(email);
|
||||||
|
|
||||||
public static AccountData? GetAccountByUid(int uid, bool force = false)
|
public static AccountData? GetAccountByUid(int uid, bool force = false)
|
||||||
{
|
{
|
||||||
var result = DatabaseHelper.GetInstance<AccountData>(uid, force);
|
var result = DatabaseHelper.GetInstance<AccountData>(uid, force);
|
||||||
@@ -61,8 +64,15 @@ public class AccountData : BaseDatabaseDataHelper
|
|||||||
|
|
||||||
#region Account
|
#region Account
|
||||||
|
|
||||||
public static void CreateAccount(string username, int uid, string password)
|
public static AccountData CreateAccount(string username, int uid, string password)
|
||||||
{
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(username))
|
||||||
|
throw new ArgumentException("Username cannot be empty.", nameof(username));
|
||||||
|
if (GetAccountByUserName(username) != null)
|
||||||
|
throw new InvalidOperationException($"Account '{username}' already exists.");
|
||||||
|
if (uid != 0 && GetAccountByUid(uid) != null)
|
||||||
|
throw new InvalidOperationException($"UID '{uid}' is already in use.");
|
||||||
|
|
||||||
var newUid = uid;
|
var newUid = uid;
|
||||||
if (uid == 0)
|
if (uid == 0)
|
||||||
{
|
{
|
||||||
@@ -84,6 +94,7 @@ public class AccountData : BaseDatabaseDataHelper
|
|||||||
SetPassword(account, password);
|
SetPassword(account, password);
|
||||||
|
|
||||||
DatabaseHelper.CreateInstance(account);
|
DatabaseHelper.CreateInstance(account);
|
||||||
|
return account;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void DeleteAccount(int uid)
|
public static void DeleteAccount(int uid)
|
||||||
@@ -178,4 +189,4 @@ public class AccountData : BaseDatabaseDataHelper
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ public class ServerTextCHS
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class WordTextCHS
|
public class WordTextCHS
|
||||||
{
|
{
|
||||||
|
public string Furniture => "家具";
|
||||||
public string Skin => "皮肤";
|
public string Skin => "皮肤";
|
||||||
public string WeaponPart => "武器部件";
|
public string WeaponPart => "武器部件";
|
||||||
public string CallItem => "召唤道具";
|
public string CallItem => "召唤道具";
|
||||||
@@ -127,9 +128,11 @@ public class CommandTextCHS
|
|||||||
{
|
{
|
||||||
public NoticeTextCHS Notice { get; } = new();
|
public NoticeTextCHS Notice { get; } = new();
|
||||||
public HelpTextCHS Help { get; } = new();
|
public HelpTextCHS Help { get; } = new();
|
||||||
|
public AccountTextCHS Account { get; } = new();
|
||||||
public GirlTextCHS Girl { get; } = new();
|
public GirlTextCHS Girl { get; } = new();
|
||||||
public GiveAllTextCHS GiveAll { get; } = new();
|
public GiveAllTextCHS GiveAll { get; } = new();
|
||||||
public DebugTextCHS Debug { get; } = new();
|
public DebugTextCHS Debug { get; } = new();
|
||||||
|
public GameCommandTextCHS Game { get; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -216,6 +219,14 @@ public class HelpTextCHS
|
|||||||
public string CommandAlias => "命令别名: ";
|
public string CommandAlias => "命令别名: ";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class AccountTextCHS
|
||||||
|
{
|
||||||
|
public string Desc => "管理 SDK 登录使用的账号映射";
|
||||||
|
public string Usage => "用法: /account create <邮箱> <UID>";
|
||||||
|
public string Created => "已创建账号映射: {0} -> UID {1}";
|
||||||
|
public string CreateFailed => "创建账号映射失败: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// path: Game.Command.Girl
|
/// path: Game.Command.Girl
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -271,6 +282,14 @@ public class DebugTextCHS
|
|||||||
public string FileDisabled => "个人调试文件输出已禁用。";
|
public string FileDisabled => "个人调试文件输出已禁用。";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class GameCommandTextCHS
|
||||||
|
{
|
||||||
|
public string Desc => "使用补丁注入启动已配置的游戏";
|
||||||
|
public string Usage => "用法: /game [额外游戏参数]";
|
||||||
|
public string Started => "游戏已启动。PID: {0}";
|
||||||
|
public string Failed => "游戏启动失败: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ public class ServerTextCHT
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class WordTextCHT
|
public class WordTextCHT
|
||||||
{
|
{
|
||||||
|
public string Furniture => "傢俱";
|
||||||
public string Skin => "皮膚";
|
public string Skin => "皮膚";
|
||||||
public string WeaponPart => "武器部件";
|
public string WeaponPart => "武器部件";
|
||||||
public string CallItem => "召喚道具";
|
public string CallItem => "召喚道具";
|
||||||
@@ -127,9 +128,11 @@ public class CommandTextCHT
|
|||||||
{
|
{
|
||||||
public NoticeTextCHT Notice { get; } = new();
|
public NoticeTextCHT Notice { get; } = new();
|
||||||
public HelpTextCHT Help { get; } = new();
|
public HelpTextCHT Help { get; } = new();
|
||||||
|
public AccountTextCHT Account { get; } = new();
|
||||||
public GirlTextCHT Girl { get; } = new();
|
public GirlTextCHT Girl { get; } = new();
|
||||||
public GiveAllTextCHT GiveAll { get; } = new();
|
public GiveAllTextCHT GiveAll { get; } = new();
|
||||||
public DebugTextCHT Debug { get; } = new();
|
public DebugTextCHT Debug { get; } = new();
|
||||||
|
public GameCommandTextCHT Game { get; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -216,6 +219,14 @@ public class HelpTextCHT
|
|||||||
public string CommandAlias => "命令別名: ";
|
public string CommandAlias => "命令別名: ";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class AccountTextCHT
|
||||||
|
{
|
||||||
|
public string Desc => "管理 SDK 登入使用的帳號映射";
|
||||||
|
public string Usage => "用法: /account create <郵箱> <UID>";
|
||||||
|
public string Created => "已建立帳號映射: {0} -> UID {1}";
|
||||||
|
public string CreateFailed => "建立帳號映射失敗: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// path: Game.Command.Girl
|
/// path: Game.Command.Girl
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -271,6 +282,14 @@ public class DebugTextCHT
|
|||||||
public string FileDisabled => "個人調試檔案輸出已停用。";
|
public string FileDisabled => "個人調試檔案輸出已停用。";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class GameCommandTextCHT
|
||||||
|
{
|
||||||
|
public string Desc => "使用補丁注入啟動已配置的遊戲";
|
||||||
|
public string Usage => "用法: /game [額外遊戲參數]";
|
||||||
|
public string Started => "遊戲已啟動。PID: {0}";
|
||||||
|
public string Failed => "遊戲啟動失敗: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ public class ServerTextEN
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class WordTextEN
|
public class WordTextEN
|
||||||
{
|
{
|
||||||
|
public string Furniture => "Furniture";
|
||||||
public string Skin => "Skin";
|
public string Skin => "Skin";
|
||||||
public string WeaponPart => "Weapon Part";
|
public string WeaponPart => "Weapon Part";
|
||||||
public string CallItem => "Call Item";
|
public string CallItem => "Call Item";
|
||||||
@@ -86,9 +87,11 @@ public class CommandTextEN
|
|||||||
{
|
{
|
||||||
public NoticeTextEN Notice { get; } = new();
|
public NoticeTextEN Notice { get; } = new();
|
||||||
public HelpTextEN Help { get; } = new();
|
public HelpTextEN Help { get; } = new();
|
||||||
|
public AccountTextEN Account { get; } = new();
|
||||||
public GirlTextEN Girl { get; } = new();
|
public GirlTextEN Girl { get; } = new();
|
||||||
public GiveAllTextEN GiveAll { get; } = new();
|
public GiveAllTextEN GiveAll { get; } = new();
|
||||||
public DebugTextEN Debug { get; } = new();
|
public DebugTextEN Debug { get; } = new();
|
||||||
|
public GameCommandTextEN Game { get; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -182,6 +185,14 @@ public class HelpTextEN
|
|||||||
public string CommandAlias => "Command Alias:";
|
public string CommandAlias => "Command Alias:";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class AccountTextEN
|
||||||
|
{
|
||||||
|
public string Desc => "Manage account mappings for SDK logins";
|
||||||
|
public string Usage => "Usage: /account create <email> <uid>";
|
||||||
|
public string Created => "Created account mapping: {0} -> UID {1}";
|
||||||
|
public string CreateFailed => "Failed to create account mapping: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// path: Game.Command.Girl
|
/// path: Game.Command.Girl
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -237,6 +248,14 @@ public class DebugTextEN
|
|||||||
public string FileDisabled => "Personal debug file output disabled.";
|
public string FileDisabled => "Personal debug file output disabled.";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class GameCommandTextEN
|
||||||
|
{
|
||||||
|
public string Desc => "Launch the configured game with patch injection";
|
||||||
|
public string Usage => "Usage: /game [extra game args]";
|
||||||
|
public string Started => "Game launched. PID: {0}";
|
||||||
|
public string Failed => "Failed to launch game: {0}";
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
46
Common/Util/PatchDownloadService.cs
Normal file
46
Common/Util/PatchDownloadService.cs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
|
||||||
|
namespace MikuSB.Util;
|
||||||
|
|
||||||
|
public static class PatchDownloadService
|
||||||
|
{
|
||||||
|
private static readonly Logger Logger = new("PatchDownloader");
|
||||||
|
private const string PatchRelativePath = @"Patch\MikuSB-Patch.dll";
|
||||||
|
private const string PatchDownloadUrl = "https://github.com/Kei-Luna/MikuSB-Patch/releases/download/MikuSB-Patch/MikuSB-Patch.dll";
|
||||||
|
private const int DownloadTimeoutSeconds = 60;
|
||||||
|
|
||||||
|
public static void EnsurePatchPresent()
|
||||||
|
{
|
||||||
|
var patchPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, PatchRelativePath));
|
||||||
|
if (File.Exists(patchPath))
|
||||||
|
return;
|
||||||
|
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(patchPath)!);
|
||||||
|
Logger.Warn($"Patch DLL not found. Downloading to {patchPath}.");
|
||||||
|
|
||||||
|
using var client = CreateHttpClient();
|
||||||
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(DownloadTimeoutSeconds));
|
||||||
|
using var response = client.GetAsync(PatchDownloadUrl, HttpCompletionOption.ResponseHeadersRead, cts.Token)
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
using var source = response.Content.ReadAsStreamAsync(cts.Token).GetAwaiter().GetResult();
|
||||||
|
using var destination = File.Create(patchPath);
|
||||||
|
source.CopyTo(destination);
|
||||||
|
|
||||||
|
Logger.Info("Patch DLL download completed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpClient CreateHttpClient()
|
||||||
|
{
|
||||||
|
var client = new HttpClient
|
||||||
|
{
|
||||||
|
Timeout = Timeout.InfiniteTimeSpan
|
||||||
|
};
|
||||||
|
|
||||||
|
client.DefaultRequestHeaders.UserAgent.Add(
|
||||||
|
new ProductInfoHeaderValue("MikuSB-PatchDownloader", BuildVersion.Current));
|
||||||
|
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,5 +38,21 @@
|
|||||||
"DebugMessage": true,
|
"DebugMessage": true,
|
||||||
"DebugDetailMessage": true,
|
"DebugDetailMessage": true,
|
||||||
"DebugNoHandlerPacket": true
|
"DebugNoHandlerPacket": true
|
||||||
|
},
|
||||||
|
"Proxy": {
|
||||||
|
"Enabled": true,
|
||||||
|
"Port": 18888
|
||||||
|
},
|
||||||
|
"Loader": {
|
||||||
|
"GamePath": "",
|
||||||
|
"PatchPaths": [
|
||||||
|
"Patch\\MikuSB-Patch.dll"
|
||||||
|
],
|
||||||
|
"Arguments": [
|
||||||
|
"-FeatureLevelES31",
|
||||||
|
"-channelid=seasun",
|
||||||
|
"-NoSplash"
|
||||||
|
],
|
||||||
|
"SetAllProxy": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
60
GameServer/Command/Commands/CommandAccount.cs
Normal file
60
GameServer/Command/Commands/CommandAccount.cs
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
using MikuSB.Database;
|
||||||
|
using MikuSB.Database.Account;
|
||||||
|
using MikuSB.Enums.Player;
|
||||||
|
using MikuSB.Internationalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace MikuSB.GameServer.Command.Commands;
|
||||||
|
|
||||||
|
[CommandInfo("account", "Game.Command.Account.Desc", "Game.Command.Account.Usage", [], [PermEnum.Admin, PermEnum.Support])]
|
||||||
|
public class CommandAccount : ICommands
|
||||||
|
{
|
||||||
|
[CommandMethod("create")]
|
||||||
|
public async ValueTask Create(CommandArg arg)
|
||||||
|
{
|
||||||
|
if (!await arg.CheckArgCnt(2))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var email = arg.Args[0].Trim();
|
||||||
|
if (!int.TryParse(arg.Args[1], out var uid) || uid <= 0)
|
||||||
|
{
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.Notice.InvalidArguments"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var account = AccountData.CreateAccount(email, uid, "");
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.Created", account.Username, account.Uid.ToString()));
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.CreateFailed", ex.Message));
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.CreateFailed", ex.Message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[CommandMethod("list")]
|
||||||
|
public async ValueTask List(CommandArg arg)
|
||||||
|
{
|
||||||
|
var accounts = DatabaseHelper.GetAllInstance<AccountData>()?
|
||||||
|
.OrderBy(account => account.Uid)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (accounts == null || accounts.Count == 0)
|
||||||
|
{
|
||||||
|
await arg.SendMsg("No accounts found.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.AppendLine("Accounts:");
|
||||||
|
foreach (var account in accounts)
|
||||||
|
builder.AppendLine($"{account.Username} -> UID {account.Uid}");
|
||||||
|
|
||||||
|
await arg.SendMsg(builder.ToString().TrimEnd());
|
||||||
|
}
|
||||||
|
}
|
||||||
29
GameServer/Command/Commands/CommandGame.cs
Normal file
29
GameServer/Command/Commands/CommandGame.cs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
using MikuSB.Enums.Player;
|
||||||
|
using MikuSB.Internationalization;
|
||||||
|
using MikuSB.Loader;
|
||||||
|
using MikuSB.Util;
|
||||||
|
|
||||||
|
namespace MikuSB.GameServer.Command.Commands;
|
||||||
|
|
||||||
|
[CommandInfo("game", "Game.Command.Game.Desc", "Game.Command.Game.Usage", [], [PermEnum.Admin, PermEnum.Support])]
|
||||||
|
public class CommandGame : ICommands
|
||||||
|
{
|
||||||
|
private static readonly Logger Logger = new("CommandManager");
|
||||||
|
|
||||||
|
[CommandDefault]
|
||||||
|
public async ValueTask Launch(CommandArg arg)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pid = GameLaunchService.Launch(arg.Args.ToArray());
|
||||||
|
var message = I18NManager.Translate("Game.Command.Game.Started", pid.ToString());
|
||||||
|
Logger.Info(message);
|
||||||
|
await arg.SendMsg(message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logger.Error("Failed to launch game.", ex);
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.Game.Failed", ex.Message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using MikuSB.Data;
|
using MikuSB.Data;
|
||||||
|
using MikuSB.Database;
|
||||||
using MikuSB.Database.Inventory;
|
using MikuSB.Database.Inventory;
|
||||||
using MikuSB.Enums.Item;
|
using MikuSB.Enums.Item;
|
||||||
using MikuSB.Enums.Player;
|
using MikuSB.Enums.Player;
|
||||||
@@ -42,6 +43,7 @@ public class CommandGiveAll : ICommands
|
|||||||
weapons.Add(weapon);
|
weapons.Add(weapon);
|
||||||
}
|
}
|
||||||
if (weapons.Count > 0) await player.SendPacket(new PacketNtfCallScript(weapons));
|
if (weapons.Count > 0) await player.SendPacket(new PacketNtfCallScript(weapons));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.Weapon"), weapons.Count.ToString()));
|
I18NManager.Translate("Word.Weapon"), weapons.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -77,6 +79,7 @@ public class CommandGiveAll : ICommands
|
|||||||
supportCards.Add(supportCard);
|
supportCards.Add(supportCard);
|
||||||
}
|
}
|
||||||
if (supportCards.Count > 0) await player.SendPacket(new PacketNtfCallScript(supportCards));
|
if (supportCards.Count > 0) await player.SendPacket(new PacketNtfCallScript(supportCards));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.SupportCard"), supportCards.Count.ToString()));
|
I18NManager.Translate("Word.SupportCard"), supportCards.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -111,6 +114,7 @@ public class CommandGiveAll : ICommands
|
|||||||
weaponSkins.Add(weaponSkin);
|
weaponSkins.Add(weaponSkin);
|
||||||
}
|
}
|
||||||
if (weaponSkins.Count > 0) await player.SendPacket(new PacketNtfCallScript(weaponSkins));
|
if (weaponSkins.Count > 0) await player.SendPacket(new PacketNtfCallScript(weaponSkins));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.WeaponSkin"), weaponSkins.Count.ToString()));
|
I18NManager.Translate("Word.WeaponSkin"), weaponSkins.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -147,6 +151,7 @@ public class CommandGiveAll : ICommands
|
|||||||
profileItems.Add(profile);
|
profileItems.Add(profile);
|
||||||
}
|
}
|
||||||
if (profileItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(profileItems));
|
if (profileItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(profileItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.Profile"), profileItems.Count.ToString()));
|
I18NManager.Translate("Word.Profile"), profileItems.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -183,6 +188,7 @@ public class CommandGiveAll : ICommands
|
|||||||
skinPartItems.Add(skinPart);
|
skinPartItems.Add(skinPart);
|
||||||
}
|
}
|
||||||
if (skinPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinPartItems));
|
if (skinPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinPartItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.SkinPart"), skinPartItems.Count.ToString()));
|
I18NManager.Translate("Word.SkinPart"), skinPartItems.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -219,6 +225,7 @@ public class CommandGiveAll : ICommands
|
|||||||
callItems.Add(callItem);
|
callItems.Add(callItem);
|
||||||
}
|
}
|
||||||
if (callItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(callItems));
|
if (callItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(callItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.CallItem"), callItems.Count.ToString()));
|
I18NManager.Translate("Word.CallItem"), callItems.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -255,6 +262,7 @@ public class CommandGiveAll : ICommands
|
|||||||
weaponPartItems.Add(weaponPart);
|
weaponPartItems.Add(weaponPart);
|
||||||
}
|
}
|
||||||
if (weaponPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(weaponPartItems));
|
if (weaponPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(weaponPartItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.WeaponPart"), weaponPartItems.Count.ToString()));
|
I18NManager.Translate("Word.WeaponPart"), weaponPartItems.Count.ToString()));
|
||||||
}
|
}
|
||||||
@@ -291,7 +299,45 @@ public class CommandGiveAll : ICommands
|
|||||||
skinItems.Add(skin);
|
skinItems.Add(skin);
|
||||||
}
|
}
|
||||||
if (skinItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinItems));
|
if (skinItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
I18NManager.Translate("Word.Skin"), skinItems.Count.ToString()));
|
I18NManager.Translate("Word.Skin"), skinItems.Count.ToString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[CommandMethod("furniture")]
|
||||||
|
public async ValueTask GiveAllHouseFurniture(CommandArg arg)
|
||||||
|
{
|
||||||
|
if (!await arg.CheckOnlineTarget()) return;
|
||||||
|
if (await arg.GetOption('p') is not int particular) return;
|
||||||
|
if (await arg.GetOption('l') is not int level) return;
|
||||||
|
if (await arg.GetOption('g') is not int genre) return;
|
||||||
|
|
||||||
|
var detail = arg.GetInt(0);
|
||||||
|
var player = arg.Target!.Player!;
|
||||||
|
List<BaseGameItemInfo> furnitureItems = [];
|
||||||
|
if (detail == -1)
|
||||||
|
{
|
||||||
|
// add all
|
||||||
|
foreach (var config in GameData.DormGiftData.Values)
|
||||||
|
{
|
||||||
|
var furniture = await player.InventoryManager!
|
||||||
|
.AddHouseFurnitureItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||||
|
if (furniture != null) furnitureItems.Add(furniture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var furniture = await player.InventoryManager!.AddHouseFurnitureItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||||
|
if (furniture == null)
|
||||||
|
{
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.Furniture")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
furnitureItems.Add(furniture);
|
||||||
|
}
|
||||||
|
if (furnitureItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(furnitureItems));
|
||||||
|
DatabaseHelper.SaveDatabaseType(player.InventoryManager.InventoryData);
|
||||||
|
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||||
|
I18NManager.Translate("Word.Furniture"), furnitureItems.Count.ToString()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -333,4 +333,25 @@ public class InventoryManager(PlayerInstance player) : BasePlayerManager(player)
|
|||||||
|
|
||||||
return weaponPartInfo;
|
return weaponPartInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async ValueTask<BaseGameItemInfo?> AddHouseFurnitureItem(ItemTypeEnum genre, uint detail, uint particular, uint level = 1, bool sendPacket = true)
|
||||||
|
{
|
||||||
|
if (genre != ItemTypeEnum.TYPE_HOUSE) return null;
|
||||||
|
var houseFurnitureData = GameData.DormGiftData.Values.FirstOrDefault(x => x.Genre == (int)genre && x.Detail == detail && x.Particular == particular && x.Level == level);
|
||||||
|
if (houseFurnitureData == null) return null;
|
||||||
|
var templateId = GameResourceTemplateId.FromGdpl((uint)genre, detail, particular, level);
|
||||||
|
if (InventoryData.Items.Values.Any(x => x.TemplateId == templateId)) return null;
|
||||||
|
var furnitureInfo = new BaseGameItemInfo
|
||||||
|
{
|
||||||
|
TemplateId = templateId,
|
||||||
|
UniqueId = InventoryData.NextUniqueUid++,
|
||||||
|
ItemType = genre,
|
||||||
|
ItemCount = 1
|
||||||
|
};
|
||||||
|
InventoryData.Items[furnitureInfo.UniqueId] = furnitureInfo;
|
||||||
|
|
||||||
|
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([furnitureInfo]));
|
||||||
|
|
||||||
|
return furnitureInfo;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -214,6 +214,10 @@ public class PlayerInstance(PlayerGameData data)
|
|||||||
};
|
};
|
||||||
|
|
||||||
foreach (var chara in CharacterManager.CharacterData.Characters) proto.Items.Add(chara.ToProto());
|
foreach (var chara in CharacterManager.CharacterData.Characters) proto.Items.Add(chara.ToProto());
|
||||||
|
foreach (var item in InventoryManager.InventoryData.Items.Values) proto.Items.Add(item.ToProto());
|
||||||
|
foreach (var skin in InventoryManager.InventoryData.Skins.Values) proto.Items.Add(skin.ToProto());
|
||||||
|
foreach (var weapon in InventoryManager.InventoryData.Weapons.Values) proto.Items.Add(weapon.ToProto());
|
||||||
|
foreach (var card in InventoryManager.InventoryData.SupportCards.Values) proto.Items.Add(card.ToProto());
|
||||||
foreach (var x in Data.Attrs)
|
foreach (var x in Data.Attrs)
|
||||||
{
|
{
|
||||||
uint gid = x.Gid;
|
uint gid = x.Gid;
|
||||||
@@ -226,7 +230,7 @@ public class PlayerInstance(PlayerGameData data)
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
proto.Attrs[ToPackedAttrKey(gid, sid)] = val;
|
proto.Attrs[ToPackedAttrKey(gid, sid)] = val;
|
||||||
proto.Attrs[ToShiftedAttrKey(gid, sid)] = val;
|
proto.Attrs[ToShiftedAttrKey(gid, sid)] = val;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,9 +292,10 @@ public class PlayerInstance(PlayerGameData data)
|
|||||||
return (gid << 16) | sid;
|
return (gid << 16) | sid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void BuildPlayerAttr()
|
public void BuildPlayerAttr(bool additional = false)
|
||||||
{
|
{
|
||||||
var bootstrapAttrs = BuildLobbyBootstrapAttrs();
|
var bootstrapAttrs = BuildLobbyBootstrapAttrs().ToList();
|
||||||
|
if (additional) bootstrapAttrs.AddRange(BuildGirlFurnitureAttrs());
|
||||||
var existingAttrs = Data.Attrs
|
var existingAttrs = Data.Attrs
|
||||||
.ToDictionary(x => (x.Gid, x.Sid));
|
.ToDictionary(x => (x.Gid, x.Sid));
|
||||||
var seenAttrs = new HashSet<(uint Gid, uint Sid)>();
|
var seenAttrs = new HashSet<(uint Gid, uint Sid)>();
|
||||||
@@ -320,6 +325,24 @@ public class PlayerInstance(PlayerGameData data)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildGirlFurnitureAttrs()
|
||||||
|
{
|
||||||
|
// Unlock some furniture slots for every girl
|
||||||
|
// Each furniture attr int stores 10 slots using 3 bits per slot
|
||||||
|
// Value below means slot 0..9 = 1
|
||||||
|
const uint furnitureUnlockedValue = 153391689;
|
||||||
|
|
||||||
|
for (uint girlId = 0; girlId <= 50; girlId++)
|
||||||
|
{
|
||||||
|
// FurnitureStart..FurnitureEnd = 10..19
|
||||||
|
for (uint offset = 10; offset <= 19; offset++)
|
||||||
|
{
|
||||||
|
uint sid = (girlId * 50) + offset;
|
||||||
|
yield return (101, sid, furnitureUnlockedValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildLobbyBootstrapAttrs()
|
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildLobbyBootstrapAttrs()
|
||||||
{
|
{
|
||||||
// GuideLogic uses group 4. Value 999 is safely above every configured step count,
|
// GuideLogic uses group 4. Value 999 is safely above every configured step count,
|
||||||
@@ -375,7 +398,7 @@ public class PlayerInstance(PlayerGameData data)
|
|||||||
yield return (4, guide.ID, 999);
|
yield return (4, guide.ID, 999);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (uint favor = 1; favor <= 50; favor++)
|
for (uint favor = 0; favor <= 50; favor++)
|
||||||
yield return (101, favor * 50, 500);
|
yield return (101, favor * 50, 500);
|
||||||
|
|
||||||
// Main Scene 0 mean default scene
|
// Main Scene 0 mean default scene
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Common\Common.csproj" />
|
<ProjectReference Include="..\Common\Common.csproj" />
|
||||||
|
<ProjectReference Include="..\MikuSB.Loader\MikuSB.Loader.csproj" />
|
||||||
<ProjectReference Include="..\TcpSharp\TcpSharp.csproj" />
|
<ProjectReference Include="..\TcpSharp\TcpSharp.csproj" />
|
||||||
<ProjectReference Include="..\Proto\Proto.csproj" />
|
<ProjectReference Include="..\Proto\Proto.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
using MikuSB.Util.Extensions;
|
|
||||||
|
|
||||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Misc;
|
namespace MikuSB.GameServer.Server.CallGS.Handlers.Misc;
|
||||||
|
|
||||||
// Client requests server time to calculate timezone offset.
|
// Client requests server time to calculate timezone offset.
|
||||||
// nTime1/nTime2 are DST transition reference timestamps; returning the same value means no offset.
|
// In the client, ZoneTime.lua hardcodes sTime1/sTime2; if nTime1/nTime2 are false, the client ignores this update.
|
||||||
|
// Otherwise, offset = nTimeX - ParseTimeNative(sTimeX).
|
||||||
[CallGSApi("ZoneTime_ReqTime")]
|
[CallGSApi("ZoneTime_ReqTime")]
|
||||||
public class ZoneTime_ReqTime : ICallGSHandler
|
public class ZoneTime_ReqTime : ICallGSHandler
|
||||||
{
|
{
|
||||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||||
{
|
{
|
||||||
var now = Extensions.GetUnixSec();
|
var arg = $"{{\"nTime1\":false,\"nTime2\":false}}";
|
||||||
var arg = $"{{\"nTime1\":{now},\"nTime2\":{now}}}";
|
|
||||||
await CallGSRouter.SendScript(connection, "ZoneTime_ChangeTime", arg);
|
await CallGSRouter.SendScript(connection, "ZoneTime_ChangeTime", arg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ using MikuSB.GameServer.Server.Packet.Send.Misc;
|
|||||||
using MikuSB.Proto;
|
using MikuSB.Proto;
|
||||||
using MikuSB.TcpSharp;
|
using MikuSB.TcpSharp;
|
||||||
using MikuSB.Util;
|
using MikuSB.Util;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
using System.Text.Json.Nodes;
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
namespace MikuSB.GameServer.Server.Packet.Recv.Login;
|
namespace MikuSB.GameServer.Server.Packet.Recv.Login;
|
||||||
@@ -18,19 +20,45 @@ namespace MikuSB.GameServer.Server.Packet.Recv.Login;
|
|||||||
[Opcode(CmdIds.ReqLogin)]
|
[Opcode(CmdIds.ReqLogin)]
|
||||||
public class HandlerReqLogin : Handler
|
public class HandlerReqLogin : Handler
|
||||||
{
|
{
|
||||||
|
private static readonly Logger Logger = new("ReqLogin");
|
||||||
|
|
||||||
|
private static string? ExtractSdkAuthToken(string? token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var normalized = Uri.UnescapeDataString(token).Trim();
|
||||||
|
var padding = normalized.Length % 4;
|
||||||
|
if (padding > 0)
|
||||||
|
normalized = normalized.PadRight(normalized.Length + (4 - padding), '=');
|
||||||
|
|
||||||
|
var json = Encoding.UTF8.GetString(Convert.FromBase64String(normalized));
|
||||||
|
using var document = JsonDocument.Parse(json);
|
||||||
|
return document.RootElement.TryGetProperty("authToken", out var authToken)
|
||||||
|
? authToken.GetString()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public override async Task OnHandle(Connection connection, byte[] data, ushort seqNo)
|
public override async Task OnHandle(Connection connection, byte[] data, ushort seqNo)
|
||||||
{
|
{
|
||||||
var req = ReqLogin.Parser.ParseFrom(data);
|
var req = ReqLogin.Parser.ParseFrom(data);
|
||||||
var account = AccountData.GetAccountByUid(1);
|
var sdkAuthToken = ExtractSdkAuthToken(req.Token);
|
||||||
|
var account = AccountData.GetAccountByComboToken(req.Token)
|
||||||
|
?? AccountData.GetAccountByDispatchToken(req.Token)
|
||||||
|
?? AccountData.GetAccountByComboToken(sdkAuthToken ?? "")
|
||||||
|
?? AccountData.GetAccountByDispatchToken(sdkAuthToken ?? "");
|
||||||
if (account == null)
|
if (account == null)
|
||||||
{
|
{
|
||||||
AccountData.CreateAccount("MIKU", 0, "");
|
Logger.Warn($"Rejected login: provider={req.Provider}, token={req.Token}, authToken={sdkAuthToken}");
|
||||||
account = AccountData.GetAccountByUid(1);
|
await connection.SendPacket(CmdIds.NtfLogout);
|
||||||
if (account == null)
|
return;
|
||||||
{
|
|
||||||
await connection.SendPacket(CmdIds.NtfLogout);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!ResourceManager.IsLoaded)
|
if (!ResourceManager.IsLoaded)
|
||||||
// resource manager not loaded, return
|
// resource manager not loaded, return
|
||||||
@@ -53,12 +81,12 @@ public class HandlerReqLogin : Handler
|
|||||||
await connection.Player.OnEnterGame();
|
await connection.Player.OnEnterGame();
|
||||||
connection.Player.Connection = connection;
|
connection.Player.Connection = connection;
|
||||||
await connection.SendPacket(new PacketRspLogin(connection.Player!));
|
await connection.SendPacket(new PacketRspLogin(connection.Player!));
|
||||||
|
await connection.SendPacket(new PacketNtfCallScript(connection.Player!));
|
||||||
await SendDebugLoginState(connection);
|
await SendDebugLoginState(connection);
|
||||||
|
|
||||||
await connection.Player.OnHeartBeat();
|
await connection.Player.OnHeartBeat();
|
||||||
await connection.SendPacket(new PacketNtfUpdateFriend(connection.Player!));
|
await connection.SendPacket(new PacketNtfUpdateFriend(connection.Player!));
|
||||||
ApplySavedGirlSkinTypes(connection.Player!);
|
ApplySavedGirlSkinTypes(connection.Player!);
|
||||||
await connection.SendPacket(new PacketNtfCallScript(connection.Player!.InventoryManager.InventoryData));
|
|
||||||
await SendGirlSkinTypeOnLogin(connection);
|
await SendGirlSkinTypeOnLogin(connection);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ public class PacketRspLogin : BasePacket
|
|||||||
};
|
};
|
||||||
|
|
||||||
var bytes = Google.Protobuf.MessageExtensions.ToByteArray(proto);
|
var bytes = Google.Protobuf.MessageExtensions.ToByteArray(proto);
|
||||||
Logger.Info($"RspLogin proto size: {bytes.Length} bytes (limit: 65535)");
|
Logger.Info($"RspLogin proto size: {bytes.Length} bytes");
|
||||||
|
|
||||||
SetData(bytes);
|
SetData(bytes);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ public class PacketNtfCallScript : BasePacket
|
|||||||
|
|
||||||
public PacketNtfCallScript(PlayerInstance Player) : base(CmdIds.NtfScript)
|
public PacketNtfCallScript(PlayerInstance Player) : base(CmdIds.NtfScript)
|
||||||
{
|
{
|
||||||
Player.BuildPlayerAttr();
|
Player.BuildPlayerAttr(true);
|
||||||
var proto = new NtfCallScript
|
var proto = new NtfCallScript
|
||||||
{
|
{
|
||||||
Api = "",
|
Api = "",
|
||||||
|
|||||||
358
MikuSB.Loader/GameLaunchService.cs
Normal file
358
MikuSB.Loader/GameLaunchService.cs
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using MikuSB.Util;
|
||||||
|
|
||||||
|
namespace MikuSB.Loader;
|
||||||
|
|
||||||
|
public static class GameLaunchService
|
||||||
|
{
|
||||||
|
public static int Launch(params string[] extraGameArguments)
|
||||||
|
{
|
||||||
|
ConfigManager.LoadConfig();
|
||||||
|
PatchDownloadService.EnsurePatchPresent();
|
||||||
|
var options = LaunchOptions.FromConfig(extraGameArguments);
|
||||||
|
return Launch(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int Launch(LaunchOptions options)
|
||||||
|
{
|
||||||
|
var startupInfo = new STARTUPINFOW
|
||||||
|
{
|
||||||
|
cb = Marshal.SizeOf<STARTUPINFOW>()
|
||||||
|
};
|
||||||
|
|
||||||
|
var commandLine = BuildCommandLine(options.GamePath, options.GameArguments);
|
||||||
|
var workingDirectory = options.WorkingDirectory ?? Path.GetDirectoryName(options.GamePath)
|
||||||
|
?? throw new InvalidOperationException("Unable to determine working directory.");
|
||||||
|
|
||||||
|
var environment = BuildEnvironmentBlock(options.EnvironmentVariables);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!CreateProcessW(
|
||||||
|
lpApplicationName: options.GamePath,
|
||||||
|
lpCommandLine: commandLine,
|
||||||
|
lpProcessAttributes: IntPtr.Zero,
|
||||||
|
lpThreadAttributes: IntPtr.Zero,
|
||||||
|
bInheritHandles: false,
|
||||||
|
dwCreationFlags: CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
|
||||||
|
lpEnvironment: environment,
|
||||||
|
lpCurrentDirectory: workingDirectory,
|
||||||
|
lpStartupInfo: ref startupInfo,
|
||||||
|
lpProcessInformation: out var processInfo))
|
||||||
|
{
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to create game process.");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var patchPath in options.PatchPaths)
|
||||||
|
InjectDll(processInfo.hProcess, patchPath);
|
||||||
|
|
||||||
|
if (ResumeThread(processInfo.hThread) == uint.MaxValue)
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to resume game process.");
|
||||||
|
|
||||||
|
return processInfo.dwProcessId;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CloseHandle(processInfo.hThread);
|
||||||
|
CloseHandle(processInfo.hProcess);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (environment != IntPtr.Zero)
|
||||||
|
Marshal.FreeHGlobal(environment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void InjectDll(IntPtr processHandle, string dllPath)
|
||||||
|
{
|
||||||
|
var dllBytes = Encoding.Unicode.GetBytes(dllPath + '\0');
|
||||||
|
var remoteBuffer = VirtualAllocEx(
|
||||||
|
processHandle,
|
||||||
|
IntPtr.Zero,
|
||||||
|
(nuint)dllBytes.Length,
|
||||||
|
AllocationType.Commit | AllocationType.Reserve,
|
||||||
|
MemoryProtection.ReadWrite);
|
||||||
|
|
||||||
|
if (remoteBuffer == IntPtr.Zero)
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "VirtualAllocEx failed.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!WriteProcessMemory(processHandle, remoteBuffer, dllBytes, dllBytes.Length, out var written) ||
|
||||||
|
written.ToInt64() != dllBytes.Length)
|
||||||
|
{
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "WriteProcessMemory failed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var kernel32 = GetModuleHandleW("kernel32.dll");
|
||||||
|
if (kernel32 == IntPtr.Zero)
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "GetModuleHandleW(kernel32.dll) failed.");
|
||||||
|
|
||||||
|
var loadLibrary = GetProcAddress(kernel32, "LoadLibraryW");
|
||||||
|
if (loadLibrary == IntPtr.Zero)
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "GetProcAddress(LoadLibraryW) failed.");
|
||||||
|
|
||||||
|
var remoteThread = CreateRemoteThread(
|
||||||
|
processHandle,
|
||||||
|
IntPtr.Zero,
|
||||||
|
0,
|
||||||
|
loadLibrary,
|
||||||
|
remoteBuffer,
|
||||||
|
0,
|
||||||
|
out _);
|
||||||
|
|
||||||
|
if (remoteThread == IntPtr.Zero)
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateRemoteThread failed.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var waitResult = WaitForSingleObject(remoteThread, 10_000);
|
||||||
|
if (waitResult != 0)
|
||||||
|
throw new Win32Exception($"Remote LoadLibraryW timed out or failed: {waitResult}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CloseHandle(remoteThread);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
VirtualFreeEx(processHandle, remoteBuffer, 0, FreeType.Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildCommandLine(string exePath, IReadOnlyList<string> gameArgs)
|
||||||
|
{
|
||||||
|
var parts = new List<string> { Quote(exePath) };
|
||||||
|
parts.AddRange(gameArgs.Select(Quote));
|
||||||
|
return string.Join(' ', parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IntPtr BuildEnvironmentBlock(IReadOnlyDictionary<string, string> variables)
|
||||||
|
{
|
||||||
|
if (variables.Count == 0)
|
||||||
|
return IntPtr.Zero;
|
||||||
|
|
||||||
|
var merged = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
|
||||||
|
merged[(string)entry.Key] = entry.Value?.ToString() ?? string.Empty;
|
||||||
|
|
||||||
|
foreach (var pair in variables)
|
||||||
|
merged[pair.Key] = pair.Value;
|
||||||
|
|
||||||
|
var payload = string.Join('\0', merged.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
|
||||||
|
.Select(x => $"{x.Key}={x.Value}")) + "\0\0";
|
||||||
|
|
||||||
|
return Marshal.StringToHGlobalUni(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Quote(string value)
|
||||||
|
{
|
||||||
|
if (value.Length == 0)
|
||||||
|
return "\"\"";
|
||||||
|
|
||||||
|
if (!value.Any(char.IsWhiteSpace) && !value.Contains('"'))
|
||||||
|
return value;
|
||||||
|
|
||||||
|
return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
[Flags]
|
||||||
|
private enum CreationFlags : uint
|
||||||
|
{
|
||||||
|
CREATE_SUSPENDED = 0x00000004,
|
||||||
|
CREATE_UNICODE_ENVIRONMENT = 0x00000400
|
||||||
|
}
|
||||||
|
|
||||||
|
[Flags]
|
||||||
|
private enum AllocationType : uint
|
||||||
|
{
|
||||||
|
Commit = 0x1000,
|
||||||
|
Reserve = 0x2000
|
||||||
|
}
|
||||||
|
|
||||||
|
[Flags]
|
||||||
|
private enum MemoryProtection : uint
|
||||||
|
{
|
||||||
|
ReadWrite = 0x04
|
||||||
|
}
|
||||||
|
|
||||||
|
[Flags]
|
||||||
|
private enum FreeType : uint
|
||||||
|
{
|
||||||
|
Release = 0x8000
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||||
|
private struct STARTUPINFOW
|
||||||
|
{
|
||||||
|
public int cb;
|
||||||
|
public string? lpReserved;
|
||||||
|
public string? lpDesktop;
|
||||||
|
public string? lpTitle;
|
||||||
|
public int dwX;
|
||||||
|
public int dwY;
|
||||||
|
public int dwXSize;
|
||||||
|
public int dwYSize;
|
||||||
|
public int dwXCountChars;
|
||||||
|
public int dwYCountChars;
|
||||||
|
public int dwFillAttribute;
|
||||||
|
public int dwFlags;
|
||||||
|
public short wShowWindow;
|
||||||
|
public short cbReserved2;
|
||||||
|
public IntPtr lpReserved2;
|
||||||
|
public IntPtr hStdInput;
|
||||||
|
public IntPtr hStdOutput;
|
||||||
|
public IntPtr hStdError;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct PROCESS_INFORMATION
|
||||||
|
{
|
||||||
|
public IntPtr hProcess;
|
||||||
|
public IntPtr hThread;
|
||||||
|
public int dwProcessId;
|
||||||
|
public int dwThreadId;
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||||
|
private static extern bool CreateProcessW(
|
||||||
|
string? lpApplicationName,
|
||||||
|
string lpCommandLine,
|
||||||
|
IntPtr lpProcessAttributes,
|
||||||
|
IntPtr lpThreadAttributes,
|
||||||
|
bool bInheritHandles,
|
||||||
|
CreationFlags dwCreationFlags,
|
||||||
|
IntPtr lpEnvironment,
|
||||||
|
string? lpCurrentDirectory,
|
||||||
|
ref STARTUPINFOW lpStartupInfo,
|
||||||
|
out PROCESS_INFORMATION lpProcessInformation);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern IntPtr VirtualAllocEx(
|
||||||
|
IntPtr hProcess,
|
||||||
|
IntPtr lpAddress,
|
||||||
|
nuint dwSize,
|
||||||
|
AllocationType flAllocationType,
|
||||||
|
MemoryProtection flProtect);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern bool VirtualFreeEx(
|
||||||
|
IntPtr hProcess,
|
||||||
|
IntPtr lpAddress,
|
||||||
|
nuint dwSize,
|
||||||
|
FreeType dwFreeType);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern bool WriteProcessMemory(
|
||||||
|
IntPtr hProcess,
|
||||||
|
IntPtr lpBaseAddress,
|
||||||
|
byte[] lpBuffer,
|
||||||
|
int nSize,
|
||||||
|
out IntPtr lpNumberOfBytesWritten);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||||
|
private static extern IntPtr GetModuleHandleW(string lpModuleName);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||||
|
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern IntPtr CreateRemoteThread(
|
||||||
|
IntPtr hProcess,
|
||||||
|
IntPtr lpThreadAttributes,
|
||||||
|
nuint dwStackSize,
|
||||||
|
IntPtr lpStartAddress,
|
||||||
|
IntPtr lpParameter,
|
||||||
|
uint dwCreationFlags,
|
||||||
|
out int lpThreadId);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern uint ResumeThread(IntPtr hThread);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern bool CloseHandle(IntPtr hObject);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class LaunchOptions
|
||||||
|
{
|
||||||
|
public required string GamePath { get; init; }
|
||||||
|
public required IReadOnlyList<string> PatchPaths { get; init; }
|
||||||
|
public string? WorkingDirectory { get; init; }
|
||||||
|
public required IReadOnlyList<string> GameArguments { get; init; }
|
||||||
|
public required IReadOnlyDictionary<string, string> EnvironmentVariables { get; init; }
|
||||||
|
|
||||||
|
public static LaunchOptions FromConfig(IEnumerable<string>? extraGameArguments = null)
|
||||||
|
{
|
||||||
|
var config = ConfigManager.Config;
|
||||||
|
var gamePath = ResolvePath(config.Loader.GamePath, AppContext.BaseDirectory);
|
||||||
|
var patchPaths = ResolvePatchPaths(config.Loader.PatchPaths, AppContext.BaseDirectory);
|
||||||
|
var gameArgs = new List<string>(config.Loader.Arguments ?? []);
|
||||||
|
if (extraGameArguments is not null)
|
||||||
|
gameArgs.AddRange(extraGameArguments.Where(x => !string.IsNullOrWhiteSpace(x)));
|
||||||
|
|
||||||
|
var env = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
if (config.Loader.SetAllProxy && config.Proxy.Enabled)
|
||||||
|
env["ALL_PROXY"] = $"socks5h://127.0.0.1:{config.Proxy.Port}";
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(gamePath))
|
||||||
|
throw new InvalidOperationException("Loader.GamePath is not configured.");
|
||||||
|
if (!File.Exists(gamePath))
|
||||||
|
throw new FileNotFoundException("Game executable not found.", gamePath);
|
||||||
|
if (patchPaths.Count == 0)
|
||||||
|
throw new InvalidOperationException("At least one patch path is required.");
|
||||||
|
|
||||||
|
foreach (var patchPath in patchPaths)
|
||||||
|
{
|
||||||
|
if (!File.Exists(patchPath))
|
||||||
|
throw new FileNotFoundException("Patch DLL not found.", patchPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
var workingDirectory = Path.GetDirectoryName(gamePath);
|
||||||
|
if (string.IsNullOrWhiteSpace(workingDirectory) || !Directory.Exists(workingDirectory))
|
||||||
|
throw new DirectoryNotFoundException($"Working directory not found: {workingDirectory}");
|
||||||
|
|
||||||
|
return new LaunchOptions
|
||||||
|
{
|
||||||
|
GamePath = Path.GetFullPath(gamePath),
|
||||||
|
PatchPaths = patchPaths,
|
||||||
|
WorkingDirectory = Path.GetFullPath(workingDirectory),
|
||||||
|
GameArguments = gameArgs,
|
||||||
|
EnvironmentVariables = env
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? ResolvePath(string? value, string baseDirectory)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return Path.IsPathRooted(value)
|
||||||
|
? value
|
||||||
|
: Path.GetFullPath(Path.Combine(baseDirectory, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> ResolvePatchPaths(IEnumerable<string>? values, string baseDirectory)
|
||||||
|
{
|
||||||
|
var result = new List<string>();
|
||||||
|
if (values is null)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
var resolved = ResolvePath(value, baseDirectory);
|
||||||
|
if (!string.IsNullOrWhiteSpace(resolved))
|
||||||
|
result.Add(resolved);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
16
MikuSB.Loader/MikuSB.Loader.csproj
Normal file
16
MikuSB.Loader/MikuSB.Loader.csproj
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Library</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<AssemblyName>MikuSB.Loader</AssemblyName>
|
||||||
|
<RootNamespace>MikuSB.Loader</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Common\Common.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proxy", "Proxy\Proxy.csproj
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikuSB.Updater", "MikuSB.Updater\MikuSB.Updater.csproj", "{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikuSB.Updater", "MikuSB.Updater\MikuSB.Updater.csproj", "{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikuSB.Loader", "MikuSB.Loader\MikuSB.Loader.csproj", "{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -62,6 +64,10 @@ Global
|
|||||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.Build.0 = Release|Any CPU
|
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -50,7 +50,6 @@
|
|||||||
Targets="Restore;Publish"
|
Targets="Restore;Publish"
|
||||||
RemoveProperties="PublishProfile"
|
RemoveProperties="PublishProfile"
|
||||||
Properties="Configuration=$(Configuration);RuntimeIdentifier=$(RuntimeIdentifier);SelfContained=false;PublishSingleFile=true;PublishDir=$(_UpdaterPublishDir)" />
|
Properties="Configuration=$(Configuration);RuntimeIdentifier=$(RuntimeIdentifier);SelfContained=false;PublishSingleFile=true;PublishDir=$(_UpdaterPublishDir)" />
|
||||||
|
|
||||||
<Copy
|
<Copy
|
||||||
SourceFiles="$(_UpdaterPublishDir)MikuSB.Updater.exe"
|
SourceFiles="$(_UpdaterPublishDir)MikuSB.Updater.exe"
|
||||||
DestinationFiles="$(PublishDir)MikuSB.Updater.exe"
|
DestinationFiles="$(PublishDir)MikuSB.Updater.exe"
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Net;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using System.Security.Cryptography.X509Certificates;
|
|
||||||
using MikuSB.Configuration;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace MikuSB.Proxy;
|
|
||||||
|
|
||||||
public sealed class ProxyCertificateAuthority
|
|
||||||
{
|
|
||||||
private const string Password = "MikuSB.Proxy.LocalCA";
|
|
||||||
private readonly ConcurrentDictionary<string, X509Certificate2> _serverCertificates = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
private readonly ILogger<ProxyCertificateAuthority> _logger;
|
|
||||||
private readonly ProxyOptions _options;
|
|
||||||
private readonly X509Certificate2 _rootCertificate;
|
|
||||||
|
|
||||||
public ProxyCertificateAuthority(IOptions<ProxyOptions> options, ILogger<ProxyCertificateAuthority> logger)
|
|
||||||
{
|
|
||||||
_options = options.Value;
|
|
||||||
_logger = logger;
|
|
||||||
_rootCertificate = LoadOrCreateRootCertificate();
|
|
||||||
|
|
||||||
if (_options.InstallRootCertificate)
|
|
||||||
InstallRootCertificate();
|
|
||||||
else
|
|
||||||
_logger.LogWarning(
|
|
||||||
"MikuSB proxy root certificate is not installed automatically. Import {CertificatePath} into CurrentUser Root to enable HTTPS interception.",
|
|
||||||
RootCerPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
public string RootCerPath => Path.Join(CertificateDirectory, "MikuSB.Proxy.Root.cer");
|
|
||||||
public string RootCerPemPath => Path.Join(CertificateDirectory, "MikuSB.Proxy.Root.pem");
|
|
||||||
|
|
||||||
private static string CertificateDirectory => Path.Combine(AppContext.BaseDirectory, "proxy-certs");
|
|
||||||
|
|
||||||
public X509Certificate2 GetServerCertificate(string host)
|
|
||||||
{
|
|
||||||
host = host.Trim().TrimEnd('.').ToLowerInvariant();
|
|
||||||
return _serverCertificates.GetOrAdd(host, CreateServerCertificate);
|
|
||||||
}
|
|
||||||
|
|
||||||
private X509Certificate2 LoadOrCreateRootCertificate()
|
|
||||||
{
|
|
||||||
Directory.CreateDirectory(CertificateDirectory);
|
|
||||||
var pfxPath = Path.Combine(CertificateDirectory, "MikuSB.Proxy.Root.pfx");
|
|
||||||
|
|
||||||
if (File.Exists(pfxPath))
|
|
||||||
{
|
|
||||||
var existing = X509CertificateLoader.LoadPkcs12(
|
|
||||||
File.ReadAllBytes(pfxPath),
|
|
||||||
Password,
|
|
||||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
|
||||||
|
|
||||||
if (!File.Exists(RootCerPath))
|
|
||||||
File.WriteAllBytes(RootCerPath, existing.Export(X509ContentType.Cert));
|
|
||||||
|
|
||||||
if (!File.Exists(RootCerPemPath))
|
|
||||||
{
|
|
||||||
string pemString = existing.ExportCertificatePem();
|
|
||||||
File.WriteAllText(RootCerPemPath, pemString);
|
|
||||||
}
|
|
||||||
|
|
||||||
return existing;
|
|
||||||
}
|
|
||||||
|
|
||||||
using var rsa = RSA.Create(4096);
|
|
||||||
var request = new CertificateRequest(
|
|
||||||
"CN=MikuSB Proxy Root CA",
|
|
||||||
rsa,
|
|
||||||
HashAlgorithmName.SHA256,
|
|
||||||
RSASignaturePadding.Pkcs1);
|
|
||||||
|
|
||||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
|
||||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.DigitalSignature, true));
|
|
||||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
|
|
||||||
|
|
||||||
var root = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10));
|
|
||||||
var exportable = X509CertificateLoader.LoadPkcs12(
|
|
||||||
root.Export(X509ContentType.Pfx, Password),
|
|
||||||
Password,
|
|
||||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
|
||||||
|
|
||||||
File.WriteAllBytes(pfxPath, exportable.Export(X509ContentType.Pfx, Password));
|
|
||||||
File.WriteAllBytes(RootCerPath, exportable.Export(X509ContentType.Cert));
|
|
||||||
_logger.LogInformation("Created MikuSB proxy root certificate at {CertificatePath}", RootCerPath);
|
|
||||||
|
|
||||||
File.WriteAllText(RootCerPemPath, exportable.ExportCertificatePem());
|
|
||||||
_logger.LogInformation("Created MikuSB proxy root certificate (PEM) at {CertificatePath}", RootCerPemPath);
|
|
||||||
return exportable;
|
|
||||||
}
|
|
||||||
|
|
||||||
private X509Certificate2 CreateServerCertificate(string host)
|
|
||||||
{
|
|
||||||
using var rsa = RSA.Create(2048);
|
|
||||||
var request = new CertificateRequest($"CN={host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
|
||||||
|
|
||||||
var san = new SubjectAlternativeNameBuilder();
|
|
||||||
if (IPAddress.TryParse(host, out var address))
|
|
||||||
san.AddIpAddress(address);
|
|
||||||
else
|
|
||||||
san.AddDnsName(host);
|
|
||||||
|
|
||||||
request.CertificateExtensions.Add(san.Build());
|
|
||||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
|
||||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
|
|
||||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
|
|
||||||
|
|
||||||
var serial = RandomNumberGenerator.GetBytes(16);
|
|
||||||
using var certificate = request.Create(
|
|
||||||
_rootCertificate,
|
|
||||||
DateTimeOffset.UtcNow.AddDays(-1),
|
|
||||||
DateTimeOffset.UtcNow.AddYears(2),
|
|
||||||
serial);
|
|
||||||
|
|
||||||
return X509CertificateLoader.LoadPkcs12(
|
|
||||||
certificate.CopyWithPrivateKey(rsa).Export(X509ContentType.Pfx),
|
|
||||||
null,
|
|
||||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void InstallRootCertificate()
|
|
||||||
{
|
|
||||||
using var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
|
|
||||||
store.Open(OpenFlags.ReadWrite);
|
|
||||||
var existing = store.Certificates.Find(X509FindType.FindByThumbprint, _rootCertificate.Thumbprint, false);
|
|
||||||
if (existing.Count > 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
store.Add(_rootCertificate);
|
|
||||||
_logger.LogWarning("Installed MikuSB proxy root certificate into CurrentUser Root store. Thumbprint={Thumbprint}", _rootCertificate.Thumbprint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +1,20 @@
|
|||||||
using System.Buffers;
|
using System.Buffers;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Security;
|
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Security.Authentication;
|
|
||||||
using System.Text;
|
|
||||||
using MikuSB.Configuration;
|
using MikuSB.Configuration;
|
||||||
using MikuSB.Util;
|
using MikuSB.Util;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace MikuSB.Proxy;
|
namespace MikuSB.Proxy;
|
||||||
|
|
||||||
public sealed class ProxyServer(
|
public sealed class ProxyServer(
|
||||||
IOptions<ProxyOptions> options,
|
IOptions<ProxyOptions> options,
|
||||||
ProxyCertificateAuthority certificateAuthority,
|
|
||||||
HttpClient httpClient,
|
|
||||||
Logger logger) : BackgroundService
|
Logger logger) : BackgroundService
|
||||||
{
|
{
|
||||||
private const string ListenAddress = "127.0.0.1";
|
private const string ListenAddress = "127.0.0.1";
|
||||||
private const string ServerHost = "127.0.0.1";
|
private const int DefaultSocksPort = 18888;
|
||||||
|
|
||||||
private static readonly string[] TargetDomains =
|
private static readonly string[] TargetDomains =
|
||||||
[
|
[
|
||||||
"amazingseasuncdn.com",
|
"amazingseasuncdn.com",
|
||||||
@@ -29,26 +24,12 @@ public sealed class ProxyServer(
|
|||||||
"xoyo.games",
|
"xoyo.games",
|
||||||
"yo.games",
|
"yo.games",
|
||||||
"qcloud.com",
|
"qcloud.com",
|
||||||
"xgsdk.xoyo.games",
|
|
||||||
"xqdata.xoyo.games",
|
"xqdata.xoyo.games",
|
||||||
"tencentcs.com"
|
"tencentcs.com"
|
||||||
];
|
];
|
||||||
|
|
||||||
private static readonly HashSet<string> HopByHopHeaders = new(StringComparer.OrdinalIgnoreCase)
|
|
||||||
{
|
|
||||||
"Connection",
|
|
||||||
"Proxy-Connection",
|
|
||||||
"Keep-Alive",
|
|
||||||
"Proxy-Authenticate",
|
|
||||||
"Proxy-Authorization",
|
|
||||||
"TE",
|
|
||||||
"Trailer",
|
|
||||||
"Transfer-Encoding",
|
|
||||||
"Upgrade"
|
|
||||||
};
|
|
||||||
|
|
||||||
private readonly ProxyOptions _options = options.Value;
|
private readonly ProxyOptions _options = options.Value;
|
||||||
private TcpListener? _listener;
|
private readonly List<TcpListener> _listeners = [];
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
{
|
{
|
||||||
@@ -58,395 +39,257 @@ public sealed class ProxyServer(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var address = IPAddress.Parse(ListenAddress);
|
foreach (var port in GetListenPorts())
|
||||||
_listener = new TcpListener(address, _options.Port);
|
{
|
||||||
_listener.Start();
|
var listener = new TcpListener(IPAddress.Parse(ListenAddress), port);
|
||||||
logger.Info($"MikuSB proxy listening on {ListenAddress}:{_options.Port}");
|
listener.Start();
|
||||||
|
_listeners.Add(listener);
|
||||||
|
logger.Info($"MikuSB SOCKS5 proxy listening on {ListenAddress}:{port}");
|
||||||
|
_ = Task.Run(() => AcceptLoopAsync(listener, port, stoppingToken), stoppingToken);
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
while (!stoppingToken.IsCancellationRequested)
|
await Task.Delay(Timeout.Infinite, stoppingToken);
|
||||||
{
|
|
||||||
var client = await _listener.AcceptTcpClientAsync(stoppingToken);
|
|
||||||
_ = Task.Run(() => HandleClientAsync(client, stoppingToken), stoppingToken);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
catch (SocketException) when (stoppingToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
catch (ObjectDisposedException) when (stoppingToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// Cancel the BackgroundService token first so shutdown exceptions are treated as expected.
|
|
||||||
var stopTask = base.StopAsync(cancellationToken);
|
var stopTask = base.StopAsync(cancellationToken);
|
||||||
_listener?.Stop();
|
foreach (var listener in _listeners)
|
||||||
|
listener.Stop();
|
||||||
await stopTask;
|
await stopTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken)
|
private IEnumerable<int> GetListenPorts()
|
||||||
|
{
|
||||||
|
yield return DefaultSocksPort;
|
||||||
|
|
||||||
|
if (_options.Port > 0 && _options.Port != DefaultSocksPort)
|
||||||
|
yield return _options.Port;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task AcceptLoopAsync(TcpListener listener, int port, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var client = await listener.AcceptTcpClientAsync(cancellationToken);
|
||||||
|
_ = Task.Run(() => HandleClientAsync(client, port, cancellationToken), cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (SocketException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleClientAsync(TcpClient client, int listenPort, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
using (client)
|
using (client)
|
||||||
{
|
{
|
||||||
//logger.Debug($"Proxy New client: {client.Client.RemoteEndPoint}");
|
using var clientStream = client.GetStream();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await HandleClientCoreAsync(client, cancellationToken);
|
await NegotiateAsync(clientStream, cancellationToken);
|
||||||
|
var request = await ReadConnectRequestAsync(clientStream, cancellationToken);
|
||||||
|
if (request is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
using var upstream = new TcpClient();
|
||||||
|
var destination = ResolveDestination(request, listenPort);
|
||||||
|
|
||||||
|
await upstream.ConnectAsync(destination.Host, destination.Port, cancellationToken);
|
||||||
|
await SendConnectReplyAsync(clientStream, success: true, cancellationToken);
|
||||||
|
|
||||||
|
if (ConfigManager.Config.HttpServer.EnableLog)
|
||||||
|
logger.Info($"SOCKS: {request.Host}:{request.Port} -> {destination.Host}:{destination.Port}");
|
||||||
|
|
||||||
|
using var upstreamStream = upstream.GetStream();
|
||||||
|
await TunnelAsync(clientStream, upstreamStream, cancellationToken);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
catch (IOException)
|
catch (Exception ex) when (ex is IOException or SocketException)
|
||||||
{
|
{
|
||||||
}
|
if (ConfigManager.Config.HttpServer.EnableLog)
|
||||||
catch (SocketException)
|
logger.Warn($"SOCKS client failed: {ex.Message}");
|
||||||
{
|
|
||||||
}
|
|
||||||
catch (AuthenticationException ex)
|
|
||||||
{
|
|
||||||
logger.Warn($"Proxy TLS authentication failed: {ex}");
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.Warn($"Proxy client failed {ex}");
|
logger.Warn($"SOCKS client failed: {ex}");
|
||||||
}
|
|
||||||
logger.Info($"Proxy client close: {client.Client.RemoteEndPoint}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleClientCoreAsync(TcpClient client, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
await using var stream = client.GetStream();
|
|
||||||
var request = await ProxyHttpRequest.ReadAsync(stream, cancellationToken);
|
|
||||||
if (request is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (request.Method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
var (host, port) = SplitHostPort(request.Target, 443);
|
|
||||||
if (ShouldRedirect(host))
|
|
||||||
{
|
|
||||||
await WriteAsciiAsync(stream, "HTTP/1.1 200 Connection Established\r\nProxy-Agent: MikuSB.Proxy\r\n\r\n", cancellationToken);
|
|
||||||
using var tlsStream = new SslStream(stream, false);
|
|
||||||
await tlsStream.AuthenticateAsServerAsync(new SslServerAuthenticationOptions
|
|
||||||
{
|
|
||||||
ServerCertificate = certificateAuthority.GetServerCertificate(host),
|
|
||||||
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
|
|
||||||
}, cancellationToken);
|
|
||||||
|
|
||||||
await HandleRedirectedHttpLoopAsync(tlsStream, host, cancellationToken);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await TunnelAsync(stream, host, port, cancellationToken);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await HandlePlainHttpLoopAsync(stream, request, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandlePlainHttpLoopAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
var host = request.Host;
|
|
||||||
if (string.IsNullOrWhiteSpace(host))
|
|
||||||
{
|
|
||||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.BadRequest, "Missing Host header", cancellationToken);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ShouldRedirect(SplitHostPort(host, 80).Host))
|
|
||||||
await ForwardToServerAsync(clientStream, request, cancellationToken);
|
|
||||||
else
|
|
||||||
await ForwardToOriginAsync(clientStream, request, cancellationToken);
|
|
||||||
|
|
||||||
if (request.ShouldClose)
|
|
||||||
return;
|
|
||||||
|
|
||||||
var nextRequest = await ProxyHttpRequest.ReadAsync(clientStream, cancellationToken);
|
|
||||||
if (nextRequest is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
request = nextRequest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task HandleRedirectedHttpLoopAsync(Stream tlsStream, string originalHost, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
while (!cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
var request = await ProxyHttpRequest.ReadAsync(tlsStream, cancellationToken);
|
|
||||||
if (request is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
request.HostOverride = originalHost;
|
|
||||||
await ForwardToServerAsync(tlsStream, request, cancellationToken);
|
|
||||||
|
|
||||||
if (request.ShouldClose)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task ForwardToServerAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var pathAndQuery = request.GetPathAndQuery();
|
|
||||||
var uri = new Uri($"http://{ServerHost}:{_options.ServerHttpPort}{pathAndQuery}");
|
|
||||||
if (ConfigManager.Config.HttpServer.EnableLog) logger.Info($"Redirect: {request.Method} {request.HostOverride ?? request.Host}{pathAndQuery} -> {uri}");
|
|
||||||
await SendHttpRequestAsync(clientStream, request, uri, true, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task ForwardToOriginAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var uri = request.GetAbsoluteUri();
|
|
||||||
if (uri is null)
|
|
||||||
{
|
|
||||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.BadRequest, "Only absolute-form proxy requests are supported for non-target HTTP", cancellationToken);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsSelfReference(uri))
|
|
||||||
{
|
|
||||||
logger.Info($"Self-reference blocked: {request.Method} {uri}");
|
|
||||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.LoopDetected, "Proxy self-reference detected", cancellationToken);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await SendHttpRequestAsync(clientStream, request, uri, false, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsSelfReference(Uri uri)
|
|
||||||
{
|
|
||||||
if (uri.Port != _options.Port)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return uri.Host is "127.0.0.1" or "localhost" or "::1"
|
|
||||||
|| uri.Host.Equals(ListenAddress, StringComparison.OrdinalIgnoreCase);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task SendHttpRequestAsync(Stream clientStream, ProxyHttpRequest request, Uri uri, bool addCors, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
using var outgoing = new HttpRequestMessage(new HttpMethod(request.Method), uri);
|
|
||||||
if (request.Body.Length > 0)
|
|
||||||
outgoing.Content = new ByteArrayContent(request.Body);
|
|
||||||
|
|
||||||
foreach (var (name, value) in request.Headers)
|
|
||||||
{
|
|
||||||
if (HopByHopHeaders.Contains(name) || name.Equals("Host", StringComparison.OrdinalIgnoreCase))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (!outgoing.Headers.TryAddWithoutValidation(name, value))
|
|
||||||
{
|
|
||||||
outgoing.Content ??= new ByteArrayContent(request.Body);
|
|
||||||
outgoing.Content.Headers.TryAddWithoutValidation(name, value);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
using var response = await httpClient.SendAsync(outgoing, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
private async Task NegotiateAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||||
var body = await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
{
|
||||||
|
var header = new byte[2];
|
||||||
|
await ReadExactAsync(stream, header, cancellationToken);
|
||||||
|
|
||||||
var builder = new StringBuilder();
|
if (header[0] != 0x05)
|
||||||
builder.Append("HTTP/1.1 ")
|
throw new IOException("Unsupported SOCKS version");
|
||||||
.Append((int)response.StatusCode)
|
|
||||||
.Append(' ')
|
|
||||||
.Append(response.ReasonPhrase ?? response.StatusCode.ToString())
|
|
||||||
.Append("\r\n");
|
|
||||||
|
|
||||||
foreach (var header in response.Headers)
|
var methods = new byte[header[1]];
|
||||||
AppendHeader(builder, header.Key, header.Value);
|
if (methods.Length > 0)
|
||||||
|
await ReadExactAsync(stream, methods, cancellationToken);
|
||||||
|
|
||||||
foreach (var header in response.Content.Headers)
|
await stream.WriteAsync(new byte[] { 0x05, 0x00 }, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<SocksRequest?> ReadConnectRequestAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var header = new byte[4];
|
||||||
|
await ReadExactAsync(stream, header, cancellationToken);
|
||||||
|
|
||||||
|
if (header[0] != 0x05)
|
||||||
|
throw new IOException("Invalid SOCKS request");
|
||||||
|
|
||||||
|
if (header[1] != 0x01)
|
||||||
{
|
{
|
||||||
if (!header.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
|
await SendConnectReplyAsync(stream, success: false, cancellationToken);
|
||||||
AppendHeader(builder, header.Key, header.Value);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addCors)
|
var host = header[3] switch
|
||||||
builder.Append("Access-Control-Allow-Origin: *\r\n");
|
|
||||||
|
|
||||||
builder.Append("Content-Length: ").Append(body.Length).Append("\r\n");
|
|
||||||
builder.Append("Connection: keep-alive\r\n\r\n");
|
|
||||||
|
|
||||||
await WriteAsciiAsync(clientStream, builder.ToString(), cancellationToken);
|
|
||||||
if (body.Length > 0)
|
|
||||||
await clientStream.WriteAsync(body, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task TunnelAsync(Stream clientStream, string host, int port, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
using var upstream = new TcpClient();
|
|
||||||
await upstream.ConnectAsync(host, port, cancellationToken);
|
|
||||||
await WriteAsciiAsync(clientStream, "HTTP/1.1 200 Connection Established\r\nProxy-Agent: MikuSB.Proxy\r\n\r\n", cancellationToken);
|
|
||||||
|
|
||||||
await using var upstreamStream = upstream.GetStream();
|
|
||||||
var clientToServer = clientStream.CopyToAsync(upstreamStream, cancellationToken);
|
|
||||||
var serverToClient = upstreamStream.CopyToAsync(clientStream, cancellationToken);
|
|
||||||
await Task.WhenAny(clientToServer, serverToClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool ShouldRedirect(string host)
|
|
||||||
{
|
|
||||||
host = host.Trim().TrimEnd('.').ToLowerInvariant();
|
|
||||||
foreach (var target in TargetDomains)
|
|
||||||
{
|
{
|
||||||
var normalized = target.Trim().TrimEnd('.').ToLowerInvariant();
|
0x01 => new IPAddress(await ReadBytesAsync(stream, 4, cancellationToken)).ToString(),
|
||||||
if (host == normalized || host.EndsWith($".{normalized}", StringComparison.OrdinalIgnoreCase))
|
0x03 => await ReadDomainAsync(stream, cancellationToken),
|
||||||
|
0x04 => new IPAddress(await ReadBytesAsync(stream, 16, cancellationToken)).ToString(),
|
||||||
|
_ => throw new IOException("Unsupported address type")
|
||||||
|
};
|
||||||
|
|
||||||
|
var portBytes = await ReadBytesAsync(stream, 2, cancellationToken);
|
||||||
|
var port = (portBytes[0] << 8) | portBytes[1];
|
||||||
|
return new SocksRequest(host, port);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> ReadDomainAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var length = await ReadBytesAsync(stream, 1, cancellationToken);
|
||||||
|
var domain = await ReadBytesAsync(stream, length[0], cancellationToken);
|
||||||
|
return System.Text.Encoding.ASCII.GetString(domain);
|
||||||
|
}
|
||||||
|
|
||||||
|
private (string Host, int Port) ResolveDestination(SocksRequest request, int listenPort)
|
||||||
|
{
|
||||||
|
if (IsSelfReference(request.Host, request.Port, listenPort))
|
||||||
|
throw new IOException("Proxy self-reference detected");
|
||||||
|
|
||||||
|
if (!ShouldRedirect(request.Host))
|
||||||
|
return (request.Host, request.Port);
|
||||||
|
|
||||||
|
return ("127.0.0.1", request.Port switch
|
||||||
|
{
|
||||||
|
80 => ConfigManager.Config.HttpServer.Port,
|
||||||
|
893 => 31443,
|
||||||
|
13443 => 13443,
|
||||||
|
18443 => 18443,
|
||||||
|
31443 => 31443,
|
||||||
|
_ => 13443
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ShouldRedirect(string host)
|
||||||
|
{
|
||||||
|
foreach (var domain in TargetDomains)
|
||||||
|
{
|
||||||
|
if (host.Equals(domain, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase))
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void AppendHeader(StringBuilder builder, string name, IEnumerable<string> values)
|
private bool IsSelfReference(string host, int port, int listenPort)
|
||||||
{
|
{
|
||||||
if (HopByHopHeaders.Contains(name))
|
if (port != listenPort && port != _options.Port && port != DefaultSocksPort)
|
||||||
return;
|
return false;
|
||||||
|
|
||||||
foreach (var value in values)
|
return host is "127.0.0.1" or "localhost" or "::1";
|
||||||
builder.Append(name).Append(": ").Append(value).Append("\r\n");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task WriteSimpleResponseAsync(Stream stream, HttpStatusCode statusCode, string message, CancellationToken cancellationToken)
|
private static async Task SendConnectReplyAsync(NetworkStream stream, bool success, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var body = Encoding.UTF8.GetBytes(message);
|
var reply = success
|
||||||
await WriteAsciiAsync(
|
? new byte[] { 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
|
||||||
stream,
|
: new byte[] { 0x05, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
|
||||||
$"HTTP/1.1 {(int)statusCode} {statusCode}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n",
|
await stream.WriteAsync(reply, cancellationToken);
|
||||||
cancellationToken);
|
|
||||||
await stream.WriteAsync(body, cancellationToken);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Task WriteAsciiAsync(Stream stream, string value, CancellationToken cancellationToken) =>
|
private static async Task TunnelAsync(NetworkStream clientStream, NetworkStream upstreamStream, CancellationToken cancellationToken)
|
||||||
stream.WriteAsync(Encoding.ASCII.GetBytes(value), cancellationToken).AsTask();
|
|
||||||
|
|
||||||
private static (string Host, int Port) SplitHostPort(string hostPort, int defaultPort)
|
|
||||||
{
|
{
|
||||||
if (hostPort.StartsWith('['))
|
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
var upstreamToClient = CopyAsync(upstreamStream, clientStream, linkedCts.Token);
|
||||||
|
var clientToUpstream = CopyAsync(clientStream, upstreamStream, linkedCts.Token);
|
||||||
|
|
||||||
|
await Task.WhenAny(upstreamToClient, clientToUpstream);
|
||||||
|
linkedCts.Cancel();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.WhenAll(upstreamToClient, clientToUpstream);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
{
|
{
|
||||||
var end = hostPort.IndexOf(']');
|
|
||||||
if (end > 0 && hostPort.Length > end + 2 && hostPort[end + 1] == ':' && int.TryParse(hostPort[(end + 2)..], out var ipv6Port))
|
|
||||||
return (hostPort[1..end], ipv6Port);
|
|
||||||
|
|
||||||
return (hostPort.Trim('[', ']'), defaultPort);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var colon = hostPort.LastIndexOf(':');
|
|
||||||
if (colon > 0 && int.TryParse(hostPort[(colon + 1)..], out var port))
|
|
||||||
return (hostPort[..colon], port);
|
|
||||||
|
|
||||||
return (hostPort, defaultPort);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class ProxyHttpRequest
|
private static async Task CopyAsync(Stream source, Stream destination, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
public required string Method { get; init; }
|
var buffer = ArrayPool<byte>.Shared.Rent(16 * 1024);
|
||||||
public required string Target { get; init; }
|
try
|
||||||
public required string Version { get; init; }
|
|
||||||
public required List<KeyValuePair<string, string>> Headers { get; init; }
|
|
||||||
public required byte[] Body { get; init; }
|
|
||||||
public string? HostOverride { get; set; }
|
|
||||||
|
|
||||||
public string? Host => HostOverride ?? Headers.FirstOrDefault(x => x.Key.Equals("Host", StringComparison.OrdinalIgnoreCase)).Value;
|
|
||||||
|
|
||||||
public bool ShouldClose =>
|
|
||||||
Headers.Any(x => x.Key.Equals("Connection", StringComparison.OrdinalIgnoreCase)
|
|
||||||
&& x.Value.Contains("close", StringComparison.OrdinalIgnoreCase));
|
|
||||||
|
|
||||||
public Uri? GetAbsoluteUri() => Uri.TryCreate(Target, UriKind.Absolute, out var uri) ? uri : null;
|
|
||||||
|
|
||||||
public string GetPathAndQuery()
|
|
||||||
{
|
{
|
||||||
// "/query?version=a.b.c&platform=PC"
|
while (true)
|
||||||
// => Uri.TryCreate() return true && uri.Scheme == "file"
|
|
||||||
// => will return "/query%3Fversion=a.b.c&platform=PC" cause 404
|
|
||||||
if (Uri.TryCreate(Target, UriKind.Absolute, out var uri) && uri.IsAbsoluteUri && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
|
|
||||||
return uri.PathAndQuery;
|
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(Target))
|
|
||||||
return "/";
|
|
||||||
|
|
||||||
return Target[0] == '/' ? Target : $"/{Target}";
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<ProxyHttpRequest?> ReadAsync(Stream stream, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var rented = ArrayPool<byte>.Shared.Rent(64 * 1024);
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
var length = 0;
|
var bytesRead = await source.ReadAsync(buffer, cancellationToken);
|
||||||
while (true)
|
if (bytesRead <= 0)
|
||||||
{
|
break;
|
||||||
var read = await stream.ReadAsync(rented.AsMemory(length, 1), cancellationToken);
|
|
||||||
if (read == 0)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
length += read;
|
await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
|
||||||
if (length >= 4
|
await destination.FlushAsync(cancellationToken);
|
||||||
&& rented[length - 4] == '\r'
|
|
||||||
&& rented[length - 3] == '\n'
|
|
||||||
&& rented[length - 2] == '\r'
|
|
||||||
&& rented[length - 1] == '\n')
|
|
||||||
break;
|
|
||||||
|
|
||||||
if (length == rented.Length)
|
|
||||||
throw new InvalidDataException("HTTP proxy request header is too large");
|
|
||||||
}
|
|
||||||
|
|
||||||
var headerText = Encoding.ASCII.GetString(rented, 0, length);
|
|
||||||
var lines = headerText.Split("\r\n", StringSplitOptions.None);
|
|
||||||
var requestLine = lines[0].Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
if (requestLine.Length != 3)
|
|
||||||
throw new InvalidDataException("Invalid HTTP proxy request line");
|
|
||||||
|
|
||||||
var headers = new List<KeyValuePair<string, string>>();
|
|
||||||
var contentLength = 0;
|
|
||||||
for (var i = 1; i < lines.Length; i++)
|
|
||||||
{
|
|
||||||
var line = lines[i];
|
|
||||||
if (string.IsNullOrEmpty(line))
|
|
||||||
break;
|
|
||||||
|
|
||||||
var colon = line.IndexOf(':');
|
|
||||||
if (colon <= 0)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
var name = line[..colon].Trim();
|
|
||||||
var value = line[(colon + 1)..].Trim();
|
|
||||||
headers.Add(new KeyValuePair<string, string>(name, value));
|
|
||||||
if (name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out var parsedLength))
|
|
||||||
contentLength = parsedLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
var body = new byte[contentLength];
|
|
||||||
var offset = 0;
|
|
||||||
while (offset < body.Length)
|
|
||||||
{
|
|
||||||
var read = await stream.ReadAsync(body.AsMemory(offset), cancellationToken);
|
|
||||||
if (read == 0)
|
|
||||||
throw new EndOfStreamException("HTTP proxy request body ended early");
|
|
||||||
|
|
||||||
offset += read;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ProxyHttpRequest
|
|
||||||
{
|
|
||||||
Method = requestLine[0],
|
|
||||||
Target = requestLine[1],
|
|
||||||
Version = requestLine[2],
|
|
||||||
Headers = headers,
|
|
||||||
Body = body
|
|
||||||
};
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
ArrayPool<byte>.Shared.Return(rented);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<byte>.Shared.Return(buffer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task<byte[]> ReadBytesAsync(Stream stream, int length, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var buffer = new byte[length];
|
||||||
|
await ReadExactAsync(stream, buffer, cancellationToken);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var offset = 0;
|
||||||
|
while (offset < buffer.Length)
|
||||||
|
{
|
||||||
|
var bytesRead = await stream.ReadAsync(buffer.AsMemory(offset), cancellationToken);
|
||||||
|
if (bytesRead <= 0)
|
||||||
|
throw new IOException("Unexpected EOF");
|
||||||
|
offset += bytesRead;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record SocksRequest(string Host, int Port);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,17 +9,8 @@ public static class ProxyServiceCollectionExtensions
|
|||||||
public static IServiceCollection AddMikuSbProxy(this IServiceCollection services, ProxyOptions options)
|
public static IServiceCollection AddMikuSbProxy(this IServiceCollection services, ProxyOptions options)
|
||||||
{
|
{
|
||||||
services.AddSingleton<IOptions<ProxyOptions>>(Microsoft.Extensions.Options.Options.Create(options));
|
services.AddSingleton<IOptions<ProxyOptions>>(Microsoft.Extensions.Options.Options.Create(options));
|
||||||
services.AddSingleton<ProxyCertificateAuthority>();
|
|
||||||
services.AddSingleton(new HttpClient(new SocketsHttpHandler
|
|
||||||
{
|
|
||||||
AllowAutoRedirect = false,
|
|
||||||
AutomaticDecompression = System.Net.DecompressionMethods.None,
|
|
||||||
UseCookies = false,
|
|
||||||
UseProxy = false
|
|
||||||
}));
|
|
||||||
services.AddSingleton<ProxyServer>();
|
services.AddSingleton<ProxyServer>();
|
||||||
services.AddHostedService(sp => sp.GetRequiredService<ProxyServer>());
|
services.AddHostedService(sp => sp.GetRequiredService<ProxyServer>());
|
||||||
services.AddHostedService<WindowsSystemProxyService>();
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
using System.Runtime.InteropServices;
|
|
||||||
using MikuSB.Configuration;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using Microsoft.Win32;
|
|
||||||
|
|
||||||
namespace MikuSB.Proxy;
|
|
||||||
|
|
||||||
public sealed class WindowsSystemProxyService(
|
|
||||||
IOptions<ProxyOptions> options,
|
|
||||||
ILogger<WindowsSystemProxyService> logger) : IHostedService, IDisposable
|
|
||||||
{
|
|
||||||
private const string InternetSettingsPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
|
|
||||||
private readonly ProxyOptions _options = options.Value;
|
|
||||||
private ConsoleCtrlHandler? _consoleCtrlHandler;
|
|
||||||
private int _proxyDisabled;
|
|
||||||
|
|
||||||
public Task StartAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (!_options.Enabled || !_options.ManageSystemProxy)
|
|
||||||
return Task.CompletedTask;
|
|
||||||
|
|
||||||
if (!OperatingSystem.IsWindows())
|
|
||||||
{
|
|
||||||
logger.LogWarning("System proxy management is only supported on Windows");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsPath, writable: true);
|
|
||||||
if (key is null)
|
|
||||||
{
|
|
||||||
logger.LogWarning("Unable to open Windows Internet Settings registry key");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxyServer = $"http=127.0.0.1:{_options.Port};https=127.0.0.1:{_options.Port}";
|
|
||||||
|
|
||||||
key.SetValue("ProxyEnable", 1, RegistryValueKind.DWord);
|
|
||||||
key.SetValue("ProxyServer", proxyServer, RegistryValueKind.String);
|
|
||||||
key.SetValue("ProxyOverride", _options.ProxyOverride, RegistryValueKind.String);
|
|
||||||
NotifyProxySettingsChanged();
|
|
||||||
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
|
|
||||||
RegisterConsoleCtrlHandler();
|
|
||||||
|
|
||||||
logger.LogWarning("Windows system proxy enabled for MikuSB: {ProxyServer}", proxyServer);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task StopAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (!_options.Enabled || !_options.ManageSystemProxy || !_options.RestoreSystemProxyOnStop)
|
|
||||||
return Task.CompletedTask;
|
|
||||||
|
|
||||||
DisableSystemProxy();
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
|
|
||||||
UnregisterConsoleCtrlHandler();
|
|
||||||
|
|
||||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
|
||||||
DisableSystemProxy();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnProcessExit(object? sender, EventArgs e)
|
|
||||||
{
|
|
||||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
|
||||||
DisableSystemProxy();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DisableSystemProxy()
|
|
||||||
{
|
|
||||||
if (!OperatingSystem.IsWindows())
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (Interlocked.Exchange(ref _proxyDisabled, 1) == 1)
|
|
||||||
return;
|
|
||||||
|
|
||||||
using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsPath, writable: true);
|
|
||||||
if (key is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
key.SetValue("ProxyEnable", 0, RegistryValueKind.DWord);
|
|
||||||
key.DeleteValue("ProxyServer", throwOnMissingValue: false);
|
|
||||||
key.DeleteValue("ProxyOverride", throwOnMissingValue: false);
|
|
||||||
NotifyProxySettingsChanged();
|
|
||||||
logger.LogWarning("Windows system proxy disabled for MikuSB shutdown");
|
|
||||||
}
|
|
||||||
|
|
||||||
private void RegisterConsoleCtrlHandler()
|
|
||||||
{
|
|
||||||
if (!OperatingSystem.IsWindows())
|
|
||||||
return;
|
|
||||||
|
|
||||||
_consoleCtrlHandler = OnConsoleCtrl;
|
|
||||||
SetConsoleCtrlHandler(_consoleCtrlHandler, add: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void UnregisterConsoleCtrlHandler()
|
|
||||||
{
|
|
||||||
if (!OperatingSystem.IsWindows() || _consoleCtrlHandler is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
SetConsoleCtrlHandler(_consoleCtrlHandler, add: false);
|
|
||||||
_consoleCtrlHandler = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool OnConsoleCtrl(int signal)
|
|
||||||
{
|
|
||||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
|
||||||
DisableSystemProxy();
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void NotifyProxySettingsChanged()
|
|
||||||
{
|
|
||||||
InternetSetOption(IntPtr.Zero, 39, IntPtr.Zero, 0);
|
|
||||||
InternetSetOption(IntPtr.Zero, 37, IntPtr.Zero, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private delegate bool ConsoleCtrlHandler(int signal);
|
|
||||||
|
|
||||||
[DllImport("kernel32.dll", SetLastError = true)]
|
|
||||||
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handler, bool add);
|
|
||||||
|
|
||||||
[DllImport("wininet.dll", SetLastError = true)]
|
|
||||||
private static extern bool InternetSetOption(IntPtr internet, int option, IntPtr buffer, int bufferLength);
|
|
||||||
}
|
|
||||||
@@ -37,12 +37,13 @@
|
|||||||
## Running
|
## Running
|
||||||
|
|
||||||
1. Restore dependencies and build.
|
1. Restore dependencies and build.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet build
|
dotnet build
|
||||||
```
|
```
|
||||||
|
2. Set `GamePath` in `Config.json` to the path of your game executable.
|
||||||
2. Enjoy.
|
3. Start the server and run the `game` command.
|
||||||
|
4. Create an account in the server console.
|
||||||
|
5. Enjoy.
|
||||||
|
|
||||||
## Feature List
|
## Feature List
|
||||||
|
|
||||||
@@ -90,4 +91,4 @@ MikuSB was developed for educational and research purposes.
|
|||||||
- This repository does not include any copyrighted game assets, binaries, or master data.
|
- This repository does not include any copyrighted game assets, binaries, or master data.
|
||||||
- Use this software at your own risk. The authors assume no responsibility for any damages or legal consequences resulting from its use.
|
- Use this software at your own risk. The authors assume no responsibility for any damages or legal consequences resulting from its use.
|
||||||
|
|
||||||
If you are a rights holder and have any concerns regarding this software, please contact `devilpromt` or `kei_luna` on Discord.
|
If you are a rights holder and have any concerns regarding this software, please contact `devilpromt` or `kei_luna` on Discord.
|
||||||
|
|||||||
@@ -37,12 +37,13 @@ English documentation is available in [README.md](README.md).
|
|||||||
## 起動方法
|
## 起動方法
|
||||||
|
|
||||||
1. 依存を復元してビルドします。
|
1. 依存を復元してビルドします。
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet build
|
dotnet build
|
||||||
```
|
```
|
||||||
|
2. Config.json の`GamePath`にあなたのゲームの実行ファイルのパスを書き込みます
|
||||||
2. 楽しんで
|
3. サーバーを起動し`game`コマンドを入力します
|
||||||
|
4. サーバーコンソールでアカウントを作成する
|
||||||
|
5. 楽しむ
|
||||||
|
|
||||||
## 機能一覧
|
## 機能一覧
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using MikuSB.Configuration;
|
using MikuSB.Configuration;
|
||||||
|
using MikuSB.Database.Account;
|
||||||
using MikuSB.SdkServer.Models;
|
using MikuSB.SdkServer.Models;
|
||||||
using MikuSB.Util;
|
using MikuSB.Util;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -107,16 +109,106 @@ public class RouteController : ControllerBase
|
|||||||
code = 0,
|
code = 0,
|
||||||
data = new
|
data = new
|
||||||
{
|
{
|
||||||
agreementUpdateTime = "1728552600000",
|
platformPrivacyAgreement = "https://www.amazingseasun.com/privacy.html?lang=zh-Hant&gamecode=200001086",
|
||||||
appDownLoadUrl = "",
|
payType = new[] { "mycard" },
|
||||||
enableReportDataToDouyin = false,
|
loginType = new[] { "mail", "google", "twitter", "guest", "steam" },
|
||||||
loginType = new[] { "channel" },
|
closeGeetest = false,
|
||||||
openActivationCode = false,
|
userAgreement = "https://www.amazingseasun.com/user.html?lang=zh-Hant&gamecode=111111680",
|
||||||
qqGroup = (string?)null,
|
privacyAgreement = "https://www.amazingseasun.com/privacy.html?lang=zh-Hant&gamecode=111111680",
|
||||||
privacyUpdateTime = "1728552600000",
|
initPrivacyUpdateTime = 0,
|
||||||
realNameAuth = false
|
platformUserAgreement = "https://www.amazingseasun.com/user.html?lang=zh-Hant&gamecode=200001086",
|
||||||
|
accountPublicKey = "",
|
||||||
|
payChannel = (string[]?)null,
|
||||||
|
registerPrivacyUrl = "https://xgsdk.xoyo.games:13443/seasun/privacy-agreement/200001086/register/privacy.html?language=zh-Hant",
|
||||||
|
loginPrivacyUrl = "https://xgsdk.xoyo.games:13443/seasun/privacy-agreement/111111680/login/privacy.html?language=zh-Hant"
|
||||||
},
|
},
|
||||||
msg = "success"
|
msg = "操作成功"
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(rsp);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AccountData? ResolveAccountByUid(string? uid)
|
||||||
|
{
|
||||||
|
if (int.TryParse(uid, out var parsedUid))
|
||||||
|
return AccountData.GetAccountByUid(parsedUid);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AccountData? ResolveAccountForSdkLogin(string? email, string? uid, string? token)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(token))
|
||||||
|
{
|
||||||
|
var accountByComboToken = AccountData.GetAccountByComboToken(token);
|
||||||
|
if (accountByComboToken != null)
|
||||||
|
return accountByComboToken;
|
||||||
|
|
||||||
|
var accountByDispatchToken = AccountData.GetAccountByDispatchToken(token);
|
||||||
|
if (accountByDispatchToken != null)
|
||||||
|
return accountByDispatchToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(email))
|
||||||
|
{
|
||||||
|
var accountByEmail = AccountData.GetAccountByEmail(email);
|
||||||
|
if (accountByEmail != null)
|
||||||
|
return accountByEmail;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResolveAccountByUid(uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string?> GetJsonBodyValue(string propertyName)
|
||||||
|
{
|
||||||
|
if (!Request.HasJsonContentType())
|
||||||
|
return null;
|
||||||
|
|
||||||
|
Request.EnableBuffering();
|
||||||
|
Request.Body.Position = 0;
|
||||||
|
|
||||||
|
using var reader = new StreamReader(Request.Body, Encoding.UTF8, leaveOpen: true);
|
||||||
|
var body = await reader.ReadToEndAsync();
|
||||||
|
Request.Body.Position = 0;
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(body))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(body);
|
||||||
|
if (document.RootElement.ValueKind != JsonValueKind.Object)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return document.RootElement.TryGetProperty(propertyName, out var value)
|
||||||
|
? value.GetString()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IActionResult BuildLoginFailedResponse(string message)
|
||||||
|
{
|
||||||
|
object rsp = new
|
||||||
|
{
|
||||||
|
code = 1001,
|
||||||
|
data = (object?)null,
|
||||||
|
msg = message
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(rsp);
|
||||||
|
}
|
||||||
|
|
||||||
|
private IActionResult BuildNotFoundResponse(string message)
|
||||||
|
{
|
||||||
|
object rsp = new
|
||||||
|
{
|
||||||
|
code = 1001,
|
||||||
|
data = (object?)null,
|
||||||
|
msg = message
|
||||||
};
|
};
|
||||||
|
|
||||||
return Ok(rsp);
|
return Ok(rsp);
|
||||||
@@ -124,40 +216,117 @@ public class RouteController : ControllerBase
|
|||||||
|
|
||||||
[HttpGet("/seasun/loginByToken")]
|
[HttpGet("/seasun/loginByToken")]
|
||||||
[HttpPost("/seasun/loginByToken")]
|
[HttpPost("/seasun/loginByToken")]
|
||||||
public IActionResult LoginByToken(
|
public async Task<IActionResult> LoginByToken(
|
||||||
[FromQuery] string? uid,
|
[FromQuery] string? uid,
|
||||||
[FromQuery] string? token,
|
[FromQuery] string? token,
|
||||||
[FromForm] string? form_uid,
|
[FromForm] string? form_uid,
|
||||||
[FromForm] string? form_token
|
[FromForm] string? form_token
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
string finalUid = uid ?? form_uid ?? "10001";
|
var finalUid = uid ?? form_uid ?? await GetJsonBodyValue("uid");
|
||||||
string finalToken = token ?? form_token ?? Guid.NewGuid().ToString("N");
|
var finalToken = token ?? form_token ?? await GetJsonBodyValue("token");
|
||||||
|
var account = ResolveAccountForSdkLogin(null, finalUid, finalToken);
|
||||||
|
if (account == null)
|
||||||
|
return BuildLoginFailedResponse("Account not found.");
|
||||||
|
|
||||||
|
var responseUid = account.Uid.ToString();
|
||||||
|
var responseToken = account.GenerateComboToken();
|
||||||
|
|
||||||
object rsp = new
|
object rsp = new
|
||||||
{
|
{
|
||||||
code = 0,
|
code = 0,
|
||||||
data = new
|
data = new
|
||||||
{
|
{
|
||||||
associatedAccounts = new[]
|
associatedAccounts = Array.Empty<string>(),
|
||||||
{
|
|
||||||
new { bindStatus = false, nickname = "", thirdPartyType = "mail" },
|
|
||||||
new { bindStatus = true, nickname = Config.GameServer.GameServerName, thirdPartyType = "google" },
|
|
||||||
new { bindStatus = false, nickname = "", thirdPartyType = "twitter" },
|
|
||||||
new { bindStatus = false, nickname = "", thirdPartyType = "guest" },
|
|
||||||
new { bindStatus = false, nickname = "", thirdPartyType = "steam" }
|
|
||||||
},
|
|
||||||
isFirstLogin = false,
|
isFirstLogin = false,
|
||||||
isNeedKoreaSciAuth = false,
|
isNeedKoreaSciAuth = false,
|
||||||
ksOpenId = $"ks_{finalUid}",
|
ksOpenId = $"ks_{responseUid}",
|
||||||
nickname = Config.GameServer.GameServerName,
|
nickname = account.Username,
|
||||||
passportId = finalUid.Length > 10 ? finalUid[^10..] : finalUid,
|
passportId = responseUid,
|
||||||
playerFillAgeUrl = "",
|
playerFillAgeUrl = "",
|
||||||
status = 0,
|
status = 0,
|
||||||
thirdPartyUid = "",
|
thirdPartyUid = "",
|
||||||
token = finalToken,
|
token = responseToken,
|
||||||
type = "google",
|
type = "guest",
|
||||||
uid = finalUid
|
uid = account.Uid
|
||||||
|
},
|
||||||
|
msg = "操作成功"
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(rsp);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("/seasun/login")]
|
||||||
|
[HttpPost("/seasun/login")]
|
||||||
|
public async Task<IActionResult> Login(
|
||||||
|
[FromQuery] string? uid,
|
||||||
|
[FromQuery] string? token,
|
||||||
|
[FromQuery] string? email,
|
||||||
|
[FromForm] string? form_uid,
|
||||||
|
[FromForm] string? form_token,
|
||||||
|
[FromForm] string? form_email
|
||||||
|
)
|
||||||
|
{
|
||||||
|
var finalEmail = email ?? form_email ?? await GetJsonBodyValue("email");
|
||||||
|
if (!string.IsNullOrWhiteSpace(finalEmail))
|
||||||
|
{
|
||||||
|
var accountByEmail = AccountData.GetAccountByEmail(finalEmail);
|
||||||
|
if (accountByEmail == null)
|
||||||
|
return BuildLoginFailedResponse("Account not found.");
|
||||||
|
|
||||||
|
var finalUidValue = accountByEmail.Uid.ToString();
|
||||||
|
var finalTokenValue = accountByEmail.GenerateComboToken();
|
||||||
|
|
||||||
|
object emailLoginRsp = new
|
||||||
|
{
|
||||||
|
code = 0,
|
||||||
|
data = new
|
||||||
|
{
|
||||||
|
associatedAccounts = Array.Empty<string>(),
|
||||||
|
isFirstLogin = false,
|
||||||
|
isNeedKoreaSciAuth = false,
|
||||||
|
ksOpenId = $"ks_{finalUidValue}",
|
||||||
|
nickname = accountByEmail.Username,
|
||||||
|
passportId = finalUidValue,
|
||||||
|
playerFillAgeUrl = "",
|
||||||
|
status = 0,
|
||||||
|
thirdPartyUid = "",
|
||||||
|
token = finalTokenValue,
|
||||||
|
type = "guest",
|
||||||
|
uid = accountByEmail.Uid
|
||||||
|
},
|
||||||
|
msg = "操作成功"
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(emailLoginRsp);
|
||||||
|
}
|
||||||
|
|
||||||
|
var finalUid = uid ?? form_uid ?? await GetJsonBodyValue("uid");
|
||||||
|
var finalToken = token ?? form_token ?? await GetJsonBodyValue("token");
|
||||||
|
var account = ResolveAccountForSdkLogin(finalEmail, finalUid, finalToken);
|
||||||
|
if (account == null)
|
||||||
|
return BuildLoginFailedResponse("Account not found.");
|
||||||
|
|
||||||
|
var responseUid = account.Uid.ToString();
|
||||||
|
var responseToken = account.GenerateComboToken();
|
||||||
|
|
||||||
|
object rsp = new
|
||||||
|
{
|
||||||
|
code = 0,
|
||||||
|
data = new
|
||||||
|
{
|
||||||
|
associatedAccounts = Array.Empty<string>(),
|
||||||
|
isFirstLogin = false,
|
||||||
|
isNeedKoreaSciAuth = false,
|
||||||
|
ksOpenId = $"ks_{responseUid}",
|
||||||
|
nickname = account.Username,
|
||||||
|
passportId = responseUid,
|
||||||
|
playerFillAgeUrl = "",
|
||||||
|
status = 0,
|
||||||
|
thirdPartyUid = "",
|
||||||
|
token = responseToken,
|
||||||
|
type = "guest",
|
||||||
|
uid = account.Uid
|
||||||
},
|
},
|
||||||
msg = "操作成功"
|
msg = "操作成功"
|
||||||
};
|
};
|
||||||
@@ -172,8 +341,11 @@ public class RouteController : ControllerBase
|
|||||||
[FromForm] string? form_uid
|
[FromForm] string? form_uid
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
string uidString = uid ?? form_uid ?? "10001";
|
var account = ResolveAccountByUid(uid ?? form_uid);
|
||||||
var finalUid = int.TryParse(uidString, out int parsedUid) ? parsedUid : 10001;
|
if (account == null)
|
||||||
|
return BuildNotFoundResponse("Account not found.");
|
||||||
|
|
||||||
|
var uidString = account.Uid.ToString();
|
||||||
|
|
||||||
object rsp = new
|
object rsp = new
|
||||||
{
|
{
|
||||||
@@ -183,9 +355,9 @@ public class RouteController : ControllerBase
|
|||||||
bindAccountTypes = new[] { "google" },
|
bindAccountTypes = new[] { "google" },
|
||||||
channelUid = uidString,
|
channelUid = uidString,
|
||||||
loginAccountType = "google",
|
loginAccountType = "google",
|
||||||
nickName = Config.GameServer.GameServerName,
|
nickName = account.Username,
|
||||||
passportId = uidString.Length > 10 ? uidString[^10..] : uidString,
|
passportId = uidString,
|
||||||
uid = $"seasun__{uid}"
|
uid = $"seasun__{uidString}"
|
||||||
},
|
},
|
||||||
msg = "操作成功"
|
msg = "操作成功"
|
||||||
};
|
};
|
||||||
@@ -252,7 +424,11 @@ public class RouteController : ControllerBase
|
|||||||
[HttpGet("/account/query-uid/{appId}")]
|
[HttpGet("/account/query-uid/{appId}")]
|
||||||
public IActionResult QueryUid(string appId, [FromQuery] string authInfo)
|
public IActionResult QueryUid(string appId, [FromQuery] string authInfo)
|
||||||
{
|
{
|
||||||
var uid = ExtractUid(authInfo) ?? "10001";
|
var account = ResolveAccountByUid(ExtractUid(authInfo));
|
||||||
|
if (account == null)
|
||||||
|
return BuildNotFoundResponse("Account not found.");
|
||||||
|
|
||||||
|
var uid = account.Uid.ToString();
|
||||||
|
|
||||||
object rsp = new
|
object rsp = new
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -23,7 +23,24 @@ public static class SdkServer
|
|||||||
webBuilder
|
webBuilder
|
||||||
.UseStartup<Startup>()
|
.UseStartup<Startup>()
|
||||||
.ConfigureLogging((_, logging) => { logging.ClearProviders(); })
|
.ConfigureLogging((_, logging) => { logging.ClearProviders(); })
|
||||||
.UseUrls(ConfigManager.Config.HttpServer.GetDisplayAddress());
|
.ConfigureKestrel(serverOptions =>
|
||||||
|
{
|
||||||
|
// Pre-warm cert before first TLS handshake
|
||||||
|
_ = Utils.CertHelper.GetOrCreate(null);
|
||||||
|
|
||||||
|
var bindAddr = System.Net.IPAddress.Parse(ConfigManager.Config.HttpServer.BindAddress);
|
||||||
|
foreach (var port in new[] { ConfigManager.Config.HttpServer.Port, 13443, 18443, 31443 })
|
||||||
|
{
|
||||||
|
serverOptions.Listen(bindAddr, port, o =>
|
||||||
|
{
|
||||||
|
o.UseHttps(https =>
|
||||||
|
{
|
||||||
|
https.ServerCertificateSelector = (_, sni) =>
|
||||||
|
Utils.CertHelper.GetOrCreate(sni);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
var host = builder.Build();
|
var host = builder.Build();
|
||||||
|
|||||||
84
SdkServer/Utils/CertHelper.cs
Normal file
84
SdkServer/Utils/CertHelper.cs
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
|
||||||
|
namespace MikuSB.SdkServer.Utils;
|
||||||
|
|
||||||
|
public static class CertHelper
|
||||||
|
{
|
||||||
|
private const string Password = "MikuSB.SdkServer.LocalTLS";
|
||||||
|
private static readonly ConcurrentDictionary<string, X509Certificate2> Certificates =
|
||||||
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private static readonly Lazy<X509Certificate2> WildcardCert =
|
||||||
|
new(() => LoadOrCreatePersisted("wildcard.xoyo.games", "*.xoyo.games"));
|
||||||
|
|
||||||
|
private static string CertificateDirectory => Path.Combine(AppContext.BaseDirectory, "sdk-certs");
|
||||||
|
|
||||||
|
public static X509Certificate2 GetOrCreate(string? serverName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(serverName) ||
|
||||||
|
serverName.EndsWith(".xoyo.games", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return WildcardCert.Value;
|
||||||
|
|
||||||
|
var normalized = serverName.Trim().TrimEnd('.').ToLowerInvariant();
|
||||||
|
return Certificates.GetOrAdd(normalized, host => LoadOrCreatePersisted(host, host));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static X509Certificate2 LoadOrCreatePersisted(string fileHost, string subjectHost)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(CertificateDirectory);
|
||||||
|
var pfxPath = Path.Combine(CertificateDirectory, $"{SanitizeFileName(fileHost)}.pfx");
|
||||||
|
if (File.Exists(pfxPath))
|
||||||
|
return LoadPkcs12(File.ReadAllBytes(pfxPath));
|
||||||
|
|
||||||
|
var certificate = CreateSelfSigned(subjectHost);
|
||||||
|
File.WriteAllBytes(pfxPath, certificate.Export(X509ContentType.Pfx, Password));
|
||||||
|
return LoadPkcs12(File.ReadAllBytes(pfxPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static X509Certificate2 LoadPkcs12(byte[] pfx)
|
||||||
|
{
|
||||||
|
return X509CertificateLoader.LoadPkcs12(
|
||||||
|
pfx,
|
||||||
|
Password,
|
||||||
|
X509KeyStorageFlags.UserKeySet |
|
||||||
|
X509KeyStorageFlags.PersistKeySet |
|
||||||
|
X509KeyStorageFlags.Exportable);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static X509Certificate2 CreateSelfSigned(string host)
|
||||||
|
{
|
||||||
|
using var rsa = RSA.Create(2048);
|
||||||
|
|
||||||
|
var req = new CertificateRequest(
|
||||||
|
new X500DistinguishedName($"CN={host}"),
|
||||||
|
rsa,
|
||||||
|
HashAlgorithmName.SHA256,
|
||||||
|
RSASignaturePadding.Pkcs1);
|
||||||
|
|
||||||
|
var san = new SubjectAlternativeNameBuilder();
|
||||||
|
san.AddDnsName(host);
|
||||||
|
req.CertificateExtensions.Add(san.Build());
|
||||||
|
|
||||||
|
req.CertificateExtensions.Add(new X509KeyUsageExtension(
|
||||||
|
X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature,
|
||||||
|
critical: false));
|
||||||
|
|
||||||
|
req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
|
||||||
|
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") },
|
||||||
|
critical: false));
|
||||||
|
|
||||||
|
var cert = req.CreateSelfSigned(
|
||||||
|
DateTimeOffset.UtcNow.AddHours(-1),
|
||||||
|
DateTimeOffset.UtcNow.AddYears(10));
|
||||||
|
|
||||||
|
var pfx = cert.Export(X509ContentType.Pfx, Password);
|
||||||
|
return LoadPkcs12(pfx);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SanitizeFileName(string host)
|
||||||
|
{
|
||||||
|
var invalidChars = Path.GetInvalidFileNameChars();
|
||||||
|
return string.Concat(host.Select(ch => invalidChars.Contains(ch) ? '_' : ch));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,34 +1,108 @@
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using MikuSB.Util;
|
using MikuSB.Util;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
namespace MikuSB.SdkServer.Utils;
|
namespace MikuSB.SdkServer.Utils;
|
||||||
|
|
||||||
public class RequestLoggingMiddleware(RequestDelegate next)
|
public class RequestLoggingMiddleware(RequestDelegate next)
|
||||||
{
|
{
|
||||||
|
private const long MaxLoggedBodyBytes = 1024 * 1024;
|
||||||
|
|
||||||
|
private static bool ShouldSkip(string path)
|
||||||
|
=> path.StartsWith("/report") || path.Contains("/log/") || path == "/alive";
|
||||||
|
|
||||||
|
private static bool ShouldLogBody(HttpRequest request)
|
||||||
|
{
|
||||||
|
if (request.ContentLength is null or 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (request.ContentLength > MaxLoggedBodyBytes)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(request.ContentType))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return request.ContentType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| request.ContentType.Contains("text", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| request.ContentType.Contains("xml", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| request.ContentType.Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SanitizeForLog(string value)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder(value.Length);
|
||||||
|
foreach (var ch in value)
|
||||||
|
{
|
||||||
|
if (ch == '\r')
|
||||||
|
{
|
||||||
|
builder.Append(@"\r");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch == '\n')
|
||||||
|
{
|
||||||
|
builder.Append(@"\n");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char.IsControl(ch))
|
||||||
|
{
|
||||||
|
builder.Append(@"\u");
|
||||||
|
builder.Append(((int)ch).ToString("x4"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> ReadBodyAsString(HttpRequest request)
|
||||||
|
{
|
||||||
|
request.EnableBuffering();
|
||||||
|
request.Body.Position = 0;
|
||||||
|
|
||||||
|
using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true);
|
||||||
|
var body = await reader.ReadToEndAsync();
|
||||||
|
|
||||||
|
request.Body.Position = 0;
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task InvokeAsync(HttpContext context, Logger logger)
|
public async Task InvokeAsync(HttpContext context, Logger logger)
|
||||||
{
|
{
|
||||||
var request = context.Request;
|
var request = context.Request;
|
||||||
var method = request.Method;
|
var method = request.Method;
|
||||||
var path = request.Path + request.QueryString;
|
var path = request.Path.ToString();
|
||||||
|
var pathWithQuery = path + request.QueryString;
|
||||||
|
|
||||||
|
if (ConfigManager.Config.HttpServer.EnableLog && !ShouldSkip(path))
|
||||||
|
{
|
||||||
|
var body = ShouldLogBody(request)
|
||||||
|
? SanitizeForLog(await ReadBodyAsString(request))
|
||||||
|
: "<omitted>";
|
||||||
|
logger.Info($"REQ {method} {pathWithQuery} body={body}");
|
||||||
|
}
|
||||||
|
|
||||||
await next(context);
|
await next(context);
|
||||||
|
|
||||||
var statusCode = context.Response.StatusCode;
|
var statusCode = context.Response.StatusCode;
|
||||||
|
|
||||||
if (path.StartsWith("/report") || path.Contains("/log/") || path == "/alive")
|
if (ShouldSkip(path))
|
||||||
return;
|
return;
|
||||||
if (!ConfigManager.Config.HttpServer.EnableLog) return;
|
if (!ConfigManager.Config.HttpServer.EnableLog) return;
|
||||||
if (statusCode == 200)
|
if (statusCode == 200)
|
||||||
{
|
{
|
||||||
logger.Info($"{method} {path} => {statusCode}");
|
logger.Info($"{method} {pathWithQuery} => {statusCode}");
|
||||||
}
|
}
|
||||||
else if (statusCode == 404)
|
else if (statusCode == 404)
|
||||||
{
|
{
|
||||||
logger.Warn($"{method} {path} => {statusCode}");
|
logger.Warn($"{method} {pathWithQuery} => {statusCode}");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.Error($"{method} {path} => {statusCode}");
|
logger.Error($"{method} {pathWithQuery} => {statusCode}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ public class BasePacket
|
|||||||
public long Timestamp { get; set; }
|
public long Timestamp { get; set; }
|
||||||
public IMessage? Message { get; set; }
|
public IMessage? Message { get; set; }
|
||||||
public PacketFraming Framing { get; set; }
|
public PacketFraming Framing { get; set; }
|
||||||
|
public int UncompressedBodySize { get; set; }
|
||||||
|
|
||||||
public BasePacket(ushort cmdId)
|
public BasePacket(ushort cmdId)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
using MikuSB.Enums.Packet;
|
using MikuSB.Enums.Packet;
|
||||||
using MikuSB.Util;
|
using MikuSB.Util;
|
||||||
using System.Buffers.Binary;
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
|
|
||||||
namespace MikuSB.TcpSharp
|
namespace MikuSB.TcpSharp
|
||||||
@@ -63,11 +64,11 @@ namespace MikuSB.TcpSharp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public byte[] Encode(ushort packetId, byte[] payload, PacketFraming framing = PacketFraming.FourByteLittleEndianLength)
|
public byte[] Encode(ushort packetId, byte[] payload, PacketFraming framing = PacketFraming.FourByteLittleEndianLength, int uncompressedSize = 0)
|
||||||
{
|
{
|
||||||
return framing switch
|
return framing switch
|
||||||
{
|
{
|
||||||
PacketFraming.TwoByteBigEndianLength => EncodeTwoByteFrame(packetId, payload),
|
PacketFraming.TwoByteBigEndianLength => EncodeTwoByteFrame(packetId, payload, uncompressedSize),
|
||||||
PacketFraming.FourByteLittleEndianLength => EncodeFourByteFrame(packetId, payload),
|
PacketFraming.FourByteLittleEndianLength => EncodeFourByteFrame(packetId, payload),
|
||||||
_ => EncodeFourByteFrame(packetId, payload)
|
_ => EncodeFourByteFrame(packetId, payload)
|
||||||
};
|
};
|
||||||
@@ -220,8 +221,20 @@ namespace MikuSB.TcpSharp
|
|||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] EncodeTwoByteFrame(ushort packetId, byte[] payload)
|
private const int CompressionThreshold = 60000;
|
||||||
|
|
||||||
|
private static byte[] ZlibCompress(byte[] data)
|
||||||
{
|
{
|
||||||
|
using var ms = new MemoryStream();
|
||||||
|
using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true))
|
||||||
|
zlib.Write(data, 0, data.Length);
|
||||||
|
return ms.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] EncodeTwoByteFrame(ushort packetId, byte[] payload, int uncompressedSize = 0)
|
||||||
|
{
|
||||||
|
if (payload.Length > CompressionThreshold)
|
||||||
|
payload = ZlibCompress(payload);
|
||||||
var wrappedPayload = WrapPayload(payload);
|
var wrappedPayload = WrapPayload(payload);
|
||||||
var buffer = new byte[HeaderSize4Byte + wrappedPayload.Length];
|
var buffer = new byte[HeaderSize4Byte + wrappedPayload.Length];
|
||||||
|
|
||||||
@@ -246,7 +259,9 @@ namespace MikuSB.TcpSharp
|
|||||||
const int wrapperHeaderSize = 35;
|
const int wrapperHeaderSize = 35;
|
||||||
var wrapped = new byte[wrapperHeaderSize + payload.Length];
|
var wrapped = new byte[wrapperHeaderSize + payload.Length];
|
||||||
BinaryPrimitives.WriteUInt16LittleEndian(wrapped.AsSpan(6, 2), (ushort)payload.Length);
|
BinaryPrimitives.WriteUInt16LittleEndian(wrapped.AsSpan(6, 2), (ushort)payload.Length);
|
||||||
wrapped[11] = 1;
|
if (payload.Length >= 2 && payload[0] == 0x78 &&
|
||||||
|
(payload[1] == 0x01 || payload[1] == 0x5E || payload[1] == 0x9C || payload[1] == 0xDA))
|
||||||
|
wrapped[10] = 2;
|
||||||
payload.CopyTo(wrapped.AsSpan(wrapperHeaderSize));
|
payload.CopyTo(wrapped.AsSpan(wrapperHeaderSize));
|
||||||
|
|
||||||
return wrapped;
|
return wrapped;
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
v=2.2
|
v=2.8
|
||||||
Reference in New Issue
Block a user