-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClientState.cs
More file actions
591 lines (501 loc) · 24.4 KB
/
ClientState.cs
File metadata and controls
591 lines (501 loc) · 24.4 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
using Atlasd.Battlenet.Exceptions;
using Atlasd.Battlenet.Protocols.BNFTP;
using Atlasd.Battlenet.Protocols.Game;
using Atlasd.Battlenet.Protocols.Game.Messages;
using Atlasd.Daemon;
using Atlasd.Helpers;
using Atlasd.Localization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Atlasd.Battlenet
{
class ClientState
{
public BNFTPState BNFTPState;
public bool Connected { get => Socket != null && Socket.Connected; }
public bool IsClosing { get; private set; } = false;
public GameState GameState { get; private set; }
public RealmState RealmState { get; set; }
public ProtocolType ProtocolType { get; private set; }
public EndPoint RemoteEndPoint { get; private set; }
public IPAddress RemoteIPAddress { get; private set; }
public Socket Socket { get; set; }
protected byte[] ReceiveBuffer = new byte[0];
protected byte[] SendBuffer = new byte[0];
protected Frame BattlenetGameFrame = new Frame();
public ClientState(Socket client)
{
Initialize(client);
}
public void Close()
{
if (IsClosing) return;
IsClosing = true;
Disconnect();
IsClosing = false;
}
public void Disconnect(string reason = null)
{
Logging.WriteLine(Logging.LogLevel.Warning, Logging.LogType.Client, RemoteEndPoint, "TCP connection forcefully closed by server");
// If reason was provided, send it to this client
if (reason != null)
{
if (GameState != null)
{
var r = reason.Length == 0 ? Resources.DisconnectedByAdmin : Resources.DisconnectedByAdminWithReason;
new ChatEvent(ChatEvent.EventIds.EID_ERROR, GameState.ChannelFlags, GameState.Ping, GameState.OnlineName, r).WriteTo(this);
}
}
// Close the GameState
try
{
if (GameState != null)
{
GameState.Close();
}
}
catch (ObjectDisposedException) { }
finally
{
GameState = null;
}
// Remove this from ActiveClientStates
if (!Common.ActiveClientStates.TryRemove(this.Socket, out _))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, $"Failed to remove client state [{RemoteEndPoint}] from active client state cache");
}
// Close the connection
try
{
if (Socket != null && Socket.Connected) Socket.Shutdown(SocketShutdown.Send);
}
catch (Exception ex)
{
if (!(ex is SocketException || ex is ObjectDisposedException)) throw;
}
finally
{
if (Socket != null) Socket.Close();
}
}
protected void Initialize(Socket client)
{
if (!Common.ActiveClientStates.TryAdd(client, this))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Server, $"Failed to add client state [{this.Socket.RemoteEndPoint}] to active client state cache");
}
BNFTPState = null;
GameState = null;
ProtocolType = null;
RemoteEndPoint = client.RemoteEndPoint;
RemoteIPAddress = (client.RemoteEndPoint as IPEndPoint).Address;
Socket = client;
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client, RemoteEndPoint, "TCP connection established");
client.NoDelay = Daemon.Common.TcpNoDelay;
client.ReceiveTimeout = 500;
client.SendTimeout = 500;
if (client.ReceiveBufferSize < 0xFFFF)
{
Logging.WriteLine(Logging.LogLevel.Debug, Logging.LogType.Client, RemoteEndPoint, "Setting ReceiveBufferSize to [0xFFFF]");
client.ReceiveBufferSize = 0xFFFF;
}
if (client.SendBufferSize < 0xFFFF)
{
Logging.WriteLine(Logging.LogLevel.Debug, Logging.LogType.Client, RemoteEndPoint, "Setting SendBufferSize to [0xFFFF]");
client.SendBufferSize = 0xFFFF;
}
}
private void Invoke(SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success) return;
var context = new MessageContext(this, Protocols.MessageDirection.ClientToServer);
while (BattlenetGameFrame.Messages.TryDequeue(out var msg))
{
if (!msg.Invoke(context))
{
Disconnect();
return;
}
}
}
public void ProcessReceive(SocketAsyncEventArgs e)
{
// check if the remote host closed the connection
if (!(e.SocketError == SocketError.Success && e.BytesTransferred > 0))
{
if (!IsClosing && Socket != null)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client, RemoteEndPoint, $"TCP connection lost");
Close();
}
return;
}
// Append received data to previously received data
lock (ReceiveBuffer)
{
var newBuffer = new byte[ReceiveBuffer.Length + e.BytesTransferred];
Buffer.BlockCopy(ReceiveBuffer, 0, newBuffer, 0, ReceiveBuffer.Length);
Buffer.BlockCopy(e.Buffer, e.Offset, newBuffer, ReceiveBuffer.Length, e.BytesTransferred);
ReceiveBuffer = newBuffer;
}
if (ProtocolType == null) ReceiveProtocolType(e);
ReceiveProtocol(e);
}
public void ProcessSend(SocketAsyncEventArgs e)
{
// check if the remote host closed the connection
if (e.SocketError != SocketError.Success)
{
if (!IsClosing && Socket != null)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client, RemoteEndPoint, $"TCP connection lost");
Close();
}
return;
}
}
public void ReceiveAsync()
{
if (Socket == null || !Socket.Connected) return;
var readEventArgs = new SocketAsyncEventArgs();
readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(SocketIOCompleted);
readEventArgs.SetBuffer(new byte[1024], 0, 1024);
readEventArgs.UserToken = this;
// As soon as the client is connected, post a receive to the connection
bool willRaiseEvent;
try
{
willRaiseEvent = Socket != null && Socket.Connected && Socket.ReceiveAsync(readEventArgs);
}
catch (ObjectDisposedException)
{
return;
}
if (!willRaiseEvent)
{
SocketIOCompleted(this, readEventArgs);
}
}
protected void ReceiveProtocolType(SocketAsyncEventArgs e)
{
if (ProtocolType != null) return;
ProtocolType = new ProtocolType((ProtocolType.Types)ReceiveBuffer[0]);
ReceiveBuffer = ReceiveBuffer[1..];
if (ProtocolType.IsGame() || ProtocolType.IsChat())
{
GameState = new GameState(this);
}
else if (ProtocolType.IsBNFTP())
{
BNFTPState = new BNFTPState(this);
}
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client, RemoteEndPoint, $"Set protocol type [0x{(byte)ProtocolType.Type:X2}] ({ProtocolType})");
if (ProtocolType.IsChat())
{
GameState.Platform = Platform.PlatformCode.Windows;
GameState.Product = Product.ProductCode.Chat;
Send(Encoding.UTF8.GetBytes($"Connection from [{RemoteEndPoint}]{Common.NewLine}"));
Send(Encoding.UTF8.GetBytes($"Enter your login name and password.{Common.NewLine}"));
}
}
protected void ReceiveProtocol(SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success) return;
switch (ProtocolType.Type)
{
case ProtocolType.Types.Game:
ReceiveProtocolGame(e); break;
case ProtocolType.Types.BNFTP:
ReceiveProtocolBNFTP(e); break;
case ProtocolType.Types.Chat:
case ProtocolType.Types.Chat_Alt1:
case ProtocolType.Types.Chat_Alt2:
ReceiveProtocolChat(e); break;
default:
throw new ProtocolNotSupportedException(ProtocolType.Type, this, $"Unsupported protocol type [0x{(byte)ProtocolType.Type:X2}]");
}
}
protected void ReceiveProtocolBNFTP(SocketAsyncEventArgs e)
{
if (ReceiveBuffer.Length == 0) return;
BNFTPState.Receive(ReceiveBuffer);
}
protected void ReceiveProtocolChat(SocketAsyncEventArgs e)
{
// TODO: Move the protocol parsing part of this function somewhere else under Protocols/ChatGateway (similar to Protocols/Game, etc.)
string text;
try
{
text = Encoding.UTF8.GetString(ReceiveBuffer);
}
catch (DecoderFallbackException)
{
Logging.WriteLine(Logging.LogLevel.Warning, Logging.LogType.Client_Chat, RemoteEndPoint, "Failed to decode UTF-8 text");
Disconnect("Failed to decode UTF-8 text");
return;
}
// Mix alternate platform's new lines into our easily parsable NewLine constant:
//text = text.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Common.NewLine);
while (text.Length > 0)
{
if (!text.Contains(Common.NewLine)) break; // Need more data from client
var pos = text.IndexOf(Common.NewLine);
ReceiveBuffer = ReceiveBuffer[(pos + Common.NewLine.Length)..];
var line = text.Substring(0, pos);
text = text[(line.Length + Common.NewLine.Length)..];
if (GameState.ActiveAccount == null && string.IsNullOrEmpty(GameState.Username) && !string.IsNullOrEmpty(line) && line[0] == 0x04)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, "Client sent login byte [0x04]");
line = line[1..];
Send(Encoding.UTF8.GetBytes("Username: "));
GameState.Username = null;
}
if (GameState.ActiveAccount == null && string.IsNullOrEmpty(GameState.Username) && !string.IsNullOrEmpty(line))
{
GameState.Username = line;
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Client set username to [{GameState.Username}]");
Send(Encoding.UTF8.GetBytes("Password: "));
continue;
}
if (GameState.ActiveAccount == null)
{
var autoAccountCreate = Settings.GetBoolean(new string[] { "battlenet", "emulation", "chat_gateway", "auto_account_create" }, false);
var inPasswordHash = MBNCSUtil.XSha1.CalculateHash(Encoding.UTF8.GetBytes(line.ToLower()));
line = string.Empty; // prevent echoing password as a message if successfully authenticated
if (!Common.AccountsDb.TryGetValue(GameState.Username, out Account account) || account == null)
{
if (!autoAccountCreate)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, "Client sent non-existent username");
Send(Encoding.UTF8.GetBytes($"Incorrect username/password.{Common.NewLine}"));
continue;
}
}
if (autoAccountCreate && account == null)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Creating account [{GameState.Username}] automatically for chat gateway client");
Account.CreateStatus status = Account.TryCreate(GameState.Username, inPasswordHash, out account);
if (account == null || status != Account.CreateStatus.Success)
{
var message = "Incorrect username/password";
switch(status)
{
case Account.CreateStatus.AccountExists:
message = "Account already exists"; break;
case Account.CreateStatus.LastCreateInProgress:
message = "Last create in progress"; break;
case Account.CreateStatus.UsernameAdjacentPunctuation:
message = "Username has adjacent punctuation"; break;
case Account.CreateStatus.UsernameBannedWord:
message = "Username contains a banned word"; break;
case Account.CreateStatus.UsernameInvalidChars:
message = "Username contains an invalid character"; break;
case Account.CreateStatus.UsernameShortAlphanumeric:
message = "Username contains too few alphanumeric characters"; break;
case Account.CreateStatus.UsernameTooManyPunctuation:
message = "Username contains too many punctuation characters"; break;
case Account.CreateStatus.UsernameTooShort:
message = "Username is too short"; break;
}
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"[{message}]");
Send(Encoding.UTF8.GetBytes($"{message}.{Common.NewLine}"));
continue;
}
else
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Created account [{account.Get(Account.UsernameKey, GameState.Username)}] automatically for chat gateway client");
}
}
var dbPasswordHash = (byte[])account.Get(Account.PasswordKey, new byte[20]);
if (!inPasswordHash.SequenceEqual(dbPasswordHash))
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Incorrect password for account [{account.Get(Account.UsernameKey, GameState.Username)}]");
Send(Encoding.UTF8.GetBytes($"Incorrect username/password.{Common.NewLine}"));
continue;
}
var flags = (Account.Flags)account.Get(Account.FlagsKey, Account.Flags.None);
if ((flags & Account.Flags.Closed) != 0)
{
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Account [{account.Get(Account.UsernameKey, GameState.Username)}] is closed");
Send(Encoding.UTF8.GetBytes($"Account closed.{Common.NewLine}"));
continue;
}
Logging.WriteLine(Logging.LogLevel.Info, Logging.LogType.Client_Chat, $"Successfully authenticated into account [{account.Get(Account.UsernameKey, GameState.Username)}]");
lock (GameState)
{
GameState.ActiveAccount = account;
GameState.LastLogon = (DateTime)account.Get(Account.LastLogonKey, DateTime.Now);
account.Set(Account.IPAddressKey, RemoteEndPoint.ToString().Split(":")[0]);
account.Set(Account.LastLogonKey, DateTime.Now);
account.Set(Account.PortKey, RemoteEndPoint.ToString().Split(":")[1]);
var serial = 1;
var onlineName = GameState.Username;
while (!Common.ActiveAccounts.TryAdd(onlineName, account)) onlineName = $"{GameState.Username}#{++serial}";
GameState.OnlineName = onlineName;
GameState.Username = (string)account.Get(Account.UsernameKey, GameState.Username);
GameState.LastPing = DateTime.Now;
GameState.LastPong = GameState.LastPing;
GameState.Ping = 0;
GameState.UDPSupported = false; // SID_ENTERCHAT will set NoUDP flag later.
GameState.Statstring = new byte[1];
}
if (!Battlenet.Common.ActiveGameStates.TryAdd(GameState.OnlineName, GameState))
{
Logging.WriteLine(Logging.LogLevel.Error, Logging.LogType.Client_Chat, RemoteEndPoint, $"Failed to add game state to active game state cache");
account.Set(Account.FailedLogonsKey, ((UInt32)account.Get(Account.FailedLogonsKey, (UInt32)0)) + 1);
Battlenet.Common.ActiveAccounts.TryRemove(GameState.OnlineName, out _);
Send(Encoding.UTF8.GetBytes($"Incorrect username/password.{Common.NewLine}"));
continue;
}
using var m1 = new MemoryStream(128);
using var w1 = new BinaryWriter(m1);
{
w1.Write(GameState.OnlineName);
w1.Write(GameState.Statstring);
new SID_ENTERCHAT(m1.ToArray()).Invoke(new MessageContext(this, Protocols.MessageDirection.ClientToServer,
new Dictionary<string, dynamic>{{ "username", GameState.Username }, { "statstring", GameState.Statstring }})
);
}
using var m2 = new MemoryStream(128);
using var w2 = new BinaryWriter(m2);
{
w2.Write((UInt32)SID_JOINCHANNEL.Flags.First);
w2.Write(Product.ProductChannelName(GameState.Product));
new SID_JOINCHANNEL(m2.ToArray()).Invoke(new MessageContext(this, Protocols.MessageDirection.ClientToServer));
}
}
if (string.IsNullOrEmpty(line)) continue;
using var m3 = new MemoryStream(1 + Encoding.UTF8.GetByteCount(line));
using var w3 = new BinaryWriter(m3);
{
w3.Write(line);
new SID_CHATCOMMAND(m3.ToArray()).Invoke(new MessageContext(this, Protocols.MessageDirection.ClientToServer));
}
}
}
protected void ReceiveProtocolGame(SocketAsyncEventArgs e)
{
byte[] newBuffer;
while (ReceiveBuffer.Length > 0)
{
if (ReceiveBuffer.Length < 4) return; // Partial message header
UInt16 messageLen = (UInt16)((ReceiveBuffer[3] << 8) + ReceiveBuffer[2]);
if (ReceiveBuffer.Length < messageLen) return; // Partial message
//byte messagePad = ReceiveBuffer[0]; // This is checked in the Message.FromByteArray() call.
byte messageId = ReceiveBuffer[1];
byte[] messageBuffer = new byte[messageLen - 4];
Buffer.BlockCopy(ReceiveBuffer, 4, messageBuffer, 0, messageLen - 4);
// Pop message off the receive buffer
newBuffer = new byte[ReceiveBuffer.Length - messageLen];
Buffer.BlockCopy(ReceiveBuffer, messageLen, newBuffer, 0, ReceiveBuffer.Length - messageLen);
ReceiveBuffer = newBuffer;
// Push message onto stack
Message message = Message.FromByteArray(messageId, messageBuffer);
if (message is Message)
{
BattlenetGameFrame.Messages.Enqueue(message);
continue;
}
else
{
throw new GameProtocolException(this, $"Received unknown SID_0x{messageId:X2} ({messageLen} bytes)");
}
}
Invoke(e);
}
public void Send(byte[] buffer)
{
if (Socket == null) return;
if (!Socket.Connected) return;
var e = new SocketAsyncEventArgs();
e.Completed += new EventHandler<SocketAsyncEventArgs>(SocketIOCompleted);
e.SetBuffer(buffer, 0, buffer.Length);
e.UserToken = this;
bool willRaiseEvent;
try
{
willRaiseEvent = Socket.SendAsync(e);
}
catch (ObjectDisposedException)
{
return;
}
if (!willRaiseEvent)
{
SocketIOCompleted(this, e);
}
}
void SocketIOCompleted(object sender, SocketAsyncEventArgs e)
{
var clientState = e.UserToken as ClientState;
try
{
// determine which type of operation just completed and call the associated handler
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
clientState.ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
clientState.ProcessSend(e);
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
}
catch (GameProtocolViolationException ex)
{
Logging.WriteLine(Logging.LogLevel.Warning, (Logging.LogType)ProtocolType.ProtocolTypeToLogType(ex.ProtocolType), clientState.RemoteEndPoint, "Protocol violation encountered!" + (ex.Message.Length > 0 ? $" {ex.Message}" : ""));
clientState.Close();
}
catch (Exception ex)
{
Logging.WriteLine(Logging.LogLevel.Warning, Logging.LogType.Client, clientState.RemoteEndPoint, $"{ex.GetType().Name} error encountered!" + (ex.Message.Length > 0 ? $" {ex.Message}" : ""));
clientState.Close();
}
finally
{
if (e.LastOperation == SocketAsyncOperation.Receive)
{
Task.Run(() =>
{
ReceiveAsync();
});
}
}
}
public void SocketIOCompleted_External(object sender, SocketAsyncEventArgs e)
{
var clientState = e.UserToken as ClientState;
if (clientState != this)
{
throw new NotSupportedException();
}
SocketIOCompleted(sender, e);
}
// exists at this level because state split across two component objects
public byte[] GenerateDiabloIIStatstring()
{
var statstring = Product.ToByteArray(GameState.Product);
if (RealmState.ActiveCharacter != null)
{
var partial = new byte[][]
{
"Olympus".ToBytes(),
new byte[] { 0x2C }, //comma
RealmState.ActiveCharacter.Name.ToBytes(),
new byte[] { 0x2C }, //comma
RealmState.ActiveCharacter.Statstring.ToBytes()
}.SelectMany(x => x).ToArray();
statstring = statstring.Concat(partial).ToArray();
}
return statstring;
}
}
}