Less haphazard locking (perhaps too?)

This commit is contained in:
flash 2023-02-19 23:27:08 +01:00
parent 70df99fe9b
commit 86a46539f2
22 changed files with 257 additions and 306 deletions

View file

@ -1,37 +1,30 @@
using Fleck;
using SharpChat.Events;
using SharpChat.Events;
using SharpChat.EventStorage;
using SharpChat.Packet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
namespace SharpChat {
public class ChatContext {
public record ChannelUserAssoc(long UserId, string ChannelName);
public readonly SemaphoreSlim ContextAccess = new(1, 1);
public HashSet<ChatChannel> Channels { get; } = new();
public readonly object ChannelsAccess = new();
public HashSet<ChatConnection> Connections { get; } = new();
public readonly object ConnectionsAccess = new();
public HashSet<ChatUser> Users { get; } = new();
public readonly object UsersAccess = new();
public IEventStorage Events { get; }
public readonly object EventsAccess = new();
public HashSet<ChannelUserAssoc> ChannelUsers { get; } = new();
public readonly object ChannelUsersAccess = new();
public Dictionary<long, RateLimiter> UserRateLimiters { get; } = new();
public ChatContext(IEventStorage evtStore) {
Events = evtStore ?? throw new ArgumentNullException(nameof(evtStore));
}
public void Update() {
lock(ConnectionsAccess) {
foreach(ChatConnection conn in Connections)
if(!conn.IsDisposed && conn.HasTimedOut) {
conn.Dispose();
@ -40,39 +33,41 @@ namespace SharpChat {
Connections.RemoveWhere(conn => conn.IsDisposed);
lock(UsersAccess)
foreach(ChatUser user in Users)
if(!Connections.Any(conn => conn.User == user)) {
HandleDisconnect(user, UserDisconnectReason.TimeOut);
Logger.Write($"Timed out {user} (no more connections).");
}
}
public void SafeUpdate() {
ContextAccess.Wait();
try {
Update();
} finally {
ContextAccess.Release();
}
}
public bool IsInChannel(ChatUser user, ChatChannel channel) {
lock(ChannelUsersAccess)
return ChannelUsers.Contains(new ChannelUserAssoc(user.UserId, channel.Name));
}
public string[] GetUserChannelNames(ChatUser user) {
lock(ChannelUsersAccess)
return ChannelUsers.Where(cu => cu.UserId == user.UserId).Select(cu => cu.ChannelName).ToArray();
}
public ChatChannel[] GetUserChannels(ChatUser user) {
string[] names = GetUserChannelNames(user);
lock(ChannelsAccess)
return Channels.Where(c => names.Any(n => c.NameEquals(n))).ToArray();
}
public long[] GetChannelUserIds(ChatChannel channel) {
lock(ChannelUsersAccess)
return ChannelUsers.Where(cu => channel.NameEquals(cu.ChannelName)).Select(cu => cu.UserId).ToArray();
}
public ChatUser[] GetChannelUsers(ChatChannel channel) {
long[] ids = GetChannelUserIds(channel);
lock(UsersAccess)
return Users.Where(u => ids.Contains(u.UserId)).ToArray();
}
@ -82,18 +77,15 @@ namespace SharpChat {
else
SendTo(user, new ForceDisconnectPacket(ForceDisconnectReason.Kicked));
lock(ConnectionsAccess) {
foreach(ChatConnection conn in Connections)
if(conn.User == user)
conn.Dispose();
Connections.RemoveWhere(conn => conn.IsDisposed);
}
HandleDisconnect(user, reason);
}
public void HandleJoin(ChatUser user, ChatChannel chan, ChatConnection conn, int maxMsgLength) {
lock(EventsAccess) {
if(!IsInChannel(user, chan)) {
SendTo(chan, new UserConnectPacket(DateTimeOffset.Now, user));
Events.AddEvent(new UserConnectEvent(DateTimeOffset.Now, user, chan));
@ -105,27 +97,18 @@ namespace SharpChat {
foreach(IChatEvent msg in Events.GetChannelEventLog(chan.Name))
conn.Send(new ContextMessagePacket(msg));
lock(ChannelsAccess)
conn.Send(new ContextChannelsPacket(Channels.Where(c => c.Rank <= user.Rank)));
lock(UsersAccess)
Users.Add(user);
lock(ChannelUsersAccess) {
ChannelUsers.Add(new ChannelUserAssoc(user.UserId, chan.Name));
user.CurrentChannel = chan;
}
}
}
public void HandleDisconnect(ChatUser user, UserDisconnectReason reason = UserDisconnectReason.Leave) {
user.Status = ChatUserStatus.Offline;
lock(EventsAccess) {
lock(UsersAccess)
Users.Remove(user);
lock(ChannelUsersAccess) {
ChatChannel[] channels = GetUserChannels(user);
foreach(ChatChannel chan in channels) {
@ -135,12 +118,9 @@ namespace SharpChat {
Events.AddEvent(new UserDisconnectEvent(DateTimeOffset.Now, user, chan, reason));
if(chan.IsTemporary && chan.Owner == user)
lock(ChannelsAccess)
RemoveChannel(chan);
}
}
}
}
public void SwitchChannel(ChatUser user, ChatChannel chan, string password) {
if(user.CurrentChannel == chan) {
@ -166,13 +146,11 @@ namespace SharpChat {
}
public void ForceChannelSwitch(ChatUser user, ChatChannel chan) {
lock(ChannelsAccess)
if(!Channels.Contains(chan))
return;
ChatChannel oldChan = user.CurrentChannel;
lock(EventsAccess) {
SendTo(oldChan, new UserChannelLeavePacket(user));
Events.AddEvent(new UserChannelLeaveEvent(DateTimeOffset.Now, user, oldChan));
SendTo(chan, new UserChannelJoinPacket(user));
@ -186,15 +164,11 @@ namespace SharpChat {
ForceChannel(user, chan);
lock(ChannelUsersAccess) {
ChannelUsers.Remove(new ChannelUserAssoc(user.UserId, oldChan.Name));
ChannelUsers.Add(new ChannelUserAssoc(user.UserId, chan.Name));
user.CurrentChannel = chan;
}
}
if(oldChan.IsTemporary && oldChan.Owner == user)
lock(ChannelsAccess)
RemoveChannel(oldChan);
}
@ -202,7 +176,6 @@ namespace SharpChat {
if(packet == null)
throw new ArgumentNullException(nameof(packet));
lock(ConnectionsAccess)
foreach(ChatConnection conn in Connections)
if(conn.IsAuthed)
conn.Send(packet);
@ -214,7 +187,6 @@ namespace SharpChat {
if(packet == null)
throw new ArgumentNullException(nameof(packet));
lock(ConnectionsAccess)
foreach(ChatConnection conn in Connections)
if(conn.IsAlive && conn.User == user)
conn.Send(packet);
@ -227,15 +199,12 @@ namespace SharpChat {
throw new ArgumentNullException(nameof(packet));
// might be faster to grab the users first and then cascade into that SendTo
lock(ConnectionsAccess) {
IEnumerable<ChatConnection> conns = Connections.Where(c => c.IsAuthed && IsInChannel(c.User, channel));
foreach(ChatConnection conn in conns)
conn.Send(packet);
}
}
public IPAddress[] GetRemoteAddresses(ChatUser user) {
lock(ConnectionsAccess)
return Connections.Where(c => c.IsAlive && c.User == user).Select(c => c.RemoteAddress).Distinct().ToArray();
}
@ -273,7 +242,6 @@ namespace SharpChat {
channel.Password = password;
// Users that no longer have access to the channel/gained access to the channel by the hierarchy change should receive delete and create packets respectively
lock(UsersAccess)
foreach(ChatUser user in Users.Where(u => u.Rank >= channel.Rank)) {
SendTo(user, new ChannelUpdatePacket(prevName, channel));
@ -299,7 +267,6 @@ namespace SharpChat {
SwitchChannel(user, defaultChannel, string.Empty);
// Broadcast deletion of channel
lock(UsersAccess)
foreach(ChatUser user in Users.Where(u => u.Rank >= channel.Rank))
SendTo(user, new ChannelDeletePacket(channel));
}

View file

@ -22,8 +22,6 @@ namespace SharpChat {
public bool HasFloodProtection
=> Rank < RANK_NO_FLOOD;
public readonly RateLimiter RateLimiter = new(DEFAULT_SIZE, DEFAULT_MINIMUM_DELAY, DEFAULT_RISKY_OFFSET);
// This needs to be a session thing
public ChatChannel CurrentChannel { get; set; }

View file

@ -38,7 +38,6 @@ namespace SharpChat.Commands {
return;
}
lock(ctx.Chat.ChannelsAccess) {
if(ctx.Chat.Channels.Any(c => c.NameEquals(createChanName))) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_ALREADY_EXISTS, true, createChanName));
return;
@ -52,14 +51,11 @@ namespace SharpChat.Commands {
};
ctx.Chat.Channels.Add(createChan);
lock(ctx.Chat.UsersAccess) {
foreach(ChatUser ccu in ctx.Chat.Users.Where(u => u.Rank >= ctx.Channel.Rank))
ctx.Chat.SendTo(ccu, new ChannelCreatePacket(ctx.Channel));
}
ctx.Chat.SwitchChannel(ctx.User, createChan, createChan.Password);
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_CREATED, false, createChan.Name));
}
}
}
}

View file

@ -17,9 +17,7 @@ namespace SharpChat.Commands {
}
string delChanName = string.Join('_', ctx.Args);
ChatChannel delChan;
lock(ctx.Chat.ChannelsAccess)
delChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(delChanName));
ChatChannel delChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(delChanName));
if(delChan == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_NOT_FOUND, true, delChanName));
@ -31,7 +29,6 @@ namespace SharpChat.Commands {
return;
}
lock(ctx.Chat.ChannelsAccess)
ctx.Chat.RemoveChannel(delChan);
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_DELETED, false, delChan.Name));
}

View file

@ -26,7 +26,6 @@ namespace SharpChat.Commands {
return;
}
lock(ctx.Chat.EventsAccess) {
IChatEvent delMsg = ctx.Chat.Events.GetEvent(delSeqId);
if(delMsg == null || delMsg.Sender.Rank > ctx.User.Rank || (!deleteAnyMessage && delMsg.Sender.UserId != ctx.User.UserId)) {
@ -39,4 +38,3 @@ namespace SharpChat.Commands {
}
}
}
}

View file

@ -9,9 +9,7 @@ namespace SharpChat.Commands {
public void Dispatch(ChatCommandContext ctx) {
string joinChanStr = ctx.Args.FirstOrDefault();
ChatChannel joinChan;
lock(ctx.Chat.ChannelsAccess)
joinChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(joinChanStr));
ChatChannel joinChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(joinChanStr));
if(joinChan == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_NOT_FOUND, true, joinChanStr));

View file

@ -30,7 +30,6 @@ namespace SharpChat.Commands {
int banReasonIndex = 1;
ChatUser banUser = null;
lock(ctx.Chat.UsersAccess)
if(banUserTarget == null || (banUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(banUserTarget))) == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, banUser == null ? "User" : banUserTarget));
return;

View file

@ -18,7 +18,6 @@ namespace SharpChat.Commands {
int offset = 0;
if(setOthersNick && long.TryParse(ctx.Args.FirstOrDefault(), out long targetUserId) && targetUserId > 0) {
lock(ctx.Chat.UsersAccess)
targetUser = ctx.Chat.Users.FirstOrDefault(u => u.UserId == targetUserId);
++offset;
}
@ -42,7 +41,6 @@ namespace SharpChat.Commands {
else if(string.IsNullOrEmpty(nickStr))
nickStr = null;
lock(ctx.Chat.UsersAccess)
if(!string.IsNullOrWhiteSpace(nickStr) && ctx.Chat.Users.Any(u => u.NameEquals(nickStr))) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.NAME_IN_USE, true, nickStr));
return;

View file

@ -30,12 +30,9 @@ namespace SharpChat.Commands {
return;
}
ChatUser unbanUser;
lock(ctx.Chat.UsersAccess)
unbanUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(unbanUserTarget));
ChatUser unbanUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(unbanUserTarget));
if(unbanUser == null && long.TryParse(unbanUserTarget, out long unbanUserId)) {
unbanUserTargetIsName = false;
lock(ctx.Chat.UsersAccess)
unbanUser = ctx.Chat.Users.FirstOrDefault(u => u.UserId == unbanUserId);
}

View file

@ -18,7 +18,6 @@ namespace SharpChat.Commands {
if(string.IsNullOrWhiteSpace(chanPass))
chanPass = string.Empty;
lock(ctx.Chat.ChannelsAccess)
ctx.Chat.UpdateChannel(ctx.Channel, password: chanPass);
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_PASSWORD_CHANGED, false));
}

View file

@ -20,7 +20,6 @@ namespace SharpChat.Commands {
return;
}
lock(ctx.Chat.ChannelsAccess)
ctx.Chat.UpdateChannel(ctx.Channel, hierarchy: chanHierarchy);
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_HIERARCHY_CHANGED, false));
}

View file

@ -18,7 +18,6 @@ namespace SharpChat.Commands {
string ipUserStr = ctx.Args.FirstOrDefault();
ChatUser ipUser;
lock(ctx.Chat.UsersAccess)
if(string.IsNullOrWhiteSpace(ipUserStr) || (ipUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(ipUserStr))) == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, ipUserStr ?? "User"));
return;

View file

@ -27,7 +27,6 @@ namespace SharpChat.Commands {
return;
if(ctx.NameEquals("restart"))
lock(ctx.Chat.ConnectionsAccess)
foreach(ChatConnection conn in ctx.Chat.Connections)
conn.PrepareForRestart();

View file

@ -17,7 +17,6 @@ namespace SharpChat.Commands {
string silUserStr = ctx.Args.FirstOrDefault();
ChatUser silUser;
lock(ctx.Chat.UsersAccess)
if(string.IsNullOrWhiteSpace(silUserStr) || (silUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(silUserStr))) == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, silUserStr ?? "User"));
return;

View file

@ -17,7 +17,6 @@ namespace SharpChat.Commands {
string unsilUserStr = ctx.Args.FirstOrDefault();
ChatUser unsilUser;
lock(ctx.Chat.UsersAccess)
if(string.IsNullOrWhiteSpace(unsilUserStr) || (unsilUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(unsilUserStr))) == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, unsilUserStr ?? "User"));
return;

View file

@ -16,15 +16,14 @@ namespace SharpChat.Commands {
return;
}
ChatUser whisperUser;
string whisperUserStr = ctx.Args.FirstOrDefault();
lock(ctx.Chat.UsersAccess)
whisperUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(whisperUserStr));
ChatUser whisperUser = ctx.Chat.Users.FirstOrDefault(u => u.NameEquals(whisperUserStr));
if(whisperUser == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, whisperUserStr));
return;
}
if(whisperUser == ctx.User)
return;

View file

@ -13,7 +13,6 @@ namespace SharpChat.Commands {
string whoChanStr = ctx.Args.FirstOrDefault();
if(string.IsNullOrEmpty(whoChanStr)) {
lock(ctx.Chat.UsersAccess)
foreach(ChatUser whoUser in ctx.Chat.Users) {
whoChanSB.Append(@"<a href=""javascript:void(0);"" onclick=""UI.InsertChatText(this.innerHTML);""");
@ -30,9 +29,7 @@ namespace SharpChat.Commands {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.USERS_LISTING_SERVER, false, whoChanSB));
} else {
ChatChannel whoChan;
lock(ctx.Chat.ChannelsAccess)
whoChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(whoChanStr));
ChatChannel whoChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(whoChanStr));
if(whoChan == null) {
ctx.Chat.SendTo(ctx.User, new LegacyCommandResponse(LCR.CHANNEL_NOT_FOUND, true, whoChanStr));

View file

@ -98,7 +98,6 @@ namespace SharpChat.PacketHandlers {
return;
}
lock(ctx.Chat.UsersAccess) {
ChatUser user = ctx.Chat.Users.FirstOrDefault(u => u.UserId == fai.UserId);
if(user == null)
@ -110,7 +109,6 @@ namespace SharpChat.PacketHandlers {
}
// Enforce a maximum amount of connections per user
lock(ctx.Chat.ConnectionsAccess)
if(ctx.Chat.Connections.Count(conn => conn.User == user) >= MaxConnections) {
ctx.Connection.Send(new AuthFailPacket(AuthFailReason.MaxSessions));
ctx.Connection.Dispose();
@ -130,7 +128,6 @@ namespace SharpChat.PacketHandlers {
}
ctx.Chat.HandleJoin(user, DefaultChannel, ctx.Connection, MaxMessageLength);
}
}).Wait();
}
}

View file

@ -32,17 +32,10 @@ namespace SharpChat.PacketHandlers {
lock(BumpAccess) {
if(LastBump < DateTimeOffset.UtcNow - BumpInterval) {
(string, string)[] bumpList;
lock(ctx.Chat.UsersAccess) {
IEnumerable<ChatUser> filtered = ctx.Chat.Users.Where(u => u.Status == ChatUserStatus.Online);
lock(ctx.Chat.ConnectionsAccess)
filtered = filtered.Where(u => ctx.Chat.Connections.Any(c => c.User == u));
bumpList = filtered
(string, string)[] bumpList = ctx.Chat.Users
.Where(u => u.Status == ChatUserStatus.Online && ctx.Chat.Connections.Any(c => c.User == u))
.Select(u => (u.UserId.ToString(), ctx.Chat.GetRemoteAddresses(u).FirstOrDefault()?.ToString() ?? string.Empty))
.ToArray();
}
if(bumpList.Any())
Task.Run(async () => {

View file

@ -94,10 +94,8 @@ namespace SharpChat.PacketHandlers {
Text = messageText,
};
lock(ctx.Chat.EventsAccess) {
ctx.Chat.Events.AddEvent(message);
ctx.Chat.SendTo(channel, new ChatMessageAddPacket(message));
}
}
}
}

View file

@ -7,7 +7,7 @@ namespace SharpChat {
private readonly int RiskyOffset;
private readonly long[] TimePoints;
public RateLimiter(int size, int minDelay, int riskyOffset) {
public RateLimiter(int size, int minDelay, int riskyOffset = 0) {
if(size < 2)
throw new ArgumentException("Size is too small.", nameof(size));
if(minDelay < 1000)

View file

@ -10,7 +10,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SharpChat {
public class SockChatServer : IDisposable {
@ -19,15 +18,6 @@ namespace SharpChat {
public const int DEFAULT_MAX_CONNECTIONS = 5;
public const int DEFAULT_FLOOD_KICK_LENGTH = 30;
public bool IsDisposed { get; private set; }
public static ChatUser Bot { get; } = new ChatUser {
UserId = -1,
Username = "ChatBot",
Rank = 0,
Colour = new ChatColour(),
};
public IWebSocketServer Server { get; }
public ChatContext Context { get; }
@ -115,14 +105,13 @@ namespace SharpChat {
SendMessageHandler.AddCommand(new ShutdownRestartCommand(waitHandle, () => !IsShuttingDown && (IsShuttingDown = true)));
Server.Start(sock => {
if(IsShuttingDown || IsDisposed) {
if(IsShuttingDown) {
sock.Close(1013);
return;
}
ChatConnection conn;
lock(Context.ConnectionsAccess)
Context.Connections.Add(conn = new(sock));
ChatConnection conn = new(sock);
Context.Connections.Add(conn);
sock.OnOpen = () => OnOpen(conn);
sock.OnClose = () => OnClose(conn);
@ -135,51 +124,78 @@ namespace SharpChat {
private void OnOpen(ChatConnection conn) {
Logger.Write($"Connection opened from {conn.RemoteAddress}:{conn.RemotePort}");
Context.SafeUpdate();
}
Context.Update();
private void OnError(ChatConnection conn, Exception ex) {
Logger.Write($"[{conn.Id} {conn.RemoteAddress}] {ex}");
Context.SafeUpdate();
}
private void OnClose(ChatConnection conn) {
Logger.Write($"Connection closed from {conn.RemoteAddress}:{conn.RemotePort}");
lock(Context.ConnectionsAccess) {
Context.ContextAccess.Wait();
try {
Context.Connections.Remove(conn);
if(conn.User != null && !Context.Connections.Any(c => c.User == conn.User))
Context.HandleDisconnect(conn.User);
}
Context.Update();
} finally {
Context.ContextAccess.Release();
}
private void OnError(ChatConnection conn, Exception ex) {
Logger.Write($"[{conn.Id} {conn.RemoteAddress}] {ex}");
Context.Update();
}
private void OnMessage(ChatConnection conn, string msg) {
Context.Update();
Context.SafeUpdate();
// this doesn't affect non-authed connections?????
if(conn.User is not null && conn.User.HasFloodProtection) {
conn.User.RateLimiter.Update();
ChatUser banUser = null;
string banAddr = string.Empty;
TimeSpan banDuration = TimeSpan.MinValue;
if(conn.User.RateLimiter.IsExceeded) {
Task.Run(async () => {
TimeSpan duration = TimeSpan.FromSeconds(FloodKickLength);
Context.ContextAccess.Wait();
try {
if(!Context.UserRateLimiters.TryGetValue(conn.User.UserId, out RateLimiter rateLimiter))
Context.UserRateLimiters.Add(conn.User.UserId, rateLimiter = new RateLimiter(
ChatUser.DEFAULT_SIZE,
ChatUser.DEFAULT_MINIMUM_DELAY,
ChatUser.DEFAULT_RISKY_OFFSET
));
await Misuzu.CreateBanAsync(
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());
} else {
Context.BanUser(conn.User, banDuration, UserDisconnectReason.Flood);
if(banDuration > TimeSpan.Zero)
Misuzu.CreateBanAsync(
conn.User.UserId.ToString(), conn.RemoteAddress.ToString(),
string.Empty, "::1",
duration,
banDuration,
"Kicked from chat for flood protection."
);
).Wait();
Context.BanUser(conn.User, duration, UserDisconnectReason.Flood);
}).Wait();
return;
} else if(conn.User.RateLimiter.IsRisky)
Context.SendTo(conn.User, new FloodWarningPacket());
}
}
} finally {
Context.ContextAccess.Release();
}
}
ChatPacketHandlerContext context = new(msg, Context, conn);
@ -187,8 +203,17 @@ namespace SharpChat {
? GuestHandlers.FirstOrDefault(h => h.IsMatch(context))
: AuthedHandlers.FirstOrDefault(h => h.IsMatch(context));
handler?.Handle(context);
if(handler is not null) {
Context.ContextAccess.Wait();
try {
handler.Handle(context);
} finally {
Context.ContextAccess.Release();
}
}
}
private bool IsDisposed;
~SockChatServer() {
DoDispose();
@ -203,8 +228,8 @@ namespace SharpChat {
if(IsDisposed)
return;
IsDisposed = true;
IsShuttingDown = true;
lock(Context.ConnectionsAccess)
foreach(ChatConnection conn in Context.Connections)
conn.Dispose();