sharp-chat/SharpChat/SockChatServer.cs

236 lines
8.7 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;
private readonly List<IPacketHandler> GuestHandlers = new();
private readonly List<IPacketHandler> AuthedHandlers = new();
2023-02-16 21:16:06 +00:00
private readonly SendMessageHandler SendMessageHandler;
2022-08-30 15:00:58 +00:00
private bool IsShuttingDown = false;
public SockChatServer(HttpClient httpClient, MisuzuClient msz, IEventStorage evtStore, IConfig config) {
Logger.Write("Initialising Sock Chat server...");
HttpClient = httpClient;
Misuzu = 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;
ChannelInfo channelInfo = new(
2024-05-10 19:18:55 +00:00
name,
channelCfg.SafeReadValue("password", string.Empty),
rank: channelCfg.SafeReadValue("minRank", 0)
);
2022-08-30 15:00:58 +00:00
2024-05-19 21:02:17 +00:00
Context.Channels.Add(channelInfo);
2024-05-10 19:18:55 +00:00
}
2024-05-19 21:02:17 +00:00
if(Context.Channels.PublicCount < 1)
Context.Channels.Add(new ChannelInfo("Default"));
2024-05-19 21:02:17 +00:00
GuestHandlers.Add(new AuthHandler(Misuzu, Context.Channels.MainChannel, MaxMessageLength, MaxConnections));
2023-02-16 21:16:06 +00:00
AuthedHandlers.AddRange(new IPacketHandler[] {
2023-02-16 21:16:06 +00:00
new PingHandler(Misuzu),
SendMessageHandler = new SendMessageHandler(MaxMessageLength),
});
SendMessageHandler.AddCommands(new IUserCommand[] {
2024-05-14 22:17:25 +00:00
new UserAFKCommand(),
new UserNickCommand(),
new MessageWhisperCommand(),
new MessageActionCommand(),
new WhoCommand(),
2024-05-14 22:17:25 +00:00
new ChannelJoinCommand(),
new ChannelCreateCommand(),
new ChannelDeleteCommand(),
new ChannelPasswordCommand(),
new ChannelRankCommand(),
new MessageBroadcastCommand(),
new MessageDeleteCommand(),
new KickBanCommand(msz),
new PardonUserCommand(msz),
new PardonAddressCommand(msz),
new BanListCommand(msz),
new WhoisCommand(),
});
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;
}
ConnectionInfo conn = new(sock);
2023-02-19 22:27:08 +00:00
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(ConnectionInfo 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
private void OnError(ConnectionInfo conn, Exception ex) {
2023-02-19 22:27:08 +00:00
Logger.Write($"[{conn.Id} {conn.RemoteAddress}] {ex}");
Context.SafeUpdate();
2022-08-30 15:00:58 +00:00
}
private void OnClose(ConnectionInfo 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(ConnectionInfo 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) {
UserInfo? 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(
UserInfo.DEFAULT_SIZE,
UserInfo.DEFAULT_MINIMUM_DELAY,
UserInfo.DEFAULT_RISKY_OFFSET
2023-02-19 22:27:08 +00:00
));
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 FloodWarningPacket());
2023-02-19 22:27:08 +00:00
} else {
Context.BanUser(conn.User, banDuration, UserDisconnectReason.Flood);
2023-02-19 22:27:08 +00:00
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
}
PacketHandlerContext context = new(msg, Context, conn);
IPacketHandler? 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
foreach(ConnectionInfo conn in Context.Connections)
2023-02-19 22:27:08 +00:00
conn.Dispose();
2022-08-30 15:00:58 +00:00
Server?.Dispose();
HttpClient?.Dispose();
2022-08-30 15:00:58 +00:00
}
}
}