-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCommon.cs
More file actions
426 lines (357 loc) · 18.7 KB
/
Common.cs
File metadata and controls
426 lines (357 loc) · 18.7 KB
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
using Atlasd.Battlenet.Protocols.Game;
using Atlasd.Battlenet.Protocols.Game.Messages;
using Atlasd.Battlenet.Protocols.Udp;
using Atlasd.Daemon;
using Atlasd.Localization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Atlasd.Battlenet
{
class Common
{
public const string NewLine = "\r\n"; // This should be the same line ending format of the Atlasd/Localization/Resources.resx XML document.
public struct ShutdownEvent
{
public string AdminMessage { get; private set; }
public bool Cancelled { get; private set; }
public DateTime EventDate { get; private set; }
public Timer EventTimer { get; private set; }
public ShutdownEvent(string adminMessage, bool cancelled, DateTime eventDate, Timer eventTimer)
{
AdminMessage = adminMessage;
Cancelled = cancelled;
EventDate = eventDate;
EventTimer = eventTimer;
}
};
public static ConcurrentDictionary<string, Account> AccountsDb;
public static ConcurrentDictionary<string, Account> AccountsProcessing;
public static ConcurrentDictionary<string, Account> ActiveAccounts;
public static ConcurrentDictionary<UInt32, Advertisement> ActiveAds;
public static ConcurrentDictionary<string, Channel> ActiveChannels;
public static ConcurrentDictionary<byte[], Clan> ActiveClans;
public static ConcurrentDictionary<Socket, ClientState> ActiveClientStates;
public static List<GameAd> ActiveGameAds;
public static readonly object ActiveGameAdsLock = new object();
public static ConcurrentDictionary<string, GameState> ActiveGameStates;
public static IPAddress DefaultAddress { get; private set; }
public static int DefaultPort { get; private set; }
public static ServerSocket Listener { get; private set; }
public static IPAddress ListenerAddress { get; private set; }
public static IPEndPoint ListenerEndPoint { get; private set; }
public static int ListenerPort { get; private set; }
public static Timer NullTimer { get; private set; }
public static Timer PingTimer { get; private set; }
public static ShutdownEvent ScheduledShutdown { get; private set; }
public static UdpListener UdpListener { get; private set; }
public static string GetServerGreeting(ClientState receiver)
{
var r = Resources.ChannelFirstJoinGreeting;
r = r.Replace("{host}", "BNETDocs");
r = r.Replace("{serverStats}", GetServerStats(receiver));
r = r.Replace("{realm}", Settings.GetString(new string[] { "battlenet", "realm", "name" }, Resources.Battlenet));
return r;
}
public static string GetServerStats(ClientState receiver)
{
if (receiver == null || receiver.GameState == null || receiver.GameState.ActiveChannel == null) return "";
var channel = receiver.GameState.ActiveChannel;
var numGameOnline = GetActiveClientCountByProduct(receiver.GameState.Product);
var numGameAdvertisements = 0;
var numTotalOnline = ActiveClientStates.Count;
var numTotalAdvertisements = 0;
var realmName = Settings.GetString(new string[] { "battlenet", "realm", "name" }, Resources.Battlenet);
var strGame = Product.ProductName(receiver.GameState.Product, true);
var r = Resources.ServerStatistics;
r = r.Replace("{channel}", channel.Name);
r = r.Replace("{host}", "BNETDocs");
r = r.Replace("{game}", strGame);
r = r.Replace("{gameUsers}", numGameOnline.ToString("#,0"));
r = r.Replace("{gameAds}", numGameAdvertisements.ToString("#,0"));
r = r.Replace("{realm}", realmName);
r = r.Replace("{totalUsers}", numTotalOnline.ToString("#,0"));
r = r.Replace("{totalGameAds}", numTotalAdvertisements.ToString("#,0"));
return r;
}
public static void Initialize()
{
Logging.WriteLine(Logging.LogLevel.Warning, Logging.LogType.Config, "Initializing Battle.net common state");
AccountsDb = new ConcurrentDictionary<string, Account>(StringComparer.OrdinalIgnoreCase);
AccountsProcessing = new ConcurrentDictionary<string, Account>(StringComparer.OrdinalIgnoreCase);
ActiveAccounts = new ConcurrentDictionary<string, Account>(StringComparer.OrdinalIgnoreCase);
ActiveChannels = new ConcurrentDictionary<string, Channel>(StringComparer.OrdinalIgnoreCase);
ActiveClans = new ConcurrentDictionary<byte[], Clan>();
ActiveClientStates = new ConcurrentDictionary<Socket, ClientState>();
ActiveGameAds = new List<GameAd>();
ActiveGameStates = new ConcurrentDictionary<string, GameState>(StringComparer.OrdinalIgnoreCase);
InitializeAds();
DefaultAddress = IPAddress.Any;
DefaultPort = 6112;
InitializeListener();
NullTimer = new Timer(ProcessNullTimer, ActiveGameStates, 100, 100);
PingTimer = new Timer(ProcessPingTimer, ActiveGameStates, 100, 100);
ScheduledShutdown = new ShutdownEvent(null, true, DateTime.MinValue, null);
Daemon.Common.TcpNoDelay = Settings.GetBoolean(new string[] { "battlenet", "listener", "tcp_nodelay" }, true);
}
public static void InitializeAds()
{
Logging.WriteLine(Logging.LogLevel.Warning, Logging.LogType.Config, "Initializing advertisements");
Settings.State.RootElement.TryGetProperty("ads", out var adsJson);
if (ActiveAds == null || ActiveAds.Count != 0) ActiveAds = new ConcurrentDictionary<UInt32, Advertisement>();
UInt32 adId = 0;
foreach (var adJson in adsJson.EnumerateArray())
{
adJson.TryGetProperty("enabled", out var enabledJson);
adJson.TryGetProperty("filename", out var filenameJson);
adJson.TryGetProperty("url", out var urlJson);
adJson.TryGetProperty("product", out var productsJson);
adJson.TryGetProperty("locale", out var localesJson);
var enabled = enabledJson.GetBoolean();
var filename = filenameJson.GetString();
var url = urlJson.GetString();
List<Product.ProductCode> products = null;
List<uint> locales = null;
if (productsJson.ValueKind == JsonValueKind.Array)
{
foreach (var productJson in productsJson.EnumerateArray())
{
var productStr = productJson.GetString();
}
}
if (localesJson.ValueKind == JsonValueKind.Array)
{
foreach (var localeJson in localesJson.EnumerateArray())
{
var localeId = localeJson.GetUInt32();
}
}
var ad = new Advertisement(filename, url, products, locales);
if (!ActiveAds.TryAdd(adId, ad))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Config, $"Failed to add advertisement [{filename}] to active advertisement cache");
}
else
{
adId++; // increment only if TryAdd succeeds, ActiveAds needs to be linear for random ad selection to work in SID_CHECKAD.
}
}
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Config, $"Initialized {ActiveAds.Count} advertisements");
}
private static void InitializeListener()
{
Settings.State.RootElement.TryGetProperty("battlenet", out var battlenetJson);
battlenetJson.TryGetProperty("listener", out var listenerJson);
listenerJson.TryGetProperty("interface", out var interfaceJson);
listenerJson.TryGetProperty("port", out var portJson);
var listenerAddressStr = interfaceJson.GetString();
if (!IPAddress.TryParse(listenerAddressStr, out IPAddress listenerAddress))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, $"Unable to parse IP address from [battlenet.listener.interface] with value [{listenerAddressStr}]; using any");
listenerAddress = DefaultAddress;
}
ListenerAddress = listenerAddress;
portJson.TryGetInt32(out var port);
ListenerPort = port;
if (!IPEndPoint.TryParse($"{ListenerAddress}:{ListenerPort}", out IPEndPoint listenerEndPoint))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, $"Unable to parse endpoint with value [{ListenerAddress}:{ListenerPort}]");
return;
}
ListenerEndPoint = listenerEndPoint;
UdpListener = new UdpListener(ListenerEndPoint);
Listener = new ServerSocket(ListenerEndPoint);
}
public static uint GetActiveClientCountByProduct(Product.ProductCode productCode)
{
var count = (uint)0;
foreach (var client in ActiveClientStates.Values)
{
if (client == null || client.GameState == null || client.GameState.Product == Product.ProductCode.None) continue;
if (client.GameState.Product == productCode) count++;
}
return count;
}
public static bool GetClientByOnlineName(string target, out GameState client)
{
var t = target;
// Escape out of Diablo II character name designation
if (t.Contains('*'))
{
t = t[(t.IndexOf('*') + 1)..];
}
// Escape out of gateway designation
if (t.Contains('#'))
{
var n = t[(t.LastIndexOf('#') + 1)..];
if (!int.TryParse(n, out var i) || i == 0)
{
t = t[0..t.LastIndexOf('#')];
}
}
return ActiveGameStates.TryGetValue(t, out client);
}
static void ProcessNullTimer(object state)
{
var gameStates = state as ConcurrentDictionary<string, GameState>;
var msg = new SID_NULL();
var interval = TimeSpan.FromSeconds(60);
var now = DateTime.Now;
foreach (var gameState in gameStates.Values)
{
if (gameState == null) continue;
if (gameState.Client == null) continue;
if (!gameState.Client.Connected) continue;
if (gameState.LastNull == null || gameState.LastNull + interval > now) continue;
gameState.LastNull = now;
msg.Invoke(new MessageContext(gameState.Client, Protocols.MessageDirection.ServerToClient));
}
}
static void ProcessPingTimer(object state)
{
var chatGatewayReceivesPings = Settings.GetBoolean(new string[] { "battlenet", "emulation", "chat_gateway", "receive_ping_messages" }, false);
var gameStates = state as ConcurrentDictionary<string, GameState>;
var msg = new SID_PING();
var r = new Random();
var interval = TimeSpan.FromSeconds(180);
var unresponsiveInterval = interval.Multiply(2);
var unresponsiveIntervalMS = (int)Math.Round(unresponsiveInterval.TotalMilliseconds);
var now = DateTime.Now;
foreach (var gameState in gameStates.Values)
{
if (gameState == null) continue;
if (gameState.Client == null) continue;
if (!gameState.Client.Connected) continue;
if (gameState.Client.ProtocolType.IsChat() && !chatGatewayReceivesPings) continue;
if (gameState.LastPing == null) continue;
if (gameState.LastPing + interval <= now)
{
gameState.LastPing = now;
gameState.PingToken = (uint)r.Next(0, 0x7FFFFFFF);
msg.Invoke(new MessageContext(gameState.Client, Protocols.MessageDirection.ServerToClient, new Dictionary<string, dynamic>(){{ "token", gameState.PingToken }}));
}
// TODO: Fix this commented out code. It seems to have false-positive conditions and abruptly sets unresponsive ping on timely clients.
/*if (gameState.LastPong + unresponsiveInterval <= now && gameState.ActiveChannel != null && gameState.Ping != unresponsiveIntervalMS)
{
gameState.ActiveChannel.UpdateUser(gameState, unresponsiveIntervalMS);
}*/
}
}
public static void ScheduleShutdown(TimeSpan period, string message = null, ChatCommandContext command = null)
{
var rescheduled = false;
if (ScheduledShutdown.EventTimer != null)
{
rescheduled = true;
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Server, "Stopping previously scheduled shutdown timer");
ScheduledShutdown.EventTimer.Dispose();
}
ScheduledShutdown = new ShutdownEvent(message, false, DateTime.Now + period,
new Timer((object state) =>
{
Program.ExitCode = 0;
Program.Exit = true;
}, command, period, period)
);
var tsStr = $"{period.Hours} hour{(period.Hours == 1 ? "" : "s")} {period.Minutes} minute{(period.Minutes == 1 ? "" : "s")} {period.Seconds} second{(period.Seconds == 1 ? "" : "s")}";
tsStr = tsStr.Replace("0 hours ", "");
tsStr = tsStr.Replace("0 minutes ", "");
tsStr = tsStr.Replace(" 0 seconds", "");
string m;
if (string.IsNullOrEmpty(message) && !rescheduled)
{
m = Resources.ServerShutdownScheduled;
}
else if (string.IsNullOrEmpty(message) && rescheduled)
{
m = Resources.ServerShutdownRescheduled;
}
else if (!string.IsNullOrEmpty(message) && !rescheduled)
{
m = Resources.ServerShutdownScheduledWithMessage;
}
else if (!string.IsNullOrEmpty(message) && rescheduled)
{
m = Resources.ServerShutdownRescheduledWithMessage;
}
else
{
throw new InvalidOperationException("Cannot set server shutdown message from localized resource");
}
m = m.Replace("{period}", tsStr);
m = m.Replace("{message}", message);
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, m);
Task.Run(() =>
{
var realmName = Settings.GetString(new string[] { "battlenet", "realm", "name" }, Resources.Battlenet);
var chatEvent = new ChatEvent(ChatEvent.EventIds.EID_BROADCAST, Account.Flags.Admin, -1, realmName, m);
foreach (var gameState in ActiveGameStates.Values) chatEvent.WriteTo(gameState.Client);
if (command != null)
{
var r = Resources.AdminShutdownCommandScheduled;
foreach (var kv in command.Environment)
{
r = r.Replace("{" + kv.Key + "}", kv.Value);
}
foreach (var line in r.Split(Environment.NewLine))
new ChatEvent(ChatEvent.EventIds.EID_INFO, (uint)command.GameState.ChannelFlags, command.GameState.Ping, command.GameState.OnlineName, line).WriteTo(command.GameState.Client);
}
});
}
public static void ScheduleShutdownCancelled(string message = null, ChatCommandContext command = null)
{
if (ScheduledShutdown.Cancelled)
{
if (command != null)
{
var r = Resources.AdminShutdownCommandNotScheduled;
foreach (var kv in command.Environment)
{
r = r.Replace("{" + kv.Key + "}", kv.Value);
}
foreach (var line in r.Split(Environment.NewLine))
new ChatEvent(ChatEvent.EventIds.EID_ERROR, (uint)command.GameState.ChannelFlags, command.GameState.Ping, command.GameState.OnlineName, line).WriteTo(command.GameState.Client);
}
}
else
{
var m = string.IsNullOrEmpty(message) ? Resources.ServerShutdownCancelled : Resources.ServerShutdownCancelledWithMessage;
m = m.Replace("{message}", message);
if (ScheduledShutdown.EventTimer != null)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Server, "Stopping previously scheduled shutdown event");
ScheduledShutdown.EventTimer.Dispose();
}
ScheduledShutdown = new ShutdownEvent(
ScheduledShutdown.AdminMessage,
true, // Cancelled
ScheduledShutdown.EventDate,
ScheduledShutdown.EventTimer
);
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, m);
Task.Run(() =>
{
var realmName = Settings.GetString(new string[] { "battlenet", "realm", "name" }, Resources.Battlenet);
var chatEvent = new ChatEvent(ChatEvent.EventIds.EID_BROADCAST, Account.Flags.Admin, -1, realmName, m);
foreach (var gameState in ActiveGameStates.Values) chatEvent.WriteTo(gameState.Client);
if (command != null)
{
var r = Resources.AdminShutdownCommandCancelled;
foreach (var kv in command.Environment)
{
r = r.Replace("{" + kv.Key + "}", kv.Value);
}
foreach (var line in r.Split(Environment.NewLine))
new ChatEvent(ChatEvent.EventIds.EID_INFO, (uint)command.GameState.ChannelFlags, command.GameState.Ping, command.GameState.OnlineName, line).WriteTo(command.GameState.Client);
}
});
}
}
}
}