sharp-chat/SharpChat/SockChatServer.cs

240 lines
9 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using Fleck;
using SharpChat.Commands;
using SharpChat.Config;
using SharpChat.EventStorage;
using SharpChat.Misuzu;
2022-08-30 15:00:58 +00:00
using SharpChat.Packet;
2023-02-16 21:16:06 +00:00
using SharpChat.PacketHandlers;
2022-08-30 15:00:58 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
2022-08-30 15:00:58 +00:00
namespace SharpChat {
public class SockChatServer : IDisposable {
public const ushort DEFAULT_PORT = 6770;
public const int DEFAULT_MSG_LENGTH_MAX = 5000;
public const int DEFAULT_MAX_CONNECTIONS = 5;
public const int DEFAULT_FLOOD_KICK_LENGTH = 30;
public const int DEFAULT_FLOOD_KICK_EXEMPT_RANK = 9;
2022-08-30 15:00:58 +00:00
public IWebSocketServer Server { get; }
public ChatContext Context { get; }
2023-02-06 20:14:50 +00:00
private readonly HttpClient HttpClient;
private readonly MisuzuClient Misuzu;
private readonly CachedValue<int> MaxMessageLength;
private readonly CachedValue<int> MaxConnections;
private readonly CachedValue<int> FloodKickLength;
private readonly CachedValue<int> FloodKickExemptRank;
2023-02-16 21:16:06 +00:00
private readonly List<IChatPacketHandler> GuestHandlers = new();
private readonly List<IChatPacketHandler> AuthedHandlers = new();
private readonly SendMessageHandler SendMessageHandler;
2022-08-30 15:00:58 +00:00
private bool IsShuttingDown = false;
private ChatChannel DefaultChannel { get; set; }
public SockChatServer(HttpClient httpClient, MisuzuClient msz, IEventStorage evtStore, IConfig config) {
Logger.Write("Initialising Sock Chat server...");
HttpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
Misuzu = msz ?? throw new ArgumentNullException(nameof(msz));
2022-08-30 15:00:58 +00:00
MaxMessageLength = config.ReadCached("msgMaxLength", DEFAULT_MSG_LENGTH_MAX);
MaxConnections = config.ReadCached("connMaxCount", DEFAULT_MAX_CONNECTIONS);
FloodKickLength = config.ReadCached("floodKickLength", DEFAULT_FLOOD_KICK_LENGTH);
FloodKickExemptRank = config.ReadCached("floodKickExemptRank", DEFAULT_FLOOD_KICK_EXEMPT_RANK);
Context = new ChatContext(evtStore);
2022-08-30 15:00:58 +00:00
2024-05-10 19:18:55 +00:00
string[]? channelNames = config.ReadValue("channels", new[] { "lounge" });
2024-05-10 19:18:55 +00:00
if(channelNames != null)
foreach(string channelName in channelNames) {
IConfig channelCfg = config.ScopeTo($"channels:{channelName}");
2024-05-10 19:18:55 +00:00
string? name = channelCfg.SafeReadValue("name", string.Empty);
if(string.IsNullOrWhiteSpace(name))
name = channelName;
2024-05-10 19:18:55 +00:00
ChatChannel channelInfo = new(
name,
channelCfg.SafeReadValue("password", string.Empty),
rank: channelCfg.SafeReadValue("minRank", 0)
);
2022-08-30 15:00:58 +00:00
2024-05-10 19:18:55 +00:00
Context.Channels.Add(channelInfo);
DefaultChannel ??= channelInfo;
}
DefaultChannel ??= new ChatChannel("Default");
if(!Context.Channels.Any())
Context.Channels.Add(DefaultChannel);
2023-02-16 21:16:06 +00:00
GuestHandlers.Add(new AuthHandler(Misuzu, DefaultChannel, MaxMessageLength, MaxConnections));
AuthedHandlers.AddRange(new IChatPacketHandler[] {
new PingHandler(Misuzu),
SendMessageHandler = new SendMessageHandler(MaxMessageLength),
});
SendMessageHandler.AddCommands(new IChatCommand[] {
new AFKCommand(),
new NickCommand(),
new WhisperCommand(),
new ActionCommand(),
new WhoCommand(),
new JoinChannelCommand(),
new CreateChannelCommand(),
new DeleteChannelCommand(),
new PasswordChannelCommand(),
new RankChannelCommand(),
new BroadcastCommand(),
new DeleteMessageCommand(),
new KickBanCommand(msz),
new PardonUserCommand(msz),
new PardonAddressCommand(msz),
new BanListCommand(msz),
new RemoteAddressCommand(),
});
ushort port = config.SafeReadValue("port", DEFAULT_PORT);
Server = new SharpChatWebSocketServer($"ws://0.0.0.0:{port}");
2023-02-06 20:14:50 +00:00
}
public void Listen(ManualResetEvent waitHandle) {
if(waitHandle != null)
2023-02-16 21:16:06 +00:00
SendMessageHandler.AddCommand(new ShutdownRestartCommand(waitHandle, () => !IsShuttingDown && (IsShuttingDown = true)));
2022-08-30 15:00:58 +00:00
Server.Start(sock => {
2023-02-19 22:27:08 +00:00
if(IsShuttingDown) {
sock.Close(1013);
return;
}
2023-02-19 22:27:08 +00:00
ChatConnection conn = new(sock);
Context.Connections.Add(conn);
sock.OnOpen = () => OnOpen(conn);
sock.OnClose = () => OnClose(conn);
sock.OnError = err => OnError(conn, err);
sock.OnMessage = msg => OnMessage(conn, msg);
2022-08-30 15:00:58 +00:00
});
Logger.Write("Listening...");
2022-08-30 15:00:58 +00:00
}
private void OnOpen(ChatConnection conn) {
Logger.Write($"Connection opened from {conn.RemoteAddress}:{conn.RemotePort}");
2023-02-19 22:27:08 +00:00
Context.SafeUpdate();
}
2022-08-30 15:00:58 +00:00
2023-02-19 22:27:08 +00:00
private void OnError(ChatConnection conn, Exception ex) {
Logger.Write($"[{conn.Id} {conn.RemoteAddress}] {ex}");
Context.SafeUpdate();
2022-08-30 15:00:58 +00:00
}
private void OnClose(ChatConnection conn) {
Logger.Write($"Connection closed from {conn.RemoteAddress}:{conn.RemotePort}");
2023-02-19 22:27:08 +00:00
Context.ContextAccess.Wait();
try {
Context.Connections.Remove(conn);
2022-08-30 15:00:58 +00:00
if(conn.User != null && !Context.Connections.Any(c => c.User == conn.User))
Context.HandleDisconnect(conn.User);
2022-08-30 15:00:58 +00:00
2023-02-19 22:27:08 +00:00
Context.Update();
} finally {
Context.ContextAccess.Release();
}
2022-08-30 15:00:58 +00:00
}
private void OnMessage(ChatConnection conn, string msg) {
2023-02-19 22:27:08 +00:00
Context.SafeUpdate();
2022-08-30 15:00:58 +00:00
2023-02-16 21:16:06 +00:00
// this doesn't affect non-authed connections?????
if(conn.User is not null && conn.User.Rank < FloodKickExemptRank) {
2024-05-10 19:18:55 +00:00
ChatUser? banUser = null;
2023-02-19 22:27:08 +00:00
string banAddr = string.Empty;
TimeSpan banDuration = TimeSpan.MinValue;
Context.ContextAccess.Wait();
try {
2024-05-10 19:18:55 +00:00
if(!Context.UserRateLimiters.TryGetValue(conn.User.UserId, out RateLimiter? rateLimiter))
2023-02-19 22:27:08 +00:00
Context.UserRateLimiters.Add(conn.User.UserId, rateLimiter = new RateLimiter(
ChatUser.DEFAULT_SIZE,
ChatUser.DEFAULT_MINIMUM_DELAY,
ChatUser.DEFAULT_RISKY_OFFSET
));
rateLimiter.Update();
if(rateLimiter.IsExceeded) {
banDuration = TimeSpan.FromSeconds(FloodKickLength);
banUser = conn.User;
banAddr = conn.RemoteAddress.ToString();
} else if(rateLimiter.IsRisky) {
banUser = conn.User;
}
if(banUser is not null) {
if(banDuration == TimeSpan.MinValue) {
Context.SendTo(conn.User, new LegacyCommandResponse(LCR.FLOOD_WARN, false));
2023-02-19 22:27:08 +00:00
} else {
Context.BanUser(conn.User, banDuration, UserDisconnectReason.Flood);
if(banDuration > TimeSpan.Zero)
Misuzu.CreateBanAsync(
conn.User.UserId.ToString(), conn.RemoteAddress.ToString(),
string.Empty, "::1",
banDuration,
"Kicked from chat for flood protection."
).Wait();
return;
}
}
} finally {
Context.ContextAccess.Release();
}
2022-08-30 15:00:58 +00:00
}
2023-02-16 21:25:41 +00:00
ChatPacketHandlerContext context = new(msg, Context, conn);
2024-05-10 19:18:55 +00:00
IChatPacketHandler? handler = conn.User is null
2023-02-16 21:16:06 +00:00
? GuestHandlers.FirstOrDefault(h => h.IsMatch(context))
: AuthedHandlers.FirstOrDefault(h => h.IsMatch(context));
2022-08-30 15:00:58 +00:00
handler?.Handle(context);
2022-08-30 15:00:58 +00:00
}
2023-02-19 22:27:08 +00:00
private bool IsDisposed;
2023-02-06 20:14:50 +00:00
~SockChatServer() {
DoDispose();
}
2022-08-30 15:00:58 +00:00
2023-02-06 20:14:50 +00:00
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
2022-08-30 15:00:58 +00:00
2023-02-06 20:14:50 +00:00
private void DoDispose() {
2022-08-30 15:00:58 +00:00
if(IsDisposed)
return;
IsDisposed = true;
2023-02-19 22:27:08 +00:00
IsShuttingDown = true;
2022-08-30 15:00:58 +00:00
2023-02-19 22:27:08 +00:00
foreach(ChatConnection conn in Context.Connections)
conn.Dispose();
2022-08-30 15:00:58 +00:00
Server?.Dispose();
HttpClient?.Dispose();
2022-08-30 15:00:58 +00:00
}
}
}