-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathServer.cs
442 lines (383 loc) · 16.8 KB
/
Server.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Data.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog.Context;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Dtos;
using SharedLibraryCore.Exceptions;
using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace SharedLibraryCore
{
public abstract class Server : IGameServer
{
public enum Game
{
COD = -1,
UKN = 0,
IW3 = 1,
IW4 = 2,
IW5 = 3,
IW6 = 4,
T4 = 5,
T5 = 6,
T6 = 7,
T7 = 8,
SHG1 = 9,
CSGO = 10,
H1 = 11,
L4D2 = 12,
H2M = 13
}
// only here for performance
private readonly bool CustomSayEnabled;
protected readonly string CustomSayName;
protected readonly DefaultSettings DefaultSettings;
protected readonly ILogger ServerLogger;
protected List<string> BroadcastMessages;
protected int ConnectionErrors;
protected string FSGame;
protected IGameLogReaderFactory gameLogReaderFactory;
// Info
private string hostname;
protected TimeSpan LastMessage;
protected DateTime LastPoll;
protected int NextMessage;
protected ManualResetEventSlim OnRemoteCommandResponse;
protected IRConConnectionFactory RConConnectionFactory;
#pragma warning disable CS0612
public Server(ILogger<Server> logger, Interfaces.ILogger deprecatedLogger,
#pragma warning restore CS0612
ServerConfiguration config, IManager mgr, IRConConnectionFactory rconConnectionFactory,
IGameLogReaderFactory gameLogReaderFactory, IServiceProvider serviceProvider)
{
Password = config.Password;
IP = config.IPAddress;
Port = config.Port;
Manager = mgr;
#pragma warning disable CS0612
Logger = deprecatedLogger ?? throw new ArgumentNullException(nameof(deprecatedLogger));
#pragma warning restore CS0612
ServerConfig = config;
EventProcessing = new SemaphoreSlim(1, 1);
Clients = new List<EFClient>(new EFClient[64]);
Reports = new List<Report>();
ClientHistory = new ClientHistoryInfo();
ChatHistory = new List<ChatInfo>();
NextMessage = 0;
CustomSayEnabled = Manager.GetApplicationSettings().Configuration().EnableCustomSayName;
CustomSayName = Manager.GetApplicationSettings().Configuration().CustomSayName;
this.gameLogReaderFactory = gameLogReaderFactory;
RConConnectionFactory = rconConnectionFactory;
ServerLogger = logger;
DefaultSettings = serviceProvider.GetRequiredService<DefaultSettings>();
InitializeTokens();
InitializeAutoMessages();
}
public long EndPoint => IPAddress.TryParse(ListenAddress, out _)
? Convert.ToInt64($"{ListenAddress!.Replace(".", "")}{ListenPort}")
: $"{ListenAddress!.Replace(".", "")}{ListenPort}".GetStableHashCode();
public abstract long LegacyDatabaseId { get; }
public string Id => $"{ListenAddress}:{ListenPort}";
// Objects
public IManager Manager { get; protected set; }
[Obsolete] public Interfaces.ILogger Logger { get; }
public ServerConfiguration ServerConfig { get; }
public List<Map> Maps { get; protected set; } = new List<Map>();
public List<Report> Reports { get; set; }
public List<ChatInfo> ChatHistory { get; protected set; }
public ClientHistoryInfo ClientHistory { get; }
public Game GameName { get; set; }
public Reference.Game GameCode => (Reference.Game)GameName;
public DateTime? MatchEndTime { get; protected set; }
public DateTime? MatchStartTime { get; protected set; }
public string Hostname
{
get => ServerConfig.CustomHostname ?? hostname;
protected set => hostname = value;
}
public string ServerName => Hostname;
public string Website { get; protected set; }
public string Gametype { get; set; }
public string GametypeName => DefaultSettings.Gametypes?.FirstOrDefault(gt => gt.Game == GameName)?.Gametypes
?.FirstOrDefault(gt => gt.Name == Gametype)?.Alias ?? Gametype;
public string GamePassword { get; protected set; }
public int PrivateClientSlots { get; protected set; }
public Map CurrentMap { get; set; }
public Map Map => CurrentMap;
public int ClientNum
{
get { return Clients.ToArray().Count(p => p != null && Utilities.IsDevelopment || (!p?.IsBot ?? false)); }
}
public int MaxClients { get; protected set; }
public List<EFClient> Clients { get; protected set; }
public IReadOnlyList<EFClient> ConnectedClients =>
new ReadOnlyCollection<EFClient>(GetClientsAsList());
public string Password { get; }
public bool Throttled { get; protected set; }
public bool CustomCallback { get; protected set; }
public bool IsLegacyGameIntegrationEnabled => CustomCallback;
public string WorkingDirectory { get; protected set; }
public IRConConnection RemoteConnection { get; protected set; }
public IRConParser RconParser { get; set; }
public IEventParser EventParser { get; set; }
public string LogPath { get; protected set; }
public bool RestartRequested { get; set; }
public SemaphoreSlim EventProcessing { get; }
// Internal
/// <summary>
/// this is actually the listen address now
/// </summary>
public string IP { get; protected set; }
public string ListenAddress => IP;
public IPEndPoint ResolvedIpEndPoint { get; protected set; }
public string Version { get; protected set; }
public bool IsInitialized { get; set; }
public int Port { get; protected set; }
public int ListenPort => Port;
public abstract Task Kick(string reason, EFClient target, EFClient origin, EFPenalty originalPenalty);
public abstract Task<string[]> ExecuteCommandAsync(string command, CancellationToken token = default);
public abstract Task SetDvarAsync(string name, object value, CancellationToken token = default);
/// <summary>
/// Returns list of all current players
/// </summary>
/// <returns></returns>
public List<EFClient> GetClientsAsList()
{
lock (Clients)
{
return Clients.FindAll(client => client is not null && client.NetworkId != 0);
}
}
/// <summary>
/// Add a player to the server's player list
/// </summary>
/// <param name="P">EFClient pulled from memory reading</param>
/// <returns>True if player added successfully, false otherwise</returns>
public abstract Task<EFClient> OnClientConnected(EFClient P);
/// <summary>
/// Remove player by client number
/// </summary>
/// <returns>true if removal succeeded, false otherwise</returns>
public abstract Task OnClientDisconnected(EFClient client);
/// <summary>
/// Get a player by name
/// todo: make this an extension
/// </summary>
/// <param name="pName">EFClient name to search for</param>
/// <returns>Matching player if found</returns>
public List<EFClient> GetClientByName(string pName)
{
if (string.IsNullOrEmpty(pName))
{
return new List<EFClient>();
}
pName = pName.Trim().StripColors();
var QuoteSplit = pName.Split('"');
var literal = false;
if (QuoteSplit.Length > 1)
{
pName = QuoteSplit[1];
literal = true;
}
if (literal)
{
return GetClientsAsList().Where(p => p.Name?.StripColors()?.ToLower() == pName.ToLower()).ToList();
}
return GetClientsAsList().Where(p => (p.Name?.StripColors()?.ToLower() ?? "").Contains(pName.ToLower()))
.ToList();
}
public virtual Task<bool> ProcessUpdatesAsync(CancellationToken token)
{
return (Task<bool>)Task.CompletedTask;
}
/// <summary>
/// Process any server event
/// </summary>
/// <param name="E">Event</param>
/// <returns>True on sucess</returns>
protected abstract Task<bool> ProcessEvent(GameEvent E);
public abstract Task ExecuteEvent(GameEvent E);
/// <summary>
/// Send a message to all players
/// </summary>
/// <param name="message">Message to be sent to all players</param>
/// <param name="sender">Client that initiated the broadcast</param>
public GameEvent Broadcast(string message, EFClient sender = null)
{
var hasRawSupport = RconParser.Configuration.CommandPrefixes.Say.Contains("raw");
var formattedMessage = string.Format(RconParser.Configuration.CommandPrefixes.Say ?? "",
$"{(CustomSayEnabled && hasRawSupport ? $"{CustomSayName}: " : "")}{message}");
ServerLogger.LogDebug("All-> {Message}",
message.FormatMessageForEngine(RconParser.Configuration).StripColors());
var e = new GameEvent
{
Type = GameEvent.EventType.Broadcast,
Data = formattedMessage,
Owner = this,
Origin = sender
};
Manager.AddEvent(e);
return e;
}
[Obsolete("Use BroadcastAsync")]
public void Broadcast(IEnumerable<string> messages, EFClient sender = null)
{
foreach (var message in messages)
{
#pragma warning disable 4014
Broadcast(message, sender).WaitAsync();
#pragma warning restore 4014
}
}
public async Task BroadcastAsync(IEnumerable<string> messages, EFClient sender = null,
CancellationToken token = default)
{
foreach (var message in messages)
{
if (Manager.CancellationToken.IsCancellationRequested)
{
return;
}
await Broadcast(message, sender).WaitAsync(Utilities.DefaultCommandTimeout, Manager.CancellationToken);
}
}
/// <summary>
/// Send a message to a particular players
/// </summary>
/// <param name="message">Message to send</param>
/// <param name="targetClient">EFClient to send message to</param>
protected async Task Tell(string message, EFClient targetClient)
{
if (!Utilities.IsDevelopment)
{
var temporalClientId = targetClient.GetAdditionalProperty<string>("ConnectionClientId");
var parsedClientId = string.IsNullOrEmpty(temporalClientId) ? (int?)null : int.Parse(temporalClientId);
var clientNumber = parsedClientId ?? targetClient.ClientNumber;
var hasRawSupport = RconParser.Configuration.CommandPrefixes.Tell.Contains("raw");
var formattedMessage = string.Format(RconParser.Configuration.CommandPrefixes.Tell,
clientNumber,
$"{(CustomSayEnabled && hasRawSupport ? $"{CustomSayName}: " : "")}{message}");
if (targetClient.ClientNumber > -1 && message.Length > 0 &&
targetClient.Level != Data.Models.Client.EFClient.Permission.Console)
{
await this.ExecuteCommandAsync(formattedMessage);
}
}
else
{
ServerLogger.LogDebug("Tell[{ClientNumber}]->{Message}", targetClient.ClientNumber,
message.FormatMessageForEngine(RconParser.Configuration).StripColors());
}
if (targetClient.Level == Data.Models.Client.EFClient.Permission.Console)
{
Console.ForegroundColor = ConsoleColor.Green;
var cleanMessage = message.FormatMessageForEngine(RconParser.Configuration)
.StripColors();
using (LogContext.PushProperty("Server", ToString()))
{
ServerLogger.LogInformation("Command output received: {Message}", cleanMessage);
}
Console.WriteLine(cleanMessage);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
/// <summary>
/// Send a message to all admins on the server
/// </summary>
/// <param name="message">Message to send out</param>
public void ToAdmins(string message)
{
foreach (var client in GetClientsAsList()
.Where(c => c.Level > Data.Models.Client.EFClient.Permission.Flagged))
client.Tell(message);
}
/// <summary>
/// Kick a player from the server
/// </summary>
/// <param name="reason">Reason for kicking</param>
/// <param name="target">EFClient to kick</param>
/// <param name="origin">Client initating the kick</param>
public Task Kick(string reason, EFClient target, EFClient origin)
{
return Kick(reason, target, origin, null);
}
/// <summary>
/// Temporarily ban a player ( default 1 hour ) from the server
/// </summary>
/// <param name="reason">Reason for banning the player</param>
/// <param name="length">Duration of the ban</param>
/// <param name="target">The client to ban</param>
/// <param name="origin">The client performing the ban</param>
public abstract Task TempBan(string reason, TimeSpan length, EFClient target, EFClient origin);
/// <summary>
/// Perm ban a player from the server
/// </summary>
/// <param name="reason">The reason for the ban</param>
/// <param name="target">The person to ban</param>
/// <param name="origin">The person who banned the target</param>
/// <param name="isEvade">obsolete</param>
public abstract Task Ban(string reason, EFClient target, EFClient origin, bool isEvade = false);
public abstract Task Warn(string reason, EFClient target, EFClient origin);
/// <summary>
/// Unban a player by npID / GUID
/// </summary>
/// <param name="reason">reason for unban</param>
/// <param name="targetClient">client being unbanned</param>
/// <param name="originClient">client performing the unban</param>
/// <returns></returns>
public abstract Task Unban(string reason, EFClient targetClient, EFClient originClient);
/// <summary>
/// Change the current server map
/// </summary>
/// <param name="mapName">Non-localized map name</param>
public async Task LoadMap(string mapName)
{
await this.ExecuteCommandAsync($"map {mapName}");
}
/// <summary>
/// Initalize the macro variables
/// </summary>
public abstract void InitializeTokens();
/// <summary>
/// Initialize the messages to be broadcasted
/// </summary>
protected void InitializeAutoMessages()
{
BroadcastMessages = new List<string>();
if (ServerConfig.AutoMessages != null)
{
BroadcastMessages.AddRange(ServerConfig.AutoMessages);
}
BroadcastMessages.AddRange(Manager.GetApplicationSettings().Configuration().AutoMessages);
}
public override string ToString()
{
return $"{ListenAddress}:{ListenPort}";
}
protected async Task<bool> ScriptLoaded()
{
try
{
return (await this.GetDvarAsync("sv_customcallbacks", "0", Manager.CancellationToken)).Value == "1";
}
catch (DvarException)
{
return false;
}
}
public abstract Task<long> GetIdForServer(Server server = null);
[Obsolete("Use the ScriptPluginExtension helper")]
public EFClient GetClientByNumber(int clientNumber) =>
GetClientsAsList().FirstOrDefault(client => client.ClientNumber == clientNumber);
}
}