Unstable v0.19.1.0

This commit is contained in:
Juan Pablo Arce
2022-08-19 13:59:08 -03:00
parent 6b55adcdd9
commit 1219615d64
192 changed files with 3875 additions and 2648 deletions
@@ -9,56 +9,16 @@ namespace Barotrauma.Networking
{
partial class BannedPlayer
{
private static UInt16 LastIdentifier = 0;
private static UInt32 LastIdentifier = 0;
public BannedPlayer(string name, string endPoint, string reason, DateTime? expirationTime)
public BannedPlayer(
string name, Either<Address, AccountId> addressOrAccountId, string reason, DateTime? expirationTime)
{
this.Name = name;
this.EndPoint = endPoint;
ParseEndPointAsSteamId();
this.AddressOrAccountId = addressOrAccountId;
this.Reason = reason;
this.ExpirationTime = expirationTime;
this.UniqueIdentifier = LastIdentifier; LastIdentifier++;
this.IsRangeBan = EndPoint.IndexOf(".x") > -1;
}
public BannedPlayer(string name, ulong steamID, string reason, DateTime? expirationTime)
{
this.Name = name;
this.SteamID = steamID;
this.Reason = reason;
this.ExpirationTime = expirationTime;
this.UniqueIdentifier = LastIdentifier; LastIdentifier++;
this.IsRangeBan = false;
this.EndPoint = "";
}
public bool CompareTo(string endpointCompare)
{
if (string.IsNullOrEmpty(EndPoint) || string.IsNullOrEmpty(endpointCompare)) { return false; }
if (!IsRangeBan)
{
return endpointCompare == EndPoint;
}
else
{
int rangeBanIndex = EndPoint.IndexOf(".x");
if (endpointCompare.Length < rangeBanIndex) return false;
return endpointCompare.Substring(0, rangeBanIndex) == EndPoint.Substring(0, rangeBanIndex);
}
}
public bool CompareTo(IPAddress ipCompare)
{
if (string.IsNullOrEmpty(EndPoint) || ipCompare == null) { return false; }
if (ipCompare.IsIPv4MappedToIPv6 && CompareTo(ipCompare.MapToIPv4NoThrow().ToString()))
{
return true;
}
return CompareTo(ipCompare.ToString());
}
}
@@ -84,10 +44,10 @@ namespace Barotrauma.Networking
foreach (string line in lines)
{
string[] separatedLine = line.Split(',');
if (separatedLine.Length < 2) continue;
if (separatedLine.Length < 2) { continue; }
string name = separatedLine[0];
string identifier = separatedLine[1];
string endpointStr = separatedLine[1];
DateTime? expirationTime = null;
if (separatedLine.Length > 2 && !string.IsNullOrEmpty(separatedLine[2]))
@@ -99,84 +59,57 @@ namespace Barotrauma.Networking
}
string reason = separatedLine.Length > 3 ? string.Join(",", separatedLine.Skip(3)) : "";
if (expirationTime.HasValue && DateTime.Now > expirationTime.Value) continue;
if (expirationTime.HasValue && DateTime.Now > expirationTime.Value) { continue; }
if (identifier.Contains(".") || identifier.Contains(":"))
if (AccountId.Parse(endpointStr).TryUnwrap(out var accountId))
{
//identifier is an ip
bannedPlayers.Add(new BannedPlayer(name, identifier, reason, expirationTime));
bannedPlayers.Add(new BannedPlayer(name, accountId, reason, expirationTime));
}
else
else if (Address.Parse(endpointStr).TryUnwrap(out var address))
{
//identifier should be a steam id
if (ulong.TryParse(identifier, out ulong steamID))
{
bannedPlayers.Add(new BannedPlayer(name, steamID, reason, expirationTime));
}
else
{
DebugConsole.ThrowError("Error in banlist: \"" + identifier + "\" is not a valid IP or a Steam ID");
}
bannedPlayers.Add(new BannedPlayer(name, address, reason, expirationTime));
}
}
}
public bool IsBanned(IPAddress IP, ulong steamID, ulong ownerSteamID, out string reason)
public void RemoveExpired()
{
reason = string.Empty;
if (IPAddress.IsLoopback(IP)) { return false; }
var bannedPlayer = bannedPlayers.Find(bp =>
bp.CompareTo(IP) ||
(steamID > 0 && (bp.SteamID == steamID || SteamManager.SteamIDStringToUInt64(bp.EndPoint) == steamID)) ||
(ownerSteamID > 0 && (bp.SteamID == ownerSteamID || SteamManager.SteamIDStringToUInt64(bp.EndPoint) == ownerSteamID)));
reason = bannedPlayer?.Reason;
return bannedPlayer != null;
}
public bool IsBanned(IPAddress IP, out string reason)
{
reason = string.Empty;
if (IPAddress.IsLoopback(IP)) { return false; }
bannedPlayers.RemoveAll(bp => bp.ExpirationTime.HasValue && DateTime.Now > bp.ExpirationTime.Value);
var bannedPlayer = bannedPlayers.Find(bp => bp.CompareTo(IP));
reason = bannedPlayer?.Reason;
}
public bool IsBanned(Endpoint endpoint, out string reason)
=> IsBanned(endpoint.Address, out reason);
public bool IsBanned(Address address, out string reason)
{
RemoveExpired();
if (address.IsLocalHost)
{
reason = string.Empty;
return false;
}
var bannedPlayer = bannedPlayers.Find(bp => bp.AddressOrAccountId.TryGet(out Address adr) && address.Equals(adr));
reason = bannedPlayer?.Reason ?? string.Empty;
return bannedPlayer != null;
}
public bool IsBanned(ulong steamID, out string reason)
public bool IsBanned(AccountId accountId, out string reason)
{
reason = string.Empty;
bannedPlayers.RemoveAll(bp => bp.ExpirationTime.HasValue && DateTime.Now > bp.ExpirationTime.Value);
var bannedPlayer = bannedPlayers.Find(bp =>
steamID > 0 &&
(bp.SteamID == steamID || SteamManager.SteamIDStringToUInt64(bp.EndPoint) == steamID));
reason = bannedPlayer?.Reason;
RemoveExpired();
var bannedPlayer = bannedPlayers.Find(bp => bp.AddressOrAccountId.TryGet(out AccountId id) && accountId.Equals(id));
reason = bannedPlayer?.Reason ?? string.Empty;
return bannedPlayer != null;
}
public void BanPlayer(string name, IPAddress ip, string reason, TimeSpan? duration)
public void BanPlayer(string name, Endpoint endpoint, string reason, TimeSpan? duration)
=> BanPlayer(name, endpoint.Address, reason, duration);
public void BanPlayer(string name, Either<Address, AccountId> addressOrAccountId, string reason, TimeSpan? duration)
{
string ipStr = ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4NoThrow().ToString() : ip.ToString();
BanPlayer(name, ipStr, 0, reason, duration);
}
public void BanPlayer(string name, string endPoint, string reason, TimeSpan? duration)
{
BanPlayer(name, endPoint, 0, reason, duration);
}
public void BanPlayer(string name, ulong steamID, string reason, TimeSpan? duration)
{
if (steamID == 0) { return; }
BanPlayer(name, "", steamID, reason, duration);
}
private void BanPlayer(string name, string endPoint, ulong steamID, string reason, TimeSpan? duration)
{
var existingBan = bannedPlayers.Find(bp => bp.EndPoint == endPoint && bp.SteamID == steamID);
var existingBan = bannedPlayers.Find(bp => bp.AddressOrAccountId == addressOrAccountId);
if (existingBan != null)
{
if (!duration.HasValue) return;
if (!duration.HasValue) { return; }
DebugConsole.Log("Set \"" + name + "\"'s ban duration to " + duration.Value);
existingBan.ExpirationTime = DateTime.Now + duration.Value;
@@ -187,8 +120,8 @@ namespace Barotrauma.Networking
System.Diagnostics.Debug.Assert(!name.Contains(','));
string logMsg = "Banned " + name;
if (!string.IsNullOrEmpty(reason)) logMsg += ", reason: " + reason;
if (duration.HasValue) logMsg += ", duration: " + duration.Value.ToString();
if (!string.IsNullOrEmpty(reason)) { logMsg += ", reason: " + reason; }
if (duration.HasValue) { logMsg += ", duration: " + duration.Value.ToString(); }
DebugConsole.Log(logMsg);
@@ -198,46 +131,20 @@ namespace Barotrauma.Networking
expirationTime = DateTime.Now + duration.Value;
}
if (!string.IsNullOrEmpty(endPoint))
{
bannedPlayers.Add(new BannedPlayer(name, endPoint, reason, expirationTime));
}
else if (steamID > 0)
{
bannedPlayers.Add(new BannedPlayer(name, steamID, reason, expirationTime));
}
else
{
DebugConsole.ThrowError("Failed to ban a client (no valid IP or Steam ID given)");
return;
}
bannedPlayers.Add(new BannedPlayer(name, addressOrAccountId, reason, expirationTime));
Save();
}
public void UnbanPlayer(string name)
public void UnbanPlayer(Endpoint endpoint)
=> UnbanPlayer(endpoint.Address);
public void UnbanPlayer(Either<Address, AccountId> addressOrAccountId)
{
name = name.ToLower();
var player = bannedPlayers.Find(bp => bp.Name.ToLower() == name);
var player = bannedPlayers.Find(bp => bp.AddressOrAccountId == addressOrAccountId);
if (player == null)
{
DebugConsole.Log("Could not unban player \"" + name + "\". Matching player not found.");
}
else
{
RemoveBan(player);
}
}
public void UnbanEndPoint(string endPoint)
{
ulong steamId = SteamManager.SteamIDStringToUInt64(endPoint);
var player = bannedPlayers.Find(bp =>
bp.EndPoint == endPoint ||
(steamId != 0 && steamId == SteamManager.SteamIDStringToUInt64(bp.EndPoint)));
if (player == null)
{
DebugConsole.Log("Could not unban endpoint \"" + endPoint + "\". Matching player not found.");
DebugConsole.Log("Could not unban endpoint \"" + addressOrAccountId + "\". Matching player not found.");
}
else
{
@@ -255,22 +162,6 @@ namespace Barotrauma.Networking
Save();
}
private void RangeBan(BannedPlayer banned)
{
banned.EndPoint = ToRange(banned.EndPoint);
BannedPlayer bp;
while ((bp = bannedPlayers.Find(x => banned.CompareTo(x.EndPoint))) != null)
{
//remove all specific bans that are now covered by the rangeban
bannedPlayers.Remove(bp);
}
bannedPlayers.Add(banned);
Save();
}
public void Save()
{
GameServer.Log("Saving banlist", ServerLog.MessageType.ServerMessage);
@@ -283,9 +174,9 @@ namespace Barotrauma.Networking
foreach (BannedPlayer banned in bannedPlayers)
{
string line = banned.Name;
line += "," + ((banned.SteamID > 0) ? SteamManager.SteamIDUInt64ToString(banned.SteamID) : banned.EndPoint);
line += "," + (banned.AddressOrAccountId.ToString());
line += "," + (banned.ExpirationTime.HasValue ? banned.ExpirationTime.Value.ToString() : "");
if (!string.IsNullOrWhiteSpace(banned.Reason)) line += "," + banned.Reason;
if (!string.IsNullOrWhiteSpace(banned.Reason)) { line += "," + banned.Reason; }
lines.Add(line);
}
@@ -324,7 +215,6 @@ namespace Barotrauma.Networking
outMsg.Write(bannedPlayer.Name);
outMsg.Write(bannedPlayer.UniqueIdentifier);
outMsg.Write(bannedPlayer.IsRangeBan);
outMsg.Write(bannedPlayer.ExpirationTime != null);
outMsg.WritePadBits();
if (bannedPlayer.ExpirationTime != null)
@@ -337,12 +227,19 @@ namespace Barotrauma.Networking
if (c.Connection == GameMain.Server.OwnerConnection)
{
outMsg.Write(bannedPlayer.EndPoint);
outMsg.Write(bannedPlayer.SteamID);
if (bannedPlayer.AddressOrAccountId.TryGet(out Address endpoint))
{
outMsg.Write(true); outMsg.WritePadBits();
outMsg.Write(endpoint.StringRepresentation);
}
else
{
outMsg.Write(false); outMsg.WritePadBits();
outMsg.Write(((SteamId)bannedPlayer.AddressOrAccountId).StringRepresentation);
}
}
}
}
catch (Exception e)
{
string errorMsg = "Error while writing banlist. {" + e + "}\n" + e.StackTrace.CleanupStackTrace();
@@ -355,38 +252,25 @@ namespace Barotrauma.Networking
{
if (!c.HasPermission(ClientPermissions.Ban))
{
UInt16 removeCount = incMsg.ReadUInt16();
incMsg.BitPosition += removeCount * 4 * 8;
UInt16 rangeBanCount = incMsg.ReadUInt16();
incMsg.BitPosition += rangeBanCount * 4 * 8;
UInt32 removeCount = incMsg.ReadVariableUInt32();
incMsg.BitPosition += (int)removeCount * 4 * 8;
return false;
}
else
{
UInt16 removeCount = incMsg.ReadUInt16();
UInt32 removeCount = incMsg.ReadVariableUInt32();
for (int i = 0; i < removeCount; i++)
{
UInt16 id = incMsg.ReadUInt16();
UInt32 id = incMsg.ReadUInt32();
BannedPlayer bannedPlayer = bannedPlayers.Find(p => p.UniqueIdentifier == id);
if (bannedPlayer != null)
{
GameServer.Log(GameServer.ClientLogName(c) + " unbanned " + bannedPlayer.Name + " (" + bannedPlayer.EndPoint + ")", ServerLog.MessageType.ConsoleUsage);
GameServer.Log(GameServer.ClientLogName(c) + " unbanned " + bannedPlayer.Name + " (" + bannedPlayer.AddressOrAccountId + ")", ServerLog.MessageType.ConsoleUsage);
RemoveBan(bannedPlayer);
}
}
Int16 rangeBanCount = incMsg.ReadInt16();
for (int i = 0; i < rangeBanCount; i++)
{
UInt16 id = incMsg.ReadUInt16();
BannedPlayer bannedPlayer = bannedPlayers.Find(p => p.UniqueIdentifier == id);
if (bannedPlayer != null)
{
GameServer.Log(GameServer.ClientLogName(c) + " rangebanned " + bannedPlayer.Name + " (" + bannedPlayer.EndPoint + ")", ServerLog.MessageType.ConsoleUsage);
RangeBan(bannedPlayer);
}
}
return removeCount > 0 || rangeBanCount > 0;
return removeCount > 0;
}
}
}
@@ -212,7 +212,7 @@ namespace Barotrauma.Networking
msg.Write(SenderClient != null);
if (SenderClient != null)
{
msg.Write((SenderClient.SteamID != 0) ? SenderClient.SteamID : SenderClient.ID);
msg.Write(SenderClient.AccountId.TryUnwrap(out var accountId) ? accountId.StringRepresentation : SenderClient.SessionId.ToString());
}
msg.Write(Sender != null && c.InGame);
if (Sender != null && c.InGame)
@@ -57,7 +57,7 @@ namespace Barotrauma.Networking
public bool ReadyToStart;
public List<JobVariant> JobPreferences;
public List<JobVariant> JobPreferences { get; set; }
public JobVariant AssignedJob;
public float DeleteDisconnectedTimer;
@@ -111,7 +111,7 @@ namespace Barotrauma.Networking
{
JobPreferences = new List<JobVariant>();
VoipQueue = new VoipQueue(ID, true, true);
VoipQueue = new VoipQueue(SessionId, true, true);
GameMain.Server.VoipServer.RegisterQueue(VoipQueue);
//initialize to infinity, gets set to a proper value when initializing midround syncing
@@ -162,7 +162,7 @@ namespace Barotrauma.Networking
return true;
}
public bool EndpointMatches(string endPoint)
public bool EndpointMatches(Endpoint endPoint)
{
return Connection.EndpointMatches(endPoint);
}
@@ -1,5 +1,4 @@
#define ALLOW_BOT_TRAITORS
using Barotrauma.Extensions;
using Barotrauma.Extensions;
using Barotrauma.IO;
using Barotrauma.Items.Components;
using Barotrauma.Steam;
@@ -85,7 +84,7 @@ namespace Barotrauma.Networking
}
#endif
public override List<Client> ConnectedClients
public override IReadOnlyList<Client> ConnectedClients
{
get
{
@@ -110,10 +109,19 @@ namespace Barotrauma.Networking
public int QueryPort => serverSettings?.QueryPort ?? 0;
public NetworkConnection OwnerConnection { get; private set; }
private readonly int? ownerKey;
private readonly UInt64? ownerSteamId;
private readonly Option<int> ownerKey;
private readonly Option<SteamId> ownerSteamId;
public GameServer(string name, int port, int queryPort = 0, bool isPublic = false, string password = "", bool attemptUPnP = false, int maxPlayers = 10, int? ownKey = null, UInt64? steamId = null)
public GameServer(
string name,
int port,
int queryPort,
bool isPublic,
string password,
bool attemptUPnP,
int maxPlayers,
Option<int> ownerKey,
Option<SteamId> ownerSteamId)
{
name = name.Replace(":", "");
name = name.Replace(";", "");
@@ -132,9 +140,9 @@ namespace Barotrauma.Networking
Voting = new Voting();
ownerKey = ownKey;
this.ownerKey = ownerKey;
ownerSteamId = steamId;
this.ownerSteamId = ownerSteamId;
entityEventManager = new ServerEntityEventManager(this);
@@ -147,15 +155,15 @@ namespace Barotrauma.Networking
try
{
Log("Starting the server...", ServerLog.MessageType.ServerMessage);
if (!ownerSteamId.HasValue || ownerSteamId.Value == 0)
if (ownerSteamId.TryUnwrap(out var steamId))
{
Log("Using Lidgren networking. Manual port forwarding may be required. If players cannot connect to the server, you may want to use the in-game hosting menu (which uses SteamP2P networking and does not require port forwarding).", ServerLog.MessageType.ServerMessage);
serverPeer = new LidgrenServerPeer(ownerKey, serverSettings);
Log("Using SteamP2P networking.", ServerLog.MessageType.ServerMessage);
serverPeer = new SteamP2PServerPeer(steamId, ownerKey.Fallback(0), serverSettings);
}
else
{
Log("Using SteamP2P networking.", ServerLog.MessageType.ServerMessage);
serverPeer = new SteamP2PServerPeer(ownerSteamId.Value, ownerKey.Value, serverSettings);
Log("Using Lidgren networking. Manual port forwarding may be required. If players cannot connect to the server, you may want to use the in-game hosting menu (which uses SteamP2P networking and does not require port forwarding).", ServerLog.MessageType.ServerMessage);
serverPeer = new LidgrenServerPeer(ownerKey, serverSettings);
}
serverPeer.OnInitializationComplete = OnInitializationComplete;
@@ -253,17 +261,15 @@ namespace Barotrauma.Networking
Thread.Sleep(500);
}
private void OnInitializationComplete(NetworkConnection connection)
private void OnInitializationComplete(NetworkConnection connection, string clientName)
{
string clName = connection.Name;
Client newClient = new Client(clName, GetNewClientID());
Client newClient = new Client(clientName, GetNewClientSessionId());
newClient.InitClientSync();
newClient.Connection = connection;
newClient.Connection.Status = NetworkConnectionStatus.Connected;
newClient.SteamID = connection.SteamID;
newClient.OwnerSteamID = connection.OwnerSteamID;
newClient.AccountInfo = connection.AccountInfo;
newClient.Language = connection.Language;
ConnectedClients.Add(newClient);
connectedClients.Add(newClient);
var previousPlayer = previousPlayers.Find(p => p.MatchesClient(newClient));
if (previousPlayer != null)
@@ -299,10 +305,10 @@ namespace Barotrauma.Networking
previousPlayer.Name = newClient.Name;
}
var savedPermissions = serverSettings.ClientPermissions.Find(cp =>
cp.SteamID > 0 ?
cp.SteamID == newClient.SteamID :
newClient.EndpointMatches(cp.EndPoint));
var savedPermissions = serverSettings.ClientPermissions.Find(scp =>
scp.AddressOrAccountId.TryGet(out AccountId accountId)
? newClient.AccountId.ValueEquals(accountId)
: newClient.Connection.Endpoint.Address == scp.AddressOrAccountId);
if (savedPermissions != null)
{
@@ -346,7 +352,7 @@ namespace Barotrauma.Networking
if (OwnerConnection != null && ChildServerRelay.HasShutDown)
{
Disconnect();
Quit();
return;
}
@@ -377,7 +383,7 @@ namespace Barotrauma.Networking
character.KillDisconnectedTimer += deltaTime;
character.SetStun(1.0f);
Client owner = connectedClients.Find(c => (c.Character == null || c.Character == character) && c.EndpointMatches(character.OwnerClientEndPoint));
Client owner = connectedClients.Find(c => (c.Character == null || c.Character == character) && c.EndpointMatches(character.OwnerClientEndpoint));
if ((OwnerConnection == null || owner?.Connection != OwnerConnection) && character.KillDisconnectedTimer > serverSettings.KillDisconnectedTime)
{
@@ -679,7 +685,7 @@ namespace Barotrauma.Networking
pingInf.Write((byte)ConnectedClients.Count);
ConnectedClients.ForEach(c2 =>
{
pingInf.Write(c2.ID);
pingInf.Write(c2.SessionId);
pingInf.Write(c2.Ping);
});
serverPeer.Send(pingInf, c.Connection, DeliveryMethod.Unreliable);
@@ -788,11 +794,11 @@ namespace Barotrauma.Networking
if (serverSettings.VoiceChatEnabled && !connectedClient.Muted)
{
byte id = inc.ReadByte();
if (connectedClient.ID != id)
if (connectedClient.SessionId != id)
{
#if DEBUG
DebugConsole.ThrowError(
"Client \"" + connectedClient.Name + "\" sent a VOIP update that didn't match its ID (" + id.ToString() + "!=" + connectedClient.ID.ToString() + ")");
"Client \"" + connectedClient.Name + "\" sent a VOIP update that didn't match its ID (" + id.ToString() + "!=" + connectedClient.SessionId.ToString() + ")");
#endif
return;
}
@@ -1010,14 +1016,14 @@ namespace Barotrauma.Networking
entityEventManager.CreateEvent(serverSerializable, extraData);
}
private byte GetNewClientID()
private byte GetNewClientSessionId()
{
byte userID = 1;
while (connectedClients.Any(c => c.ID == userID))
byte userId = 1;
while (connectedClients.Any(c => c.SessionId == userId))
{
userID++;
userId++;
}
return userID;
return userId;
}
private void ClientReadLobby(IReadMessage inc)
@@ -1165,6 +1171,12 @@ namespace Barotrauma.Networking
DebugConsole.Log("Finished midround syncing " + c.Name + " - switching from ID " + prevID + " to " + c.LastRecvEntityEventID);
//notify the client of the state of the respawn manager (so they show the respawn prompt if needed)
if (respawnManager != null) { CreateEntityEvent(respawnManager); }
if (GameMain.GameSession?.GameMode is MultiPlayerCampaign campaign)
{
//notify the client of the current bank balance and purchased repairs
campaign.Bank.ForceUpdate();
campaign.IncrementLastUpdateIdForFlag(MultiPlayerCampaign.NetFlags.Misc);
}
}
else
{
@@ -1189,7 +1201,7 @@ namespace Barotrauma.Networking
{
//give midround-joining clients a bit more time to get in sync if they keep receiving messages
int receivedEventCount = lastRecvEntityEventID - c.LastRecvEntityEventID;
if (receivedEventCount < 0) receivedEventCount += ushort.MaxValue;
if (receivedEventCount < 0) { receivedEventCount += ushort.MaxValue; }
c.MidRoundSyncTimeOut += receivedEventCount * 0.01f;
DebugConsole.Log("Midround sync timeout " + c.MidRoundSyncTimeOut.ToString("0.##") + "/" + Timing.TotalTime.ToString("0.##"));
}
@@ -1241,7 +1253,7 @@ namespace Barotrauma.Networking
}
//don't read further messages if the client has been disconnected (kicked due to spam for example)
if (!connectedClients.Contains(c)) break;
if (!connectedClients.Contains(c)) { break; }
}
}
@@ -1341,7 +1353,6 @@ namespace Barotrauma.Networking
case ClientPermissions.Ban:
string bannedName = inc.ReadString().ToLowerInvariant();
string banReason = inc.ReadString();
bool range = inc.ReadBoolean();
double durationSeconds = inc.ReadDouble();
TimeSpan? banDuration = null;
@@ -1351,7 +1362,7 @@ namespace Barotrauma.Networking
if (bannedClient != null)
{
Log("Client \"" + ClientLogName(sender) + "\" banned \"" + ClientLogName(bannedClient) + "\".", ServerLog.MessageType.ServerMessage);
BanClient(bannedClient, string.IsNullOrEmpty(banReason) ? $"ServerMessage.BannedBy~[initiator]={sender.Name}" : banReason, range, banDuration);
BanClient(bannedClient, string.IsNullOrEmpty(banReason) ? $"ServerMessage.BannedBy~[initiator]={sender.Name}" : banReason, banDuration);
}
else
{
@@ -1359,7 +1370,7 @@ namespace Barotrauma.Networking
if (bannedPreviousClient != null)
{
Log("Client \"" + ClientLogName(sender) + "\" banned \"" + bannedPreviousClient.Name + "\".", ServerLog.MessageType.ServerMessage);
BanPreviousPlayer(bannedPreviousClient, string.IsNullOrEmpty(banReason) ? $"ServerMessage.BannedBy~[initiator]={sender.Name}" : banReason, range, banDuration);
BanPreviousPlayer(bannedPreviousClient, string.IsNullOrEmpty(banReason) ? $"ServerMessage.BannedBy~[initiator]={sender.Name}" : banReason, banDuration);
}
else
{
@@ -1368,9 +1379,16 @@ namespace Barotrauma.Networking
}
break;
case ClientPermissions.Unban:
string unbannedName = inc.ReadString();
string unbannedIP = inc.ReadString();
UnbanPlayer(unbannedName, unbannedIP);
bool isPlayerName = inc.ReadBoolean(); inc.ReadPadBits();
string str = inc.ReadString();
if (isPlayerName)
{
UnbanPlayer(playerName: str);
}
else if (Endpoint.Parse(str).TryUnwrap(out var endpoint))
{
UnbanPlayer(endpoint);
}
break;
case ClientPermissions.ManageRound:
bool end = inc.ReadBoolean();
@@ -1506,7 +1524,7 @@ namespace Barotrauma.Networking
break;
case ClientPermissions.ManagePermissions:
byte targetClientID = inc.ReadByte();
Client targetClient = connectedClients.Find(c => c.ID == targetClientID);
Client targetClient = connectedClients.Find(c => c.SessionId == targetClientID);
if (targetClient == null || targetClient == sender || targetClient.Connection == OwnerConnection) { return; }
targetClient.ReadPermissions(inc);
@@ -1592,7 +1610,7 @@ namespace Barotrauma.Networking
DebugConsole.NewMessage("Sending initial lobby update", Color.Gray);
}
outmsg.Write(c.ID);
outmsg.Write(c.SessionId);
var subList = GameMain.NetLobbyScreen.GetSubList();
outmsg.Write((UInt16)subList.Count);
@@ -1811,15 +1829,15 @@ namespace Barotrauma.Networking
{
var tempClientData = new TempClient
{
ID = client.ID,
SteamID = client.SteamID,
NameID = client.NameID,
SessionId = client.SessionId,
AccountInfo = client.AccountInfo,
NameId = client.NameId,
Name = client.Name,
PreferredJob = client.Character?.Info?.Job != null && gameStarted
? client.Character.Info.Job.Prefab.Identifier
: client.PreferredJob,
PreferredTeam = client.PreferredTeam,
CharacterID = client.Character == null || !gameStarted ? (ushort)0 : client.Character.ID,
CharacterId = client.Character == null || !gameStarted ? (ushort)0 : client.Character.ID,
Karma = c.HasPermission(ClientPermissions.ServerLog) ? client.Karma : 100.0f,
Muted = client.Muted,
InGame = client.InGame,
@@ -2382,7 +2400,7 @@ namespace Barotrauma.Networking
mpCampaign.ClearSavedExperiencePoints(teamClients[i]);
}
spawnedCharacter.OwnerClientEndPoint = teamClients[i].Connection.EndPointString;
spawnedCharacter.OwnerClientEndpoint = teamClients[i].Connection.Endpoint;
spawnedCharacter.OwnerClientName = teamClients[i].Name;
}
@@ -2693,9 +2711,15 @@ namespace Barotrauma.Networking
Identifier newJob = inc.ReadIdentifier();
CharacterTeamType newTeam = (CharacterTeamType)inc.ReadByte();
if (c == null || string.IsNullOrEmpty(newName) || !NetIdUtils.IdMoreRecent(nameId, c.NameID)) { return false; }
c.NameID = nameId;
if (c == null || string.IsNullOrEmpty(newName) || !NetIdUtils.IdMoreRecent(nameId, c.NameId)) { return false; }
if (!newJob.IsEmpty)
{
if (!JobPrefab.Prefabs.TryGet(newJob, out JobPrefab newJobPrefab) || newJobPrefab.HiddenJob)
{
newJob = Identifier.Empty;
}
}
c.NameId = nameId;
if (newName == c.Name && newJob == c.PreferredJob && newTeam == c.PreferredTeam) { return false; }
c.PreferredJob = newJob;
c.PreferredTeam = newTeam;
@@ -2716,7 +2740,6 @@ namespace Barotrauma.Networking
{
string oldName = c.Name;
c.Name = newName;
c.Connection.Name = newName;
SendChatMessage($"ServerMessage.NameChangeSuccessful~[oldname]={oldName}~[newname]={newName}", ChatMessageType.Server);
return true;
}
@@ -2797,7 +2820,7 @@ namespace Barotrauma.Networking
DisconnectClient(client, logMsg, msg, reason, PlayerConnectionChangeType.Kicked);
}
public override void BanPlayer(string playerName, string reason, bool range = false, TimeSpan? duration = null)
public override void BanPlayer(string playerName, string reason, TimeSpan? duration = null)
{
Client client = connectedClients.Find(c =>
c.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase) ||
@@ -2809,10 +2832,10 @@ namespace Barotrauma.Networking
return;
}
BanClient(client, reason, range, duration);
BanClient(client, reason, duration);
}
public void BanClient(Client client, string reason, bool range = false, TimeSpan? duration = null)
public void BanClient(Client client, string reason, TimeSpan? duration = null)
{
if (client == null || client.Connection == OwnerConnection) { return; }
@@ -2827,45 +2850,32 @@ namespace Barotrauma.Networking
string targetMsg = DisconnectReason.Banned.ToString();
DisconnectClient(client, $"ServerMessage.BannedFromServer~[client]={client.Name}", targetMsg, reason, PlayerConnectionChangeType.Banned);
if (client.Connection is LidgrenConnection lidgrenConn && (client.SteamID == 0 || range))
serverSettings.BanList.BanPlayer(client.Name, client.Connection.Endpoint, reason, duration);
if (client.AccountInfo.AccountId.TryUnwrap(out var accountId))
{
string ip = "";
ip = lidgrenConn.IPEndPoint.Address.IsIPv4MappedToIPv6 ?
lidgrenConn.IPEndPoint.Address.MapToIPv4NoThrow().ToString() :
lidgrenConn.IPEndPoint.Address.ToString();
if (range) { ip = BanList.ToRange(ip); }
serverSettings.BanList.BanPlayer(client.Name, ip, reason, duration);
serverSettings.BanList.BanPlayer(client.Name, accountId, reason, duration);
}
if (client.SteamID > 0)
foreach (var relatedId in client.AccountInfo.OtherMatchingIds)
{
serverSettings.BanList.BanPlayer(client.Name, client.SteamID, reason, duration);
}
if (client.OwnerSteamID > 0)
{
serverSettings.BanList.BanPlayer(client.Name, client.OwnerSteamID, reason, duration);
serverSettings.BanList.BanPlayer(client.Name, relatedId, reason, duration);
}
}
public void BanPreviousPlayer(PreviousPlayer previousPlayer, string reason, bool range = false, TimeSpan? duration = null)
public void BanPreviousPlayer(PreviousPlayer previousPlayer, string reason, TimeSpan? duration = null)
{
if (previousPlayer == null) { return; }
//reset karma to a neutral value, so if/when the ban is revoked the client wont get immediately punished by low karma again
previousPlayer.Karma = Math.Max(previousPlayer.Karma, 50.0f);
if (!string.IsNullOrEmpty(previousPlayer.EndPoint) && (previousPlayer.SteamID == 0 || range))
serverSettings.BanList.BanPlayer(previousPlayer.Name, previousPlayer.Endpoint, reason, duration);
if (previousPlayer.AccountInfo.AccountId.TryUnwrap(out var accountId))
{
string ip = previousPlayer.EndPoint;
if (range) { ip = BanList.ToRange(ip); }
serverSettings.BanList.BanPlayer(previousPlayer.Name, ip, reason, duration);
serverSettings.BanList.BanPlayer(previousPlayer.Name, accountId, reason, duration);
}
if (previousPlayer.SteamID > 0)
foreach (var relatedId in previousPlayer.AccountInfo.OtherMatchingIds)
{
serverSettings.BanList.BanPlayer(previousPlayer.Name, previousPlayer.SteamID, reason, duration);
}
if (previousPlayer.OwnerSteamID > 0)
{
serverSettings.BanList.BanPlayer(previousPlayer.Name, previousPlayer.OwnerSteamID, reason, duration);
serverSettings.BanList.BanPlayer(previousPlayer.Name, relatedId, reason, duration);
}
string msg = $"ServerMessage.BannedFromServer~[client]={previousPlayer.Name}";
@@ -2876,16 +2886,17 @@ namespace Barotrauma.Networking
SendChatMessage(msg, ChatMessageType.Server, changeType: PlayerConnectionChangeType.Banned);
}
public override void UnbanPlayer(string playerName, string playerEndPoint)
public override void UnbanPlayer(string playerName)
{
if (!string.IsNullOrEmpty(playerEndPoint))
{
serverSettings.BanList.UnbanEndPoint(playerEndPoint);
}
else if (!string.IsNullOrEmpty(playerName))
{
serverSettings.BanList.UnbanPlayer(playerName);
}
BannedPlayer bannedPlayer
= serverSettings.BanList.BannedPlayers.FirstOrDefault(bp => bp.Name == playerName);
if (bannedPlayer is null) { return; }
serverSettings.BanList.UnbanPlayer(bannedPlayer.AddressOrAccountId);
}
public override void UnbanPlayer(Endpoint endpoint)
{
serverSettings.BanList.UnbanPlayer(endpoint);
}
public void DisconnectClient(NetworkConnection senderConnection, string msg = "", string targetmsg = "")
@@ -2906,7 +2917,7 @@ namespace Barotrauma.Networking
{
if (client == null) return;
if (gameStarted && client.Character != null)
if (client.Character != null)
{
client.Character.ClientDisconnected = true;
client.Character.ClearInputs();
@@ -2925,7 +2936,7 @@ namespace Barotrauma.Networking
targetmsg += $"/\n/ServerMessage.Reason/: /{reason}";
}
if (client.SteamID != 0) { SteamManager.StopAuthSession(client.SteamID); }
if (client.AccountId is Some<AccountId> { Value: SteamId steamId }) { SteamManager.StopAuthSession(steamId); }
var previousPlayer = previousPlayers.Find(p => p.MatchesClient(client));
if (previousPlayer == null)
@@ -3363,26 +3374,26 @@ namespace Barotrauma.Networking
public void UpdateClientPermissions(Client client)
{
if (client.SteamID > 0)
if (client.AccountId.TryUnwrap(out var accountId))
{
serverSettings.ClientPermissions.RemoveAll(cp => cp.SteamID == client.SteamID);
serverSettings.ClientPermissions.RemoveAll(scp => scp.AddressOrAccountId == accountId);
if (client.Permissions != ClientPermissions.None)
{
serverSettings.ClientPermissions.Add(new ServerSettings.SavedClientPermission(
client.Name,
client.SteamID,
accountId,
client.Permissions,
client.PermittedConsoleCommands));
}
}
else
{
serverSettings.ClientPermissions.RemoveAll(cp => client.EndpointMatches(cp.EndPoint));
serverSettings.ClientPermissions.RemoveAll(scp => client.Connection.Endpoint.Address == scp.AddressOrAccountId);
if (client.Permissions != ClientPermissions.None)
{
serverSettings.ClientPermissions.Add(new ServerSettings.SavedClientPermission(
client.Name,
client.Connection.EndPointString,
client.Connection.Endpoint.Address,
client.Permissions,
client.PermittedConsoleCommands));
}
@@ -3504,7 +3515,7 @@ namespace Barotrauma.Networking
if (client.Character != null)
{
client.Character.IsRemotePlayer = false;
client.Character.OwnerClientEndPoint = null;
client.Character.OwnerClientEndpoint = null;
client.Character.OwnerClientName = null;
}
@@ -3531,7 +3542,7 @@ namespace Barotrauma.Networking
newCharacter.Info.Character = newCharacter;
}
newCharacter.OwnerClientEndPoint = client.Connection.EndPointString;
newCharacter.OwnerClientEndpoint = client.Connection.Endpoint;
newCharacter.OwnerClientName = client.Name;
newCharacter.IsRemotePlayer = true;
newCharacter.Enabled = true;
@@ -3920,17 +3931,7 @@ namespace Barotrauma.Networking
}
}
public Tuple<ulong, string> FindPreviousClientData(Client client)
{
var player = previousPlayers.Find(p => p.MatchesClient(client));
if (player != null)
{
return Tuple.Create(player.SteamID, player.EndPoint);
}
return null;
}
public override void Disconnect()
public override void Quit()
{
if (started)
{
@@ -3959,12 +3960,11 @@ namespace Barotrauma.Networking
}
}
partial class PreviousPlayer
class PreviousPlayer
{
public string Name;
public string EndPoint;
public UInt64 SteamID;
public UInt64 OwnerSteamID;
public Endpoint Endpoint;
public AccountInfo AccountInfo;
public float Karma;
public int KarmaKickCount;
public readonly List<Client> KickVoters = new List<Client>();
@@ -3972,15 +3972,14 @@ namespace Barotrauma.Networking
public PreviousPlayer(Client c)
{
Name = c.Name;
EndPoint = c.Connection?.EndPointString ?? "";
SteamID = c.SteamID;
OwnerSteamID = c.OwnerSteamID;
Endpoint = c.Connection.Endpoint;
AccountInfo = c.AccountInfo;
}
public bool MatchesClient(Client c)
{
if (c.SteamID > 0 && SteamID > 0) { return c.SteamID == SteamID; }
return c.EndpointMatches(EndPoint);
if (c.AccountInfo.AccountId.IsSome() && AccountInfo.AccountId.IsSome()) { return c.AccountInfo.AccountId == AccountInfo.AccountId; }
return c.EndpointMatches(Endpoint);
}
}
}
@@ -1,4 +1,5 @@
using System;
using Barotrauma.Steam;
using System;
namespace Barotrauma.Networking
{
@@ -13,7 +14,7 @@ namespace Barotrauma.Networking
msg.Write(SenderClient != null);
if (SenderClient != null)
{
msg.Write((SenderClient.SteamID != 0) ? SenderClient.SteamID : SenderClient.ID);
msg.Write(SenderClient.AccountId.TryUnwrap(out var accountId) ? accountId.StringRepresentation : SenderClient.SessionId.ToString());
}
msg.Write(Sender != null && c.InGame);
if (Sender != null && c.InGame)
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Net;
using System.Linq;
using Barotrauma.Steam;
using Lidgren.Network;
namespace Barotrauma.Networking
@@ -13,7 +14,7 @@ namespace Barotrauma.Networking
private readonly List<NetIncomingMessage> incomingLidgrenMessages;
public LidgrenServerPeer(int? ownKey, ServerSettings settings)
public LidgrenServerPeer(Option<int> ownKey, ServerSettings settings)
{
serverSettings = settings;
@@ -184,7 +185,7 @@ namespace Barotrauma.Networking
return;
}
if (serverSettings.BanList.IsBanned(inc.SenderConnection.RemoteEndPoint.Address, 0, 0, out string banReason))
if (serverSettings.BanList.IsBanned(new LidgrenEndpoint(inc.SenderConnection.RemoteEndPoint), out string banReason))
{
//IP banned: deny immediately
inc.SenderConnection.Deny(DisconnectReason.Banned.ToString() + "/ " + banReason);
@@ -195,7 +196,7 @@ namespace Barotrauma.Networking
if (pendingClient == null)
{
pendingClient = new PendingClient(new LidgrenConnection("PENDING", inc.SenderConnection, 0));
pendingClient = new PendingClient(new LidgrenConnection(inc.SenderConnection));
pendingClients.Add(pendingClient);
}
@@ -206,7 +207,7 @@ namespace Barotrauma.Networking
{
if (netServer == null) { return; }
PendingClient pendingClient = pendingClients.Find(c => (c.Connection is LidgrenConnection l) && l.NetConnection == inc.SenderConnection);
PendingClient pendingClient = pendingClients.Find(c => c.Connection is LidgrenConnection l && l.NetConnection == inc.SenderConnection);
PacketHeader packetHeader = (PacketHeader)inc.ReadByte();
@@ -231,7 +232,9 @@ namespace Barotrauma.Networking
return;
}
if (pendingClient != null) { pendingClients.Remove(pendingClient); }
if (serverSettings.BanList.IsBanned(conn.IPEndPoint.Address, conn.SteamID, conn.OwnerSteamID, out string banReason))
if (serverSettings.BanList.IsBanned(conn.Endpoint, out string banReason)
|| (conn.AccountInfo.AccountId.TryUnwrap(out var accountId) && serverSettings.BanList.IsBanned(accountId, out banReason))
|| conn.AccountInfo.OtherMatchingIds.Any(id => serverSettings.BanList.IsBanned(id, out banReason)))
{
Disconnect(conn, DisconnectReason.Banned.ToString() + "/ " + banReason);
return;
@@ -264,7 +267,7 @@ namespace Barotrauma.Networking
}
else
{
disconnectMsg = $"ServerMessage.HasDisconnected~[client]={conn.Name}";
disconnectMsg = $"ServerMessage.HasDisconnected~[client]={GameMain.Server.ConnectedClients.First(c => c.Connection == conn).Name}";
Disconnect(conn, disconnectMsg);
}
}
@@ -285,18 +288,18 @@ namespace Barotrauma.Networking
Steamworks.SteamServer.OnValidateAuthTicketResponse += OnAuthChange;
}
private void OnAuthChange(Steamworks.SteamId steamID, Steamworks.SteamId ownerID, Steamworks.AuthResponse status)
private void OnAuthChange(Steamworks.SteamId steamId, Steamworks.SteamId ownerId, Steamworks.AuthResponse status)
{
if (netServer == null) { return; }
PendingClient pendingClient = pendingClients.Find(c => c.SteamID == steamID);
DebugConsole.Log(steamID + " validation: " + status+", "+(pendingClient!=null));
PendingClient pendingClient = pendingClients.Find(c => c.AccountInfo.AccountId is Some<AccountId> { Value: SteamId id } && id.Value == steamId);
DebugConsole.Log(steamId + " validation: " + status+", "+(pendingClient!=null));
if (pendingClient == null)
{
if (status != Steamworks.AuthResponse.OK)
{
LidgrenConnection connection = connectedClients.Find(c => c.SteamID == steamID) as LidgrenConnection;
LidgrenConnection connection = connectedClients.Find(c => c.AccountInfo.AccountId is Some<AccountId> { Value: SteamId id } && id.Value == steamId) as LidgrenConnection;
if (connection != null)
{
Disconnect(connection, DisconnectReason.SteamAuthenticationFailed.ToString() + "/ Steam authentication status changed: " + status.ToString());
@@ -307,7 +310,9 @@ namespace Barotrauma.Networking
LidgrenConnection pendingConnection = pendingClient.Connection as LidgrenConnection;
string banReason;
if (serverSettings.BanList.IsBanned(pendingConnection.NetConnection.RemoteEndPoint.Address, steamID, ownerID, out banReason))
if (serverSettings.BanList.IsBanned(pendingConnection.Endpoint, out banReason)
|| serverSettings.BanList.IsBanned(new SteamId(steamId), out banReason)
|| serverSettings.BanList.IsBanned(new SteamId(ownerId), out banReason))
{
RemovePendingClient(pendingClient, DisconnectReason.Banned, banReason);
return;
@@ -315,7 +320,7 @@ namespace Barotrauma.Networking
if (status == Steamworks.AuthResponse.OK)
{
pendingClient.OwnerSteamID = ownerID;
pendingClient.Connection.SetAccountInfo(new AccountInfo(new SteamId(steamId), new SteamId(ownerId)));
pendingClient.InitializationStep = serverSettings.HasPassword ? ConnectionInitialization.Password : ConnectionInitialization.ContentPackageOrder;
pendingClient.UpdateTime = Timing.TotalTime;
}
@@ -333,7 +338,7 @@ namespace Barotrauma.Networking
if (!(conn is LidgrenConnection lidgrenConn)) return;
if (!connectedClients.Contains(lidgrenConn))
{
DebugConsole.ThrowError("Tried to send message to unauthenticated connection: " + lidgrenConn.IPString);
DebugConsole.ThrowError("Tried to send message to unauthenticated connection: " + lidgrenConn.Endpoint.StringRepresentation);
return;
}
@@ -368,7 +373,7 @@ namespace Barotrauma.Networking
NetSendResult result = netServer.SendMessage(lidgrenMsg, lidgrenConn.NetConnection, lidgrenDeliveryMethod);
if (result != NetSendResult.Sent && result != NetSendResult.Queued)
{
DebugConsole.NewMessage("Failed to send message to "+conn.Name+": " + result.ToString(), Microsoft.Xna.Framework.Color.Yellow);
DebugConsole.NewMessage("Failed to send message to "+conn.Endpoint.StringRepresentation+": " + result.ToString(), Microsoft.Xna.Framework.Color.Yellow);
}
}
@@ -382,7 +387,7 @@ namespace Barotrauma.Networking
lidgrenConn.Status = NetworkConnectionStatus.Disconnected;
connectedClients.Remove(lidgrenConn);
OnDisconnect?.Invoke(conn, msg);
Steam.SteamManager.StopAuthSession(conn.SteamID);
if (conn.AccountInfo.AccountId is Some<AccountId> { Value: SteamId steamId }) { Steam.SteamManager.StopAuthSession(steamId); }
}
lidgrenConn.NetConnection.Disconnect(msg ?? "Disconnected");
}
@@ -409,25 +414,25 @@ namespace Barotrauma.Networking
NetSendResult result = netServer.SendMessage(lidgrenMsg, lidgrenConn.NetConnection, lidgrenDeliveryMethod);
if (result != NetSendResult.Sent && result != NetSendResult.Queued)
{
DebugConsole.NewMessage("Failed to send message to " + conn.Name + ": " + result.ToString(), Microsoft.Xna.Framework.Color.Yellow);
DebugConsole.NewMessage("Failed to send message to " + conn.Endpoint.StringRepresentation + ": " + result.ToString(), Microsoft.Xna.Framework.Color.Yellow);
}
}
protected override void CheckOwnership(PendingClient pendingClient)
{
LidgrenConnection l = pendingClient.Connection as LidgrenConnection;
if (OwnerConnection == null &&
IPAddress.IsLoopback(l.NetConnection.RemoteEndPoint.Address.MapToIPv4NoThrow()) &&
ownerKey != null && pendingClient.OwnerKey != 0 && pendingClient.OwnerKey == ownerKey)
if (OwnerConnection == null
&& pendingClient.Connection is LidgrenConnection l
&& IPAddress.IsLoopback(l.NetConnection.RemoteEndPoint.Address)
&& ownerKey.IsSome() && pendingClient.OwnerKey == ownerKey)
{
ownerKey = null;
ownerKey = Option<int>.None();
OwnerConnection = pendingClient.Connection;
}
}
protected override void ProcessAuthTicket(string name, int ownKey, ulong steamId, PendingClient pendingClient, byte[] ticket)
protected override void ProcessAuthTicket(string name, Option<int> ownKey, Option<SteamId> steamId, PendingClient pendingClient, byte[] ticket)
{
if (pendingClient.SteamID == null)
if (pendingClient.AccountInfo.AccountId.IsNone())
{
bool requireSteamAuth = GameSettings.CurrentConfig.RequireSteamAuthentication;
#if DEBUG
@@ -436,32 +441,42 @@ namespace Barotrauma.Networking
//steam auth cannot be done (SteamManager not initialized or no ticket given),
//but it's not required either -> let the client join without auth
if ((!Steam.SteamManager.IsInitialized || (ticket?.Length ?? 0) == 0) &&
!requireSteamAuth)
if ((!SteamManager.IsInitialized || (ticket?.Length ?? 0) == 0)
&& !requireSteamAuth)
{
pendingClient.Connection.Name = name;
pendingClient.Name = name;
pendingClient.OwnerKey = ownKey;
pendingClient.InitializationStep = serverSettings.HasPassword ? ConnectionInitialization.Password : ConnectionInitialization.ContentPackageOrder;
}
else
{
Steamworks.BeginAuthResult authSessionStartState = Steam.SteamManager.StartAuthSession(ticket, steamId);
if (authSessionStartState != Steamworks.BeginAuthResult.OK)
if (!steamId.TryUnwrap(out var id))
{
if (requireSteamAuth)
{
RemovePendingClient(pendingClient, DisconnectReason.SteamAuthenticationFailed, "Steam auth session failed to start: " + authSessionStartState.ToString());
RemovePendingClient(pendingClient, DisconnectReason.SteamAuthenticationFailed, "Steam auth session failed to start: Steam ID not provided");
return;
}
else
}
else
{
Steamworks.BeginAuthResult authSessionStartState = Steam.SteamManager.StartAuthSession(ticket, id);
if (authSessionStartState != Steamworks.BeginAuthResult.OK)
{
steamId = 0;
pendingClient.InitializationStep = serverSettings.HasPassword ? ConnectionInitialization.Password : ConnectionInitialization.ContentPackageOrder;
if (requireSteamAuth)
{
RemovePendingClient(pendingClient, DisconnectReason.SteamAuthenticationFailed, "Steam auth session failed to start: " + authSessionStartState.ToString());
return;
}
else
{
steamId = Option<SteamId>.None();
pendingClient.InitializationStep = serverSettings.HasPassword ? ConnectionInitialization.Password : ConnectionInitialization.ContentPackageOrder;
}
}
}
pendingClient.SteamID = steamId;
pendingClient.Connection.Name = name;
pendingClient.Connection.SetAccountInfo(new AccountInfo(steamId.Select(uid => (AccountId)uid)));
pendingClient.Name = name;
pendingClient.OwnerKey = ownKey;
pendingClient.AuthSessionStarted = true;
@@ -469,7 +484,7 @@ namespace Barotrauma.Networking
}
else
{
if (pendingClient.SteamID != steamId)
if (pendingClient.AccountInfo.AccountId != steamId.Select(uid => (AccountId)uid))
{
RemovePendingClient(pendingClient, DisconnectReason.SteamAuthenticationFailed, "SteamID mismatch");
return;
@@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Barotrauma.Extensions;
namespace Barotrauma.Networking
{
@@ -10,7 +9,7 @@ namespace Barotrauma.Networking
{
public delegate void MessageCallback(NetworkConnection connection, IReadMessage message);
public delegate void DisconnectCallback(NetworkConnection connection, string reason);
public delegate void InitializationCompleteCallback(NetworkConnection connection);
public delegate void InitializationCompleteCallback(NetworkConnection connection, string clientName);
public delegate void ShutdownCallback();
public delegate void OwnerDeterminedCallback(NetworkConnection connection);
@@ -20,7 +19,7 @@ namespace Barotrauma.Networking
public ShutdownCallback OnShutdown;
public OwnerDeterminedCallback OnOwnerDetermined;
protected int? ownerKey;
protected Option<int> ownerKey;
public NetworkConnection OwnerConnection { get; protected set; }
@@ -33,43 +32,23 @@ namespace Barotrauma.Networking
protected class PendingClient
{
public string Name;
public int OwnerKey;
public Option<int> OwnerKey;
public NetworkConnection Connection;
public ConnectionInitialization InitializationStep;
public double UpdateTime;
public double TimeOut;
public int Retries;
private UInt64? steamId;
public UInt64? SteamID
{
get { return steamId; }
set
{
steamId = value;
Connection.SetSteamIDIfUnknown(value ?? 0);
}
}
private UInt64? ownerSteamId;
public UInt64? OwnerSteamID
{
get { return ownerSteamId; }
set
{
ownerSteamId = value;
Connection.SetOwnerSteamIDIfUnknown(value ?? 0);
}
}
public Int32? PasswordSalt;
public bool AuthSessionStarted;
public AccountInfo AccountInfo => Connection.AccountInfo;
public PendingClient(NetworkConnection conn)
{
OwnerKey = 0;
OwnerKey = Option<int>.None();
Connection = conn;
InitializationStep = ConnectionInitialization.SteamTicketAndVersion;
Retries = 0;
SteamID = null;
OwnerSteamID = null;
PasswordSalt = null;
UpdateTime = Timing.TotalTime + Timing.Step * 3.0;
TimeOut = NetworkConnection.TimeoutThreshold;
@@ -101,7 +80,10 @@ namespace Barotrauma.Networking
case ConnectionInitialization.SteamTicketAndVersion:
string name = Client.SanitizeName(inc.ReadString());
int ownerKey = inc.ReadInt32();
UInt64 steamId = inc.ReadUInt64();
UInt64 steamIdVal = inc.ReadUInt64();
Option<SteamId> steamId = steamIdVal != 0
? Option<SteamId>.Some(new SteamId(steamIdVal))
: Option<SteamId>.None();
UInt16 ticketLength = inc.ReadUInt16();
byte[] ticketBytes = inc.ReadBytes(ticketLength);
@@ -136,7 +118,7 @@ namespace Barotrauma.Networking
if (!pendingClient.AuthSessionStarted)
{
ProcessAuthTicket(name, ownerKey, steamId, pendingClient, ticketBytes);
ProcessAuthTicket(name, ownerKey != 0 ? Option<int>.Some(ownerKey) : Option<int>.None(), steamId, pendingClient, ticketBytes);
}
break;
case ConnectionInitialization.Password:
@@ -172,34 +154,37 @@ namespace Barotrauma.Networking
}
}
protected abstract void ProcessAuthTicket(string name, int ownKey, ulong steamId, PendingClient pendingClient, byte[] ticket);
protected abstract void ProcessAuthTicket(string name, Option<int> ownKey, Option<SteamId> steamId, PendingClient pendingClient, byte[] ticket);
protected void BanPendingClient(PendingClient pendingClient, string banReason, TimeSpan? duration)
{
if (pendingClient.Connection is LidgrenConnection l)
void banAccountId(AccountId accountId)
{
serverSettings.BanList.BanPlayer(pendingClient.Name, l.NetConnection.RemoteEndPoint.Address, banReason, duration);
}
else if (pendingClient.Connection is SteamP2PConnection s)
{
serverSettings.BanList.BanPlayer(pendingClient.Name, s.SteamID, banReason, duration);
serverSettings.BanList.BanPlayer(pendingClient.Name, s.OwnerSteamID, banReason, duration);
serverSettings.BanList.BanPlayer(pendingClient.Name, accountId, banReason, duration);
}
if (pendingClient.AccountInfo.AccountId.TryUnwrap(out var id)) { banAccountId(id); }
pendingClient.AccountInfo.OtherMatchingIds.ForEach(banAccountId);
serverSettings.BanList.BanPlayer(pendingClient.Name, pendingClient.Connection.Endpoint, banReason, duration);
}
protected bool IsPendingClientBanned(PendingClient pendingClient, out string banReason)
{
if (pendingClient.Connection is LidgrenConnection l)
bool isAccountIdBanned(AccountId accountId, out string banReason)
{
return serverSettings.BanList.IsBanned(l.NetConnection.RemoteEndPoint.Address, out banReason);
banReason = default;
return serverSettings.BanList.IsBanned(accountId, out banReason);
}
else if (pendingClient.Connection is SteamP2PConnection s)
banReason = default;
bool isBanned = pendingClient.AccountInfo.AccountId.TryUnwrap(out var id)
&& isAccountIdBanned(id, out banReason);
foreach (var otherId in pendingClient.AccountInfo.OtherMatchingIds)
{
return serverSettings.BanList.IsBanned(s.SteamID, out banReason) ||
serverSettings.BanList.IsBanned(s.OwnerSteamID, out banReason);
if (isBanned) { break; }
isBanned |= isAccountIdBanned(otherId, out banReason);
}
banReason = null;
return false;
return isBanned;
}
protected abstract void SendMsgInternal(NetworkConnection conn, DeliveryMethod deliveryMethod, IWriteMessage msg);
@@ -225,7 +210,7 @@ namespace Barotrauma.Networking
CheckOwnership(pendingClient);
OnInitializationComplete?.Invoke(newConnection);
OnInitializationComplete?.Invoke(newConnection, pendingClient.Name);
}
pendingClient.TimeOut -= Timing.Step;
@@ -244,8 +229,6 @@ namespace Barotrauma.Networking
switch (pendingClient.InitializationStep)
{
case ConnectionInitialization.ContentPackageOrder:
outMsg.Write(GameMain.Server.ServerName);
var mpContentPackages = ContentPackageManager.EnabledPackages.All.Where(cp => cp.HasMultiplayerSyncedContent).ToList();
outMsg.WriteVariableUInt32((UInt32)mpContentPackages.Count);
for (int i = 0; i < mpContentPackages.Count; i++)
@@ -286,11 +269,10 @@ namespace Barotrauma.Networking
pendingClients.Remove(pendingClient);
if (pendingClient.AuthSessionStarted)
if (pendingClient.AuthSessionStarted && pendingClient.AccountInfo.AccountId is Some<AccountId> { Value: SteamId steamId })
{
Steam.SteamManager.StopAuthSession(pendingClient.SteamID.Value);
pendingClient.SteamID = null;
pendingClient.OwnerSteamID = null;
Steam.SteamManager.StopAuthSession(steamId);
pendingClient.Connection.SetAccountInfo(AccountInfo.None);
pendingClient.AuthSessionStarted = false;
}
}
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Threading;
namespace Barotrauma.Networking
{
@@ -10,29 +8,25 @@ namespace Barotrauma.Networking
{
private bool started;
public UInt64 OwnerSteamID
{
get;
private set;
}
private readonly SteamId ownerSteamId;
private UInt64 ownerKey64 => unchecked((UInt64)ownerKey.Value);
private UInt64 ownerKey64 => unchecked((UInt64)ownerKey.Fallback(0));
private UInt64 ReadSteamId(IReadMessage inc)
=> inc.ReadUInt64() ^ ownerKey64;
private void WriteSteamId(IWriteMessage msg, UInt64 val)
=> msg.Write(val ^ ownerKey64);
private SteamId ReadSteamId(IReadMessage inc)
=> new SteamId(inc.ReadUInt64() ^ ownerKey64);
private void WriteSteamId(IWriteMessage msg, SteamId val)
=> msg.Write(val.Value ^ ownerKey64);
public SteamP2PServerPeer(UInt64 steamId, int ownerKey, ServerSettings settings)
public SteamP2PServerPeer(SteamId steamId, int ownerKey, ServerSettings settings)
{
serverSettings = settings;
connectedClients = new List<NetworkConnection>();
pendingClients = new List<PendingClient>();
this.ownerKey = ownerKey;
this.ownerKey = Option<int>.Some(ownerKey);
OwnerSteamID = steamId;
ownerSteamId = steamId;
started = false;
}
@@ -40,7 +34,7 @@ namespace Barotrauma.Networking
public override void Start()
{
IWriteMessage outMsg = new WriteOnlyMessage();
WriteSteamId(outMsg, OwnerSteamID);
WriteSteamId(outMsg, ownerSteamId);
outMsg.Write((byte)DeliveryMethod.Reliable);
outMsg.Write((byte)(PacketHeader.IsConnectionInitializationStep | PacketHeader.IsServerMessage));
@@ -129,9 +123,9 @@ namespace Barotrauma.Networking
{
if (!started) { return; }
UInt64 senderSteamId = ReadSteamId(inc);
UInt64 ownerSteamId = ReadSteamId(inc);
SteamId senderSteamId = ReadSteamId(inc);
SteamId ownerSteamId = ReadSteamId(inc);
PacketHeader packetHeader = (PacketHeader)inc.ReadByte();
if (packetHeader.IsServerMessage())
@@ -140,11 +134,14 @@ namespace Barotrauma.Networking
return;
}
if (senderSteamId != OwnerSteamID) //sender is remote, handle disconnects and heartbeats
if (senderSteamId != this.ownerSteamId) //sender is remote, handle disconnects and heartbeats
{
PendingClient pendingClient = pendingClients.Find(c => c.SteamID == senderSteamId);
SteamP2PConnection connectedClient = connectedClients.Find(c => c.SteamID == senderSteamId) as SteamP2PConnection;
bool connectionMatches(NetworkConnection conn)
=> conn is SteamP2PConnection { Endpoint: SteamP2PEndpoint { SteamId: var steamId } }
&& steamId == senderSteamId;
PendingClient pendingClient = pendingClients.Find(c => connectionMatches(c.Connection));
SteamP2PConnection connectedClient = connectedClients.Find(connectionMatches) as SteamP2PConnection;
pendingClient?.Heartbeat();
connectedClient?.Heartbeat();
@@ -171,7 +168,7 @@ namespace Barotrauma.Networking
}
else if (connectedClient != null)
{
string disconnectMsg = $"ServerMessage.HasDisconnected~[client]={connectedClient.Name}";
string disconnectMsg = $"ServerMessage.HasDisconnected~[client]={GameMain.Server.ConnectedClients.First(c => c.Connection == connectedClient).Name}";
Disconnect(connectedClient, disconnectMsg, false);
}
return;
@@ -183,13 +180,9 @@ namespace Barotrauma.Networking
}
else if (packetHeader.IsConnectionInitializationStep())
{
if (pendingClient != null)
{
if (ownerSteamId != 0)
{
pendingClient.Connection.SetOwnerSteamIDIfUnknown(ownerSteamId);
}
pendingClient.Connection.SetAccountInfo(new AccountInfo(senderSteamId, ownerSteamId));
ReadConnectionInitializationStep(pendingClient, new ReadOnlyMessage(inc.Buffer, false, inc.BytePosition, inc.LengthBytes - inc.BytePosition, null));
}
else
@@ -197,7 +190,7 @@ namespace Barotrauma.Networking
ConnectionInitialization initializationStep = (ConnectionInitialization)inc.ReadByte();
if (initializationStep == ConnectionInitialization.ConnectionStarted)
{
pendingClients.Add(new PendingClient(new SteamP2PConnection("PENDING", senderSteamId)) { SteamID = senderSteamId });
pendingClients.Add(new PendingClient(new SteamP2PConnection(senderSteamId)));
}
}
}
@@ -228,13 +221,13 @@ namespace Barotrauma.Networking
if (OwnerConnection == null)
{
string ownerName = inc.ReadString();
OwnerConnection = new SteamP2PConnection(ownerName, OwnerSteamID)
OwnerConnection = new SteamP2PConnection(this.ownerSteamId)
{
Language = GameSettings.CurrentConfig.Language
};
OwnerConnection.SetOwnerSteamIDIfUnknown(OwnerSteamID);
OwnerConnection.SetAccountInfo(new AccountInfo(this.ownerSteamId, this.ownerSteamId));
OnInitializationComplete?.Invoke(OwnerConnection);
OnInitializationComplete?.Invoke(OwnerConnection, ownerName);
}
return;
}
@@ -261,17 +254,19 @@ namespace Barotrauma.Networking
{
if (!started) { return; }
if (!(conn is SteamP2PConnection steamp2pConn)) return;
if (!(conn is SteamP2PConnection steamp2pConn)) { return; }
if (!connectedClients.Contains(steamp2pConn) && conn != OwnerConnection)
{
DebugConsole.ThrowError("Tried to send message to unauthenticated connection: " + steamp2pConn.SteamID.ToString());
DebugConsole.ThrowError("Tried to send message to unauthenticated connection: " + steamp2pConn.AccountInfo.AccountId.ToString());
return;
}
if (!conn.AccountInfo.AccountId.TryUnwrap(out var connAccountId) || !(connAccountId is SteamId connSteamId)) { return; }
IWriteMessage msgToSend = new WriteOnlyMessage();
byte[] msgData = new byte[16];
msg.PrepareForSending(ref msgData, compressPastThreshold, out bool isCompressed, out int length);
WriteSteamId(msgToSend, conn.SteamID);
WriteSteamId(msgToSend, connSteamId);
msgToSend.Write((byte)deliveryMethod);
msgToSend.Write((byte)((isCompressed ? PacketHeader.IsCompressed : PacketHeader.None) | PacketHeader.IsServerMessage));
msgToSend.Write((UInt16)length);
@@ -282,7 +277,7 @@ namespace Barotrauma.Networking
ChildServerRelay.Write(bufToSend);
}
private void SendDisconnectMessage(UInt64 steamId, string msg)
private void SendDisconnectMessage(SteamId steamId, string msg)
{
if (!started) { return; }
if (string.IsNullOrWhiteSpace(msg)) { return; }
@@ -303,13 +298,16 @@ namespace Barotrauma.Networking
if (!started) { return; }
if (!(conn is SteamP2PConnection steamp2pConn)) { return; }
if (sendDisconnectMessage) { SendDisconnectMessage(steamp2pConn.SteamID, msg); }
if (!conn.AccountInfo.AccountId.TryUnwrap(out var connAccountId) || !(connAccountId is SteamId connSteamId)) { return; }
if (sendDisconnectMessage) { SendDisconnectMessage(connSteamId, msg); }
if (connectedClients.Contains(steamp2pConn))
{
steamp2pConn.Status = NetworkConnectionStatus.Disconnected;
connectedClients.Remove(steamp2pConn);
OnDisconnect?.Invoke(conn, msg);
Steam.SteamManager.StopAuthSession(conn.SteamID);
Steam.SteamManager.StopAuthSession(connSteamId);
}
else if (steamp2pConn == OwnerConnection)
{
@@ -324,8 +322,12 @@ namespace Barotrauma.Networking
protected override void SendMsgInternal(NetworkConnection conn, DeliveryMethod deliveryMethod, IWriteMessage msg)
{
var connSteamId = conn is SteamP2PConnection { Endpoint: SteamP2PEndpoint { SteamId: var id } }
? id : null;
if (connSteamId is null) { return; }
IWriteMessage msgToSend = new WriteOnlyMessage();
WriteSteamId(msgToSend, conn.SteamID);
WriteSteamId(msgToSend, connSteamId);
msgToSend.Write((byte)deliveryMethod);
msgToSend.Write(msg.Buffer, 0, msg.LengthBytes);
byte[] bufToSend = (byte[])msgToSend.Buffer.Clone();
@@ -333,11 +335,10 @@ namespace Barotrauma.Networking
ChildServerRelay.Write(bufToSend);
}
protected override void ProcessAuthTicket(string name, int ownKey, ulong steamId, PendingClient pendingClient, byte[] ticket)
protected override void ProcessAuthTicket(string name, Option<int> ownKey, Option<SteamId> steamId, PendingClient pendingClient, byte[] ticket)
{
pendingClient.InitializationStep = serverSettings.HasPassword ? ConnectionInitialization.Password : ConnectionInitialization.ContentPackageOrder;
pendingClient.Connection.Name = name;
pendingClient.Name = name;
pendingClient.AuthSessionStarted = true;
}
@@ -444,26 +444,28 @@ namespace Barotrauma.Networking
}
clients[i].Character = character;
character.OwnerClientEndPoint = clients[i].Connection.EndPointString;
character.OwnerClientEndpoint = clients[i].Connection.Endpoint;
character.OwnerClientName = clients[i].Name;
GameServer.Log(string.Format("Respawning {0} ({1}) as {2}", GameServer.ClientLogName(clients[i]), clients[i].Connection?.EndPointString, characterInfos[i].Job.Name), ServerLog.MessageType.Spawning);
GameServer.Log(
$"Respawning {GameServer.ClientLogName(clients[i])} ({clients[i].Connection.Endpoint}) as {characterInfos[i].Job.Name}", ServerLog.MessageType.Spawning);
}
if (RespawnShuttle != null)
{
Vector2 pos = cargoSp == null ? character.Position : cargoSp.Position;
List<Item> newRespawnItems = new List<Item>();
Vector2 pos = cargoSp?.Position ?? character.Position;
if (divingSuitPrefab != null)
{
var divingSuit = new Item(divingSuitPrefab, pos, respawnSub);
Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(divingSuit));
respawnItems.Add(divingSuit);
newRespawnItems.Add(divingSuit);
if (oxyPrefab != null && divingSuit.GetComponent<ItemContainer>() != null)
{
var oxyTank = new Item(oxyPrefab, pos, respawnSub);
Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(oxyTank));
divingSuit.Combine(oxyTank, user: null);
respawnItems.Add(oxyTank);
newRespawnItems.Add(oxyTank);
}
}
@@ -473,13 +475,13 @@ namespace Barotrauma.Networking
{
var scooter = new Item(scooterPrefab, pos, respawnSub);
Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(scooter));
respawnItems.Add(scooter);
newRespawnItems.Add(scooter);
if (batteryPrefab != null)
{
var battery = new Item(batteryPrefab, pos, respawnSub);
Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(battery));
scooter.Combine(battery, user: null);
respawnItems.Add(battery);
newRespawnItems.Add(battery);
}
}
}
@@ -489,8 +491,9 @@ namespace Barotrauma.Networking
}
//try to put the items in containers in the shuttle
foreach (var respawnItem in respawnItems)
foreach (var respawnItem in newRespawnItems)
{
System.Diagnostics.Debug.Assert(!respawnItem.Removed);
foreach (Item shuttleItem in RespawnShuttle.GetItems(alsoFromConnectedSubs: false))
{
if (shuttleItem.NonInteractable || shuttleItem.NonPlayerTeamInteractable) { continue; }
@@ -500,6 +503,7 @@ namespace Barotrauma.Networking
break;
}
}
respawnItems.Add(respawnItem);
}
}
@@ -69,7 +69,6 @@ namespace Barotrauma.Networking
WriteNetProperties(outMsg, c);
WriteMonsterEnabled(outMsg);
BanList.ServerAdminWrite(outMsg, c);
Whitelist.ServerAdminWrite(outMsg, c);
}
public void ServerWrite(IWriteMessage outMsg, Client c)
@@ -171,7 +170,6 @@ namespace Barotrauma.Networking
propertiesChanged |= changedMonsterSettings;
if (changedMonsterSettings) { ReadMonsterEnabled(incMsg); }
propertiesChanged |= BanList.ServerAdminRead(incMsg, c);
propertiesChanged |= Whitelist.ServerAdminRead(incMsg, c);
if (propertiesChanged)
{
@@ -444,31 +442,27 @@ namespace Barotrauma.Networking
{
ClientPermissions.Clear();
if (!File.Exists(ClientPermissionsFile))
{
if (File.Exists("Data/clientpermissions.txt"))
{
LoadClientPermissionsOld("Data/clientpermissions.txt");
}
return;
}
if (!File.Exists(ClientPermissionsFile)) { return; }
XDocument doc = XMLExtensions.TryLoadXml(ClientPermissionsFile);
if (doc == null) { return; }
foreach (XElement clientElement in doc.Root.Elements())
{
string clientName = clientElement.GetAttributeString("name", "");
string clientEndPoint = clientElement.GetAttributeString("endpoint", null) ?? clientElement.GetAttributeString("ip", "");
string steamIdStr = clientElement.GetAttributeString("steamid", "");
string addressStr = clientElement.GetAttributeString("address", null)
?? clientElement.GetAttributeString("endpoint", null)
?? clientElement.GetAttributeString("ip", "");
string accountIdStr = clientElement.GetAttributeString("accountid", null)
?? clientElement.GetAttributeString("steamid", "");
if (string.IsNullOrWhiteSpace(clientName))
{
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - all clients must have a name and an IP address.");
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - all clients must have a name.");
continue;
}
if (string.IsNullOrWhiteSpace(clientEndPoint) && string.IsNullOrWhiteSpace(steamIdStr))
if (string.IsNullOrWhiteSpace(addressStr) && string.IsNullOrWhiteSpace(accountIdStr))
{
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - all clients must have an IP address or a Steam ID.");
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - all clients must have an endpoint or a Steam ID.");
continue;
}
@@ -525,69 +519,33 @@ namespace Barotrauma.Networking
}
}
if (!string.IsNullOrEmpty(steamIdStr))
if (!string.IsNullOrEmpty(accountIdStr))
{
if (ulong.TryParse(steamIdStr, out ulong steamID))
if (AccountId.Parse(accountIdStr).TryUnwrap(out var accountId))
{
ClientPermissions.Add(new SavedClientPermission(clientName, steamID, permissions, permittedCommands));
ClientPermissions.Add(new SavedClientPermission(clientName, accountId, permissions, permittedCommands));
}
else
{
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - \"" + steamIdStr + "\" is not a valid Steam ID.");
continue;
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - \"" + accountIdStr + "\" is not a valid account ID.");
}
}
else
{
ClientPermissions.Add(new SavedClientPermission(clientName, clientEndPoint, permissions, permittedCommands));
}
}
}
/// <summary>
/// Method for loading old .txt client permission files to provide backwards compatibility
/// </summary>
private void LoadClientPermissionsOld(string file)
{
if (!File.Exists(file)) return;
string[] lines;
try
{
lines = File.ReadAllLines(file);
}
catch (Exception e)
{
DebugConsole.ThrowError("Failed to open client permission file " + ClientPermissionsFile, e);
return;
}
ClientPermissions.Clear();
foreach (string line in lines)
{
string[] separatedLine = line.Split('|');
if (separatedLine.Length < 3) { continue; }
string name = string.Join("|", separatedLine.Take(separatedLine.Length - 2));
string ip = separatedLine[separatedLine.Length - 2];
ClientPermissions permissions;
if (Enum.TryParse(separatedLine.Last(), out permissions))
{
ClientPermissions.Add(new SavedClientPermission(name, ip, permissions, new HashSet<DebugConsole.Command>()));
if (Address.Parse(addressStr).TryUnwrap(out var address))
{
ClientPermissions.Add(new SavedClientPermission(clientName, address, permissions, permittedCommands));
}
else
{
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - \"" + addressStr + "\" is not a valid endpoint.");
}
}
}
}
public void SaveClientPermissions()
{
//delete old client permission file
if (File.Exists("Data/clientpermissions.txt"))
{
File.Delete("Data/clientpermissions.txt");
}
GameServer.Log("Saving client permissions", ServerLog.MessageType.ServerMessage);
XDocument doc = new XDocument(new XElement("ClientPermissions"));
@@ -595,6 +553,7 @@ namespace Barotrauma.Networking
foreach (SavedClientPermission clientPermission in ClientPermissions)
{
var matchingPreset = PermissionPreset.List.Find(p => p.MatchesPermissions(clientPermission.Permissions, clientPermission.PermittedCommands));
#warning TODO: this is broken because of localization
if (matchingPreset != null && matchingPreset.Name == "None")
{
continue;
@@ -603,23 +562,14 @@ namespace Barotrauma.Networking
XElement clientElement = new XElement("Client",
new XAttribute("name", clientPermission.Name));
if (clientPermission.SteamID > 0)
{
clientElement.Add(new XAttribute("steamid", clientPermission.SteamID));
}
else
{
clientElement.Add(new XAttribute("endpoint", clientPermission.EndPoint));
}
clientElement.Add(clientPermission.AddressOrAccountId.TryGet(out AccountId accountId)
? new XAttribute("accountid", accountId.StringRepresentation)
: new XAttribute("address", ((Address)clientPermission.AddressOrAccountId).StringRepresentation));
if (matchingPreset == null)
{
clientElement.Add(new XAttribute("permissions", clientPermission.Permissions.ToString()));
}
else
{
clientElement.Add(new XAttribute("preset", matchingPreset.Name));
}
clientElement.Add(matchingPreset == null
? new XAttribute("permissions", clientPermission.Permissions.ToString())
: new XAttribute("preset", matchingPreset.Name));
if (clientPermission.Permissions.HasFlag(Networking.ClientPermissions.ConsoleCommands))
{
foreach (DebugConsole.Command command in clientPermission.PermittedCommands)
@@ -257,11 +257,10 @@ namespace Barotrauma
if ((DateTime.Now - sender.JoinTime).TotalSeconds > GameMain.Server.ServerSettings.DisallowKickVoteTime)
{
GameMain.Server.SendDirectChatMessage($"ServerMessage.kickvotedisallowed", sender);
}
else
{
Client kicked = GameMain.Server.ConnectedClients.Find(c => c.ID == kickedClientID);
Client kicked = GameMain.Server.ConnectedClients.Find(c => c.SessionId == kickedClientID);
if (kicked != null && kicked.Connection != GameMain.Server.OwnerConnection && !kicked.HasKickVoteFrom(sender))
{
kicked.AddKickVote(sender);
@@ -293,9 +292,9 @@ namespace Barotrauma
if (!ShouldRejectVote(sender, voteType))
{
pendingVotes.Enqueue(new TransferVote(sender,
GameMain.Server.ConnectedClients.Find(c => c.ID == fromClientId),
GameMain.Server.ConnectedClients.Find(c => c.SessionId == fromClientId),
amount,
GameMain.Server.ConnectedClients.Find(c => c.ID == toClientId)));
GameMain.Server.ConnectedClients.Find(c => c.SessionId == toClientId)));
}
}
else
@@ -372,14 +371,14 @@ namespace Barotrauma
msg.Write((byte)yesClients.Count());
foreach (Client c in yesClients)
{
msg.Write(c.ID);
msg.Write(c.SessionId);
}
var noClients = eligibleClients.Where(c => c.GetVote<int>(ActiveVote.VoteType) == 1);
msg.Write((byte)noClients.Count());
foreach (Client c in noClients)
{
msg.Write(c.ID);
msg.Write(c.SessionId);
}
msg.Write((byte)eligibleClients.Count());
@@ -387,7 +386,7 @@ namespace Barotrauma
switch (ActiveVote.State)
{
case VoteState.Started:
msg.Write(ActiveVote.VoteStarter.ID);
msg.Write(ActiveVote.VoteStarter.SessionId);
msg.Write((byte)GameMain.Server.ServerSettings.VoteTimeout);
switch (ActiveVote.VoteType)
@@ -401,8 +400,8 @@ namespace Barotrauma
break;
case VoteType.TransferMoney:
var transferVote = (ActiveVote as TransferVote);
msg.Write(transferVote.From?.ID ?? 0);
msg.Write(transferVote.To?.ID ?? 0);
msg.Write(transferVote.From?.SessionId ?? 0);
msg.Write(transferVote.To?.SessionId ?? 0);
msg.Write(transferVote.TransferAmount);
break;
}
@@ -430,11 +429,11 @@ namespace Barotrauma
}
}
var readyClients = GameMain.Server.ConnectedClients.FindAll(c => c.GetVote<bool>(VoteType.StartRound));
msg.Write((byte)readyClients.Count);
var readyClients = GameMain.Server.ConnectedClients.Where(c => c.GetVote<bool>(VoteType.StartRound));
msg.Write((byte)readyClients.Count());
foreach (Client c in readyClients)
{
msg.Write(c.ID);
msg.Write(c.SessionId);
}
msg.WritePadBits();