forked from elfinlazz/aura-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChannelServer.cs
429 lines (349 loc) · 11.4 KB
/
ChannelServer.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
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
using Aura.Channel.Database;
using Aura.Channel.Network;
using Aura.Channel.Network.Handlers;
using Aura.Channel.Network.Sending;
using Aura.Channel.Scripting;
using Aura.Channel.Skills;
using Aura.Channel.Util;
using Aura.Channel.Util.Configuration;
using Aura.Channel.World;
using Aura.Channel.World.Weather;
using Aura.Mabi.Network;
using Aura.Shared;
using Aura.Shared.Database;
using Aura.Shared.Network;
using Aura.Shared.Network.Crypto;
using Aura.Shared.Util;
using Aura.Shared.Util.Configuration;
using System;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Aura.Mabi;
using Aura.Mabi.Const;
using Aura.Channel.World.Guilds;
using Aura.Channel.World.GameEvents;
namespace Aura.Channel
{
public class ChannelServer : ServerMain
{
public static readonly ChannelServer Instance = new ChannelServer();
/// <summary>
/// Milliseconds between connection tries.
/// </summary>
private const int LoginTryTime = 10 * 1000;
private bool _running;
/// <summary>
/// Instance of the actual server component.
/// </summary>
public DefaultServer<ChannelClient> Server { get; protected set; }
/// <summary>
/// List of servers and channels.
/// </summary>
public ServerInfoManager ServerList { get; private set; }
/// <summary>
/// Configuration
/// </summary>
public ChannelConf Conf { get; private set; }
/// <summary>
/// Database
/// </summary>
public ChannelDb Database { get; private set; }
/// <summary>
/// Client connecting to the login server.
/// </summary>
public InternalClient LoginServer { get; private set; }
public GmCommandManager CommandProcessor { get; private set; }
public ChannelConsoleCommands ConsoleCommands { get; private set; }
public ScriptManager ScriptManager { get; private set; }
public SkillManager SkillManager { get; private set; }
public EventManager Events { get; private set; }
public WeatherManager Weather { get; private set; }
public PartyManager PartyManager { get; private set; }
public GuildManager GuildManager { get; private set; }
public GameEventManager GameEventManager { get; private set; }
public WorldManager World { get; private set; }
public bool ShuttingDown { get; private set; }
private Timer Timer { get; set; }
private ChannelServer()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
this.Server = new DefaultServer<ChannelClient>();
this.Server.Handlers = new ChannelServerHandlers();
this.Server.Handlers.AutoLoad();
this.Server.ClientDisconnected += this.OnClientDisconnected;
this.ServerList = new ServerInfoManager();
this.CommandProcessor = new GmCommandManager();
this.ConsoleCommands = new ChannelConsoleCommands();
this.ScriptManager = new ScriptManager();
this.SkillManager = new SkillManager();
this.Events = new EventManager();
this.Weather = new WeatherManager();
this.PartyManager = new PartyManager();
this.GuildManager = new GuildManager();
this.GameEventManager = new GameEventManager();
this.Timer = new Timer(new TimerCallback(ShutdownTimerDone));
}
/// <summary>
/// Loads all necessary components and starts the server.
/// </summary>
public void Run()
{
if (_running)
throw new Exception("Server is already running.");
CliUtil.WriteHeader("Channel Server", ConsoleColor.DarkGreen);
CliUtil.LoadingTitle();
this.NavigateToRoot();
// Conf
this.LoadConf(this.Conf = new ChannelConf());
// Database
this.InitDatabase(this.Database = new ChannelDb(), this.Conf);
// Data
this.LoadData(DataLoad.ChannelServer, false);
// Localization
this.LoadLocalization(this.Conf);
// World
this.InitializeWorld();
// Skills
this.LoadSkills();
// Scripts
this.LoadScripts();
// Weather
this.Weather.Initialize();
// Autoban
if (this.Conf.Autoban.Enabled)
this.Events.SecurityViolation += (e) => Autoban.Incident(e.Client, e.Level, e.Report, e.StackReport);
// Start
this.Server.Start(this.Conf.Channel.ChannelPort);
// Inter
this.ConnectToLogin(true);
this.StartStatusUpdateTimer();
CliUtil.RunningTitle();
_running = true;
// Commands
this.ConsoleCommands.Wait();
}
/// <summary>
/// Tries to connect to login server, keeps trying every 10 seconds
/// till there is a success. Blocking.
/// </summary>
public void ConnectToLogin(bool firstTime)
{
if (this.LoginServer != null && this.LoginServer.State == ClientState.LoggedIn)
throw new Exception("Channel already connected to login server.");
Log.WriteLine();
if (firstTime)
Log.Info("Trying to connect to login server at {0}:{1}...", ChannelServer.Instance.Conf.Channel.LoginHost, ChannelServer.Instance.Conf.Channel.LoginPort);
else
{
Log.Info("Trying to re-connect to login server in {0} seconds.", LoginTryTime / 1000);
Thread.Sleep(LoginTryTime);
}
var success = false;
while (!success)
{
try
{
if (this.LoginServer != null && this.LoginServer.State != ClientState.Dead)
this.LoginServer.Kill();
this.LoginServer = new InternalClient();
this.LoginServer.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.LoginServer.Socket.Connect(ChannelServer.Instance.Conf.Channel.LoginHost, ChannelServer.Instance.Conf.Channel.LoginPort);
var buffer = new byte[255];
// Recv Seed, send back empty packet to get done with the challenge.
this.LoginServer.Socket.Receive(buffer);
this.LoginServer.Crypto = new MabiCrypto(BitConverter.ToUInt32(buffer, 0), false);
this.LoginServer.Send(Packet.Empty());
// Challenge end
this.LoginServer.Socket.Receive(buffer);
// Inject login server into normal data receiving.
this.Server.AddReceivingClient(this.LoginServer);
// Identify
this.LoginServer.State = ClientState.LoggingIn;
success = true;
Send.Internal_ServerIdentify();
}
catch (Exception ex)
{
Log.Error("Unable to connect to login server. ({0})", ex.Message);
Log.Info("Trying again in {0} seconds.", LoginTryTime / 1000);
Thread.Sleep(LoginTryTime);
}
}
Log.Info("Connection to login server at '{0}' established.", this.LoginServer.Address);
Log.WriteLine();
}
/// <summary>
/// Calculates the state of the channel.
/// </summary>
/// <remarks>
/// When calculating the <see cref="ChannelState"/> we take into account
/// whether the server is running as well as if it is in Maintenance.
/// </remarks>
/// <returns></returns>
public ChannelState CalculateChannelState()
{
// Just in case this gets called
if (this.ShuttingDown)
return ChannelState.Maintenance;
var current = this.World.CountPlayers();
var max = this.Conf.Channel.MaxUsers;
if (max == 0)
{
Log.Warning("Max user count was zero, falling back to Normal.");
// Fallback value
return ChannelState.Normal;
}
double stress = (current / max) * 100;
if (stress >= 40 && stress <= 70)
return ChannelState.Busy;
if (stress > 70 && stress <= 95)
return ChannelState.Full;
if (stress > 95)
return ChannelState.Bursting;
return ChannelState.Normal;
}
private void OnClientDisconnected(ChannelClient client)
{
if (client == this.LoginServer)
this.ConnectToLogin(false);
}
/// <summary>
/// Handler for unhandled exceptions.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Log.Error("Oh no! Ferghus escaped his memory block and infected the rest of the server!");
Log.Error("Aura has encountered an unexpected and unrecoverable error. We're going to try to save as much as we can.");
}
catch { }
try
{
this.Server.Stop();
}
catch { }
try
{
// save the world
}
catch { }
try
{
Log.Exception((Exception)e.ExceptionObject);
Log.Status("Closing server.");
}
catch { }
CliUtil.Exit(1, false);
}
private void StartStatusUpdateTimer()
{
this.Events.MinutesTimeTick += (_) =>
{
if (this.LoginServer == null || this.LoginServer.State != ClientState.LoggedIn || this.ShuttingDown)
return;
Send.Internal_ChannelStatus();
};
}
private void InitializeWorld()
{
Log.Info("Initializing world...");
this.World = new WorldManager();
this.World.Initialize();
this.PartyManager.Initialize();
this.GuildManager.Initialize();
this.GameEventManager.Initialize();
Log.Info(" done loading {0} regions.", this.World.Count);
Log.Info(" done loading {0} guilds.", this.GuildManager.Count);
}
private void LoadScripts()
{
this.ScriptManager.Init();
this.ScriptManager.Load();
}
private void LoadSkills()
{
this.SkillManager.AutoLoad();
}
public override void InitDatabase(AuraDb db, BaseConf conf)
{
base.InitDatabase(db, conf);
// If items end up with temp ids in the db we'd get entity ids
// that exist twice, when creating new temps later on.
if (ChannelServer.Instance.Database.TmpItemsExist())
{
Log.Warning("InitDatabase: Found items with temp entity ids.");
// TODO: clean up dbs
}
}
/// <summary>
/// Shutdown procedure for the current channel.
/// </summary>
/// <param name="time">The amount of time in seconds until shutdown.</param>
public void Shutdown(int time)
{
this.ShuttingDown = true;
var channel = this.ServerList.GetChannel(this.Conf.Channel.ChannelServer, this.Conf.Channel.ChannelName);
if (channel == null)
{
Log.Warning("Unregistered channel.");
}
else
{
channel.State = ChannelState.Maintenance;
Send.Internal_ChannelStatus();
Log.Info("{0} switched to maintenance.", this.Conf.Channel.ChannelName);
}
var notice = Localization.GetPlural(
"The server will be brought down for maintenance in {0} second. Please log out safely before then.",
"The server will be brought down for maintenance in {0} seconds. Please log out safely before then.",
time
);
Send.Internal_Broadcast(string.Format(notice, time));
Send.RequestClientDisconnect(time);
// Add a few seconds, as `time` is the moment when all clients
// send their DC request, because of RequestClientDisconnect.
// The channel should shutdown *after* that's done. 10 seconds
// should be plenty.
time += 10;
Log.Info("Shutting down in {0} seconds...", time);
this.Timer.Change(time * 1000, Timeout.Infinite);
}
private void ShutdownTimerDone(object timer)
{
((Timer)timer).Dispose();
// Kill clients
this.KillConnectedClients();
// Save global variables
this.Database.SaveVars("Aura System", 0, this.ScriptManager.GlobalVars.Perm);
CliUtil.Exit(0, false);
}
/// <summary>
/// Kills all clients currently connected to the channel.
/// </summary>
private void KillConnectedClients()
{
// Grab a copy of the list of users still currently logged in
var shutdownClientList = this.Server.Clients.ToList<ChannelClient>();
// Kill all clients still logged in
foreach (var user in shutdownClientList)
{
try
{
if (user.State == ClientState.LoggedIn)
user.Kill();
}
catch (Exception e)
{
Log.Exception(e, "Error killing client.");
}
}
}
}
}