Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions apps/counterstrikesharp/src/FiveStack.Events/InitConnect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
ConnectRefusal.Password
);
public static ConnectRoleBook ConnectRoles = new();
public static RefusedConnects RefusedConnects = new();

// near "CNetworkGameServerBase::ConnectClient( name=\'%s\', remote=\'%s\' )\n"
private static string ConnectClientSignature = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
Expand Down Expand Up @@ -68,6 +69,15 @@
ConnectDecision decision = ConnectUtility.Authorize(rules, steamId, token);

ConnectRoles.Offer(steamId, rules?.match_id, decision.pending_role);
// With a password the engine refuses the client itself; without one it is
// let in and kicked with a reason at connect full.
bool refusedByPassword =
decision.action == eConnectAction.Reject
&& ConnectRefusal.ByPassword(ConVar.Find("sv_password")?.StringValue);

Check warning on line 76 in apps/counterstrikesharp/src/FiveStack.Events/InitConnect.cs

View workflow job for this annotation

GitHub Actions / test (counterstrikesharp)

'ConVar' is obsolete: 'Use ConVar<T> instead for type-safe access to ConVars.'
RefusedConnects.Record(
steamId,
decision.action == eConnectAction.Reject && !refusedByPassword
);

_logger.LogInformation(
"{connect}",
Expand All @@ -91,15 +101,10 @@
}
break;
case eConnectAction.Reject:
if (ConnectRefusal.ByPassword(ConVar.Find("sv_password")?.StringValue))
if (refusedByPassword)
{
hook.SetParam(5, RefusedPasswordBuffer);
}
else
{
hook.SetParam(6, 0);
hook.SetParam(7, 0);
}
break;
}

Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/FiveStack.Events/MapChange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public void ListenForMapChange()
async (mapName) =>
{
_logger.LogInformation("map changed: precaching models");
RefusedConnects.Clear();

Server.PrecacheModel(ModelPathCtmSas);
Server.PrecacheModel(ModelPathTmPhoenix);
Expand Down
40 changes: 40 additions & 0 deletions apps/counterstrikesharp/src/FiveStack.Events/PlayerConnected.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.ValveConstants.Protobuf;
using FiveStack.Entities;
using FiveStack.Utilities;
using Microsoft.Extensions.Logging;
Expand All @@ -12,6 +13,8 @@ namespace FiveStack;
public partial class FiveStackPlugin
{
private readonly HashSet<ulong> _overCapacityKicks = new();
private readonly HashSet<ulong> _refusedKicks = new();
private const float RefusedKickDelaySeconds = 4f;

[GameEventHandler]
public HookResult OnPlayerConnect(EventPlayerConnectFull @event, GameEventInfo info)
Expand All @@ -21,6 +24,43 @@ public HookResult OnPlayerConnect(EventPlayerConnectFull @event, GameEventInfo i
return HookResult.Continue;
}

// Still marked after a map change inside the kick delay: kicked again.
if (
RefusedConnects.Take(@event.Userid.SteamID)
|| _refusedKicks.Contains(@event.Userid.SteamID)
)
{
CCSPlayerController refused = @event.Userid;
ulong steamId = refused.SteamID;
string reason = _gameServer.Localize(refused, "player.join.refused");

_logger.LogInformation($"Kicking {refused.PlayerName} ({steamId}): refused at connect");
_refusedKicks.Add(steamId);

// CounterStrikeSharp cannot put a reason on the kick, so it is
// shown first.
refused.ChangeTeam(CsTeam.Spectator);
refused.PrintToChat(reason);
refused.PrintToCenter(reason);
TimerUtility.AddTimer(
RefusedKickDelaySeconds,
() =>
{
// Gone and back in the meantime: that connect decides again.
if (
refused.IsValid
&& refused.SteamID == steamId
&& refused.Connected == PlayerConnectedState.Connected
&& _refusedKicks.Contains(steamId)
)
{
refused.Disconnect(NetworkDisconnectionReason.NETWORK_DISCONNECT_KICKED);
}
}
);
return HookResult.Continue;
}

ClearCommunicationAbuseMute(@event.Userid, LogLevel.Information);

MatchManager? match = _matchService.GetCurrentMatch();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo

eDisconnectHandling handling = PlayerDisconnectUtility.Handle(
player.IsBot,
_overCapacityKicks.Remove(player.SteamID),
_overCapacityKicks.Remove(player.SteamID) | _refusedKicks.Remove(player.SteamID),
member != null
);

Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/ar-SA.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " اكتب {0}{1}help {2} لعرض الأوامر المتاحة",
"player.join.ready_hint": " اكتب {0}{1}r{2} للاستعداد!",
"player.join.link_discord": " لست في فريق؟ سجّل الدخول إلى 5stack.gg بحساب Discord الخاص بك لتأخذ مقعدك، ثم ابقَ متصلاً",
"player.join.refused": "هذا الخادم يستضيف مباراة ولست ضمن تشكيلتها. انضم إلى المباريات من اللوحة.",
"match.resume_hint": "للاستئناف اكتب {0}resume",
"match.received_data": "تم استلام بيانات المباراة",
"match.tv_delay": "تأخير التلفاز ({0}ث متبقية)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/da-DK.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Skriv {0}{1}help {2} for tilgængelige kommandoer",
"player.join.ready_hint": " Skriv {0}{1}r{2} for at blive klar!",
"player.join.link_discord": " Ikke på et hold? Log ind på 5stack.gg med din Discord-konto for at tage din plads, og bliv forbundet",
"player.join.refused": "Denne server kører en kamp, og du er ikke med i holdopstillingen. Deltag i kampe fra panelet.",
"match.resume_hint": "for at genoptage skriv {0}resume",
"match.received_data": "Modtog kampdata",
"match.tv_delay": "TV-forsinkelse ({0}s tilbage)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/de-DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Tippe {0}{1}help {2} für verfügbare Befehle",
"player.join.ready_hint": " Tippe {0}{1}r{2} um bereit zu sein!",
"player.join.link_discord": " Kein Team? Melde dich auf 5stack.gg mit deinem Discord-Konto an, um deinen Platz einzunehmen, und bleib verbunden",
"player.join.refused": "Auf diesem Server läuft ein Match, und du bist nicht im Aufgebot. Tritt Matches über das Panel bei.",
"match.resume_hint": "zum Fortsetzen {0}resume eingeben",
"match.received_data": "Matchdaten empfangen",
"match.tv_delay": "TV‑Verzögerung ({0}s übrig)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
"player.join.help_hint": " Type {0}{1}help {2} for available commands",
"player.join.ready_hint": " Type {0}{1}r{2} to ready up!",
"player.join.link_discord": " Not on a team? Log in at 5stack.gg with your Discord account to take your seat, then stay connected",
"player.join.refused": "This server is running a match and you are not in its lineup. Join matches from the panel.",
"match.resume_hint": "to resume type {0}resume",
"match.received_data": "Received Match Data",
"match.tv_delay": "TV delay ({0}s left)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/es-ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Escribe {0}{1}help {2} para ver comandos disponibles",
"player.join.ready_hint": " ¡Escribe {0}{1}r{2} para estar listo!",
"player.join.link_discord": " ¿Sin equipo? Inicia sesión en 5stack.gg con tu cuenta de Discord para ocupar tu plaza y no te desconectes",
"player.join.refused": "Este servidor está jugando una partida y no estás en su alineación. Únete a las partidas desde el panel.",
"match.resume_hint": "para reanudar escribe {0}resume",
"match.received_data": "Datos del partido recibidos",
"match.tv_delay": "Retraso de TV ({0}s restantes)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Tapez {0}{1}help {2} pour les commandes disponibles",
"player.join.ready_hint": " Tapez {0}{1}r{2} pour être prêt !",
"player.join.link_discord": " Pas dans une équipe ? Connecte-toi sur 5stack.gg avec ton compte Discord pour prendre ta place, puis reste connecté",
"player.join.refused": "Ce serveur accueille un match et vous ne faites pas partie de sa composition. Rejoignez les matchs depuis le panneau.",
"match.resume_hint": "pour reprendre tapez {0}resume",
"match.received_data": "Données du match reçues",
"match.tv_delay": "Délai TV ({0}s restants)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/it-IT.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Digita {0}{1}help {2} per i comandi disponibili",
"player.join.ready_hint": " Digita {0}{1}r{2} per essere pronto!",
"player.join.link_discord": " Non sei in una squadra? Accedi a 5stack.gg con il tuo account Discord per prendere il tuo posto, poi resta connesso",
"player.join.refused": "Su questo server è in corso una partita e non sei nella formazione. Unisciti alle partite dal pannello.",
"match.resume_hint": "per riprendere digita {0}resume",
"match.received_data": "Dati della partita ricevuti",
"match.tv_delay": "Ritardo TV ({0}s rimanenti)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/ja-JP.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " 利用可能なコマンドを見るには {0}{1}help {2} を入力",
"player.join.ready_hint": " 準備するには {0}{1}r{2} と入力!",
"player.join.link_discord": " チームに入っていませんか?5stack.gg に Discord アカウントでログインして席を確保し、そのまま接続していてください",
"player.join.refused": "このサーバーでは試合が行われており、あなたはそのメンバーではありません。試合にはパネルから参加してください。",
"match.resume_hint": "再開するには {0}resume と入力",
"match.received_data": "試合データを受信しました",
"match.tv_delay": "TV 遅延(残り {0}s)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/ko-KR.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"player.join.help_hint": " 사용 가능한 명령을 보려면 {0}{1}help {2} 입력",
"player.join.ready_hint": " 준비하려면 {0}{1}r{2} 입력!",
"player.join.link_discord": " 팀에 없나요? 5stack.gg에 Discord 계정으로 로그인해 자리를 차지한 뒤 접속을 유지하세요",
"player.join.refused": "이 서버에서는 경기가 진행 중이며 당신은 해당 라인업에 없습니다. 경기는 패널에서 참가하세요.",
"match.resume_hint": "재개하려면 {0}resume 입력",
"match.received_data": "경기 데이터 수신됨",
"match.tv_delay": "TV 지연({0}s 남음)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/pl-PL.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Wpisz {0}{1}help {2} dla dostępnych poleceń",
"player.join.ready_hint": " Wpisz {0}{1}r{2}, aby być gotowym!",
"player.join.link_discord": " Nie jesteś w drużynie? Zaloguj się na 5stack.gg kontem Discord, aby zająć swoje miejsce, i pozostań połączony",
"player.join.refused": "Na tym serwerze trwa mecz, a nie jesteś w jego składzie. Dołączaj do meczów przez panel.",
"match.resume_hint": "aby wznowić wpisz {0}resume",
"match.received_data": "Otrzymano dane meczu",
"match.tv_delay": "Opóźnienie TV ({0}s pozostało)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
"player.join.help_hint": "Digite {0}{1}help {2} para ver comandos disponíveis",
"player.join.ready_hint": "Digite {0}{1}r{2} para ficar pronto!",
"player.join.link_discord": " Sem time? Entre no 5stack.gg com sua conta do Discord para ocupar sua vaga e continue conectado",
"player.join.refused": "Este servidor está rodando uma partida e você não está na escalação. Entre nas partidas pelo painel.",
"match.resume_hint": "para retomar digite {0}resume",
"match.received_data": "Dados da partida recebidos",
"match.tv_delay": "Delay da TV ({0}s restantes)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/ru-RU.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Введите {0}{1}help {2} для доступных команд",
"player.join.ready_hint": " Введите {0}{1}r{2}, чтобы быть готовым!",
"player.join.link_discord": " Не в команде? Войдите на 5stack.gg через аккаунт Discord, чтобы занять своё место, и оставайтесь на сервере",
"player.join.refused": "На этом сервере идёт матч, а вас нет в его составе. Присоединяйтесь к матчам через панель.",
"match.resume_hint": "для возобновления введите {0}resume",
"match.received_data": "Данные матча получены",
"match.tv_delay": "Задержка ТВ ({0}с осталось)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/sv-SE.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Skriv {0}{1}help {2} för tillgängliga kommandon",
"player.join.ready_hint": " Skriv {0}{1}r{2} för att bli redo!",
"player.join.link_discord": " Inte i ett lag? Logga in på 5stack.gg med ditt Discord-konto för att ta din plats och förbli ansluten",
"player.join.refused": "Den här servern kör en match och du är inte med i laguppställningen. Gå med i matcher via panelen.",
"match.resume_hint": "för att återuppta skriv {0}resume",
"match.received_data": "Matchdata mottagna",
"match.tv_delay": "TV-fördröjning ({0}s kvar)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/tr-TR.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"player.join.help_hint": " Kullanılabilir komutlar için {0}{1}help {2} yazın",
"player.join.ready_hint": " Hazır olmak için {0}{1}r{2} yazın!",
"player.join.link_discord": " Bir takımda değil misin? Yerini almak için 5stack.gg'ye Discord hesabınla giriş yap, ardından bağlı kal",
"player.join.refused": "Bu sunucuda bir maç oynanıyor ve kadroda değilsin. Maçlara panelden katıl.",
"match.resume_hint": "devam etmek için {0}resume yazın",
"match.received_data": "Maç verileri alındı",
"match.tv_delay": "TV gecikmesi ({0}s kaldı)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/uk-UA.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " Введіть {0}{1}help {2} для доступних команд",
"player.join.ready_hint": " Введіть {0}{1}r{2}, щоб бути готовим!",
"player.join.link_discord": " Не в команді? Увійдіть на 5stack.gg через обліковий запис Discord, щоб зайняти своє місце, і залишайтеся на сервері",
"player.join.refused": "На цьому сервері йде матч, а вас немає в його складі. Приєднуйтеся до матчів через панель.",
"match.resume_hint": "щоб відновити, введіть {0}resume",
"match.received_data": "Отримано дані матчу",
"match.tv_delay": "Затримка TV ({0}с залишилось)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/zh-Hans.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " 输入 {0}{1}help {2} 查看可用命令",
"player.join.ready_hint": " 输入 {0}{1}r{2} 以就绪!",
"player.join.link_discord": " 没有队伍?请用 Discord 账号登录 5stack.gg 以占据你的位置,然后保持连接",
"player.join.refused": "此服务器正在进行一场比赛,而你不在其阵容中。请通过面板加入比赛。",
"match.resume_hint": "要继续请输入 {0}resume",
"match.received_data": "已接收比赛数据",
"match.tv_delay": "TV 延迟(剩余 {0}s)",
Expand Down
1 change: 1 addition & 0 deletions apps/counterstrikesharp/src/lang/zh-Hant.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"player.join.help_hint": " 輸入 {0}{1}help {2} 查看可用指令",
"player.join.ready_hint": " 輸入 {0}{1}r{2} 以就緒!",
"player.join.link_discord": " 沒有隊伍?請用 Discord 帳號登入 5stack.gg 以取得你的位置,然後保持連線",
"player.join.refused": "此伺服器正在進行一場比賽,而你不在其陣容中。請透過面板加入比賽。",
"match.resume_hint": "要繼續請輸入 {0}resume",
"match.received_data": "已接收比賽數據",
"match.tv_delay": "TV 延遲(剩餘 {0}s)",
Expand Down
43 changes: 31 additions & 12 deletions apps/counterstrikesharp/test/ConnectRefusalTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

// An empty Steam ticket made the engine challenge a refused client again,
// forever, each try holding a slot until the server was full. With a server
// password the client is handed one that can't match, and refused once.
// password the client is handed one that can't match, and refused once;
// without one it is let in and kicked with a reason at connect full.
public class ConnectRefusalTests
{
private static string Code(string app, params string[] path)
Expand Down Expand Up @@ -48,27 +49,45 @@ public void TheRefusedPasswordIsOneNobodyCouldSet()
Assert.Contains(ConnectRefusal.Password, character => char.IsControl(character));
}

private static void RefusesWithThePasswordBeforeStrippingTheTicket(string hook, string byPassword, string stripped)
[Fact]
public void TheMatchConnectHookRefusesWithThePasswordAndNeverStripsTheTicket()
{
Match password = Regex.Match(hook, byPassword);
Match ticket = Regex.Match(hook, stripped);
string hook = Code("counterstrikesharp", "FiveStack.Events", "InitConnect.cs");

Assert.True(password.Success, "the refused password path is gone or changed");
Assert.True(ticket.Success, "the empty ticket path is gone or changed");
Assert.True(password.Index < ticket.Index);
Assert.Matches(@"bool refusedByPassword =\s*decision\.action == eConnectAction\.Reject\s*&&\s*ConnectRefusal\.ByPassword\(ConVar\.Find\(""sv_password""\)\?\.StringValue\);", hook);
Assert.Matches(@"case eConnectAction\.Reject:\s*if\s*\(refusedByPassword\)\s*\{\s*hook\.SetParam\(5, RefusedPasswordBuffer\);\s*\}\s*break;", hook);
Assert.Matches(
@"RefusedPasswordBuffer = Marshal\.StringToCoTaskMemUTF8\(\s*ConnectRefusal\.Password\s*\)",
hook
);
Assert.DoesNotMatch(@"SetParam\(\s*[67]\s*,|nint\.Zero,\s*0,", hook);

int authorize = hook.IndexOf("ConnectUtility.Authorize(");
int record = hook.IndexOf("RefusedConnects.Record(");
Assert.True(authorize >= 0 && record > authorize, "the hook no longer records its decision");
// Only a refusal the engine does not enforce itself is kicked later.
Assert.Matches(
@"RefusedConnects\.Record\(\s*steamId,\s*decision\.action == eConnectAction\.Reject && !refusedByPassword\s*\)",
hook
);
Assert.Contains("RefusedConnects.Clear();", Code("counterstrikesharp", "FiveStack.Events", "MapChange.cs"));
}

[Fact]
public void TheMatchConnectHookRefusesWithThePasswordAndOnlyStripsTheTicketWithoutOne()
public void ARefusedClientIsKickedWithAReasonBeforeAnythingElseAtConnectFull()
{
RefusesWithThePasswordBeforeStrippingTheTicket(
Code("counterstrikesharp", "FiveStack.Events", "InitConnect.cs"),
@"case eConnectAction\.Reject:\s*if\s*\(ConnectRefusal\.ByPassword\(ConVar\.Find\(""sv_password""\)\?\.StringValue\)\)\s*\{\s*hook\.SetParam\(5, RefusedPasswordBuffer\);\s*\}",
@"else\s*\{\s*hook\.SetParam\(6, 0\);\s*hook\.SetParam\(7, 0\);\s*\}\s*break;"
string connected = Code("counterstrikesharp", "FiveStack.Events", "PlayerConnected.cs");
string disconnected = Code("counterstrikesharp", "FiveStack.Events", "PlayerDisconnected.cs");

int take = connected.IndexOf("RefusedConnects.Take(");
Assert.True(take >= 0, "connect full no longer takes refused clients");
Assert.True(take < connected.IndexOf("ClearCommunicationAbuseMute("));
Assert.Contains("\"player.join.refused\"", connected);
Assert.Contains("_refusedKicks.Add(", connected);
Assert.Contains("_refusedKicks.Remove(player.SteamID)", disconnected);
Assert.Matches(
@"refused\.Connected == PlayerConnectedState\.Connected\s*&& _refusedKicks\.Contains\(steamId\)\s*\)\s*\{\s*refused\.Disconnect\(",
connected
);
}
}
Loading
Loading