-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathServerApi.cs
More file actions
587 lines (511 loc) · 18.3 KB
/
ServerApi.cs
File metadata and controls
587 lines (511 loc) · 18.3 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Linq;
using Terraria;
using TerrariaApi.Reporting;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Collections.Immutable;
namespace TerrariaApi.Server
{
// TODO: Maybe re-implement a reload functionality for plugins, but you'll have to load all assemblies into their own
// AppDomain in order to unload them again later. Beware that having them in their own AppDomain might cause threading
// problems as usual locks will only work in their own AppDomains.
public static class ServerApi
{
public const string PluginsPath = "ServerPlugins";
/// <summary>
/// Returns the first value from <see cref="AdditionalPluginsPaths"/> if it exists, otherwise null.
/// </summary>
[Obsolete("Use AdditionalPluginsPaths instead", error: false)]
public static string? AdditionalPluginsPath => AdditionalPluginsPaths.FirstOrDefault();
/// <summary> A list of all plugin paths specified by the -additionalplugins flag. </summary>
public static ImmutableList<string> AdditionalPluginsPaths { get; private set; } = ImmutableList.Create<string>();
public static readonly Version ApiVersion = new Version(2, 1, 0, 0);
private static Main game;
private static readonly Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();
private static readonly List<PluginContainer> plugins = new List<PluginContainer>();
internal static readonly CrashReporter reporter = new CrashReporter();
public static bool IgnoreVersion
{
get;
set;
}
public static string ServerPluginsDirectoryPath
{
get;
private set;
}
public static ReadOnlyCollection<PluginContainer> Plugins
{
get { return new ReadOnlyCollection<PluginContainer>(plugins); }
}
public static HookManager Hooks
{
get;
private set;
}
public static LogWriterManager LogWriter
{
get;
private set;
}
public static ProfilerManager Profiler
{
get;
private set;
}
public static bool IsWorldRunning
{
get;
internal set;
}
public static bool RunningMono { get; private set; }
public static bool ForceUpdate { get; private set; }
public static bool UseAsyncSocketsInMono { get; private set; }
static ServerApi()
{
AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
Dictionary<string, string> args = Utils.ParseArguements(Environment.GetCommandLineArgs());
Hooks = new HookManager();
LogWriter = new LogWriterManager(enabled: !args.ContainsKey("-nolog"));
Profiler = new ProfilerManager();
UseAsyncSocketsInMono = false;
ForceUpdate = false;
Type t = Type.GetType("Mono.Runtime");
RunningMono = (t != null);
Main.SkipAssemblyLoad = true;
}
internal static void Initialize(string[] commandLineArgs, Main game)
{
Profiler.BeginMeasureServerInitTime();
ServerApi.LogWriter.ServerWriteLine(
string.Format("TerrariaApi - Server v{0} started.", ApiVersion), TraceLevel.Verbose);
ServerApi.LogWriter.ServerWriteLine(
"\tCommand line: " + Environment.CommandLine, TraceLevel.Verbose);
ServerApi.LogWriter.ServerWriteLine(
string.Format("\tOS: {0} (64bit: {1})", Environment.OSVersion, Environment.Is64BitOperatingSystem), TraceLevel.Verbose);
ServerApi.LogWriter.ServerWriteLine(
"\tMono: " + RunningMono, TraceLevel.Verbose);
ServerApi.game = game;
HandleCommandLine(commandLineArgs);
ServerPluginsDirectoryPath = Path.Combine(AppContext.BaseDirectory, PluginsPath);
if (!Directory.Exists(ServerPluginsDirectoryPath))
{
string lcDirectoryPath =
Path.Combine(Path.GetDirectoryName(ServerPluginsDirectoryPath), PluginsPath.ToLower());
if (Directory.Exists(lcDirectoryPath))
{
Directory.Move(lcDirectoryPath, ServerPluginsDirectoryPath);
LogWriter.ServerWriteLine("Case sensitive filesystem detected, serverplugins directory has been renamed.", TraceLevel.Warning);
}
else
{
Directory.CreateDirectory(ServerPluginsDirectoryPath);
}
}
// Add assembly resolver instructing it to use the server plugins directory as a search path.
// TODO: Either adding the server plugins directory to PATH or as a privatePath node in the assembly config should do too.
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
LoadPlugins();
}
internal static void DeInitialize()
{
UnloadPlugins();
Profiler.Deatch();
LogWriter.Deatch();
}
internal static void HandleCommandLine(string[] parms)
{
Dictionary<string, string> args = Utils.ParseArguements(parms);
bool isAutoCreating = false;
foreach (KeyValuePair<string, string> arg in args)
{
// Note that the flag -nolog also exists in the constructor, but it can't be here because
// the log writer initializes before this code is run
switch (arg.Key.ToLower())
{
case "-ignoreversion":
{
ServerApi.IgnoreVersion = true;
ServerApi.LogWriter.ServerWriteLine(
"Plugin versions are no longer being regarded, you are on your own! If problems arise, TShock developers will not help you with issues regarding this.",
TraceLevel.Warning);
break;
}
case "-forceupdate":
{
ServerApi.ForceUpdate = true;
ServerApi.LogWriter.ServerWriteLine(
"Forcing game updates regardless of players! This is experimental, and will cause constant CPU usage, you are on your own.",
TraceLevel.Warning);
break;
}
case "-asyncmono":
{
ServerApi.UseAsyncSocketsInMono = true;
ServerApi.LogWriter.ServerWriteLine(
"Forcing Mono to use asynchronous sockets. This is highly experimental and may not work on all versions of Mono.",
TraceLevel.Warning);
break;
}
case "-players":
case "-maxplayers":
{
int playerCount;
if (!Int32.TryParse(arg.Value, out playerCount))
{
ServerApi.LogWriter.ServerWriteLine("Invalid player count. Using 8", TraceLevel.Warning);
playerCount = 8;
}
game.SetNetPlayers(playerCount);
break;
}
case "-pass":
case "-password":
{
Netplay.ServerPassword = arg.Value;
break;
}
case "-worldname":
{
game.SetWorldName(arg.Value);
break;
}
case "-world":
{
if (File.Exists(arg.Value))
{
game.SetWorld(arg.Value, false);
}
else
{
Main.autoGenFileLocation = arg.Value;
Main.ActiveWorldFileData = new Terraria.IO.WorldFileData(arg.Value, false);
}
var full_path = Path.GetFullPath(arg.Value);
Main.WorldPath = Path.GetDirectoryName(full_path);
Main.worldName = Path.GetFileNameWithoutExtension(full_path);
break;
}
case "-motd":
{
game.NewMOTD(arg.Value);
break;
}
case "-banlist":
{
Netplay.BanFilePath = arg.Value;
break;
}
case "-autoshutdown":
{
game.EnableAutoShutdown();
break;
}
case "-secure":
{
Netplay.SpamCheck = true;
break;
}
case "-autocreate":
{
game.autoCreate(arg.Value);
isAutoCreating = true;
break;
}
case "-difficulty":
{
if (!isAutoCreating)
{
LogWriter.ServerWriteLine("Ignoring difficulty command line flag because server is starting in interactive mode without autocreate", TraceLevel.Warning);
continue;
}
// If the arg isn't an integer, or its an incorrect value, we want to ignore it
if (int.TryParse(arg.Value, out int dif))
{
if (dif >= 0 && dif <= 3)
{
Main.GameMode = dif;
}
}
else
{
LogWriter.ServerWriteLine("Unexpected difficulty value. Expected values are 0-3.", TraceLevel.Warning);
}
break;
}
case "-loadlib":
{
game.loadLib(arg.Value);
break;
}
case "-crashdir":
CrashReporter.crashReportPath = arg.Value;
break;
case "-additionalplugins":
AdditionalPluginsPaths = arg.Value.Split(',').ToImmutableList();
break;
}
}
}
/// <summary>
/// Tests to see if a plugin is using an incompatible architecture
/// </summary>
/// <param name="file">File info of the plugin</param>
/// <param name="data">File contents</param>
static void TryCheckArchitecture(FileInfo file, byte[] data)
{
using var ms = new MemoryStream(data);
using var pe = new PEReader(ms);
if (pe.HasMetadata)
{
var currentArch = RuntimeInformation.ProcessArchitecture;
var laa = (pe.PEHeaders.CoffHeader.Characteristics & Characteristics.LargeAddressAware) != 0;
Architecture? asmArch = pe.PEHeaders.CoffHeader.Machine switch
{
Machine.IA64 => Architecture.X64,
Machine.Arm64 => Architecture.Arm64,
Machine.Amd64 => Architecture.X64,
Machine.I386 => laa ? Architecture.X64 : Architecture.X86,
Machine.Arm => Architecture.Arm,
_ => null,
};
if (asmArch is not null && currentArch != asmArch)
LogWriter.ServerWriteLine($"{file.Name} was built for {asmArch} but expected it to be compatible with {currentArch}.", TraceLevel.Error);
}
}
internal static void LoadPlugins()
{
string ignoredPluginsFilePath = Path.Combine(ServerPluginsDirectoryPath, "ignoredplugins.txt");
DangerousPluginDetector detector = new DangerousPluginDetector();
List<string> ignoredFiles = new List<string>();
if (File.Exists(ignoredPluginsFilePath))
ignoredFiles.AddRange(File.ReadAllLines(ignoredPluginsFilePath));
List<FileInfo> fileInfos = new DirectoryInfo(ServerPluginsDirectoryPath).GetFiles("*.dll").ToList();
fileInfos.AddRange(new DirectoryInfo(ServerPluginsDirectoryPath).GetFiles("*.dll-plugin"));
foreach (string additionalPath in AdditionalPluginsPaths)
{
var di = new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, additionalPath));
fileInfos.AddRange(di.GetFiles("*.dll"));
fileInfos.AddRange(di.GetFiles("*.dll-plugin"));
}
Dictionary<TerrariaPlugin, Stopwatch> pluginInitWatches = new Dictionary<TerrariaPlugin, Stopwatch>();
foreach (FileInfo fileInfo in fileInfos)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
if (ignoredFiles.Contains(fileNameWithoutExtension))
{
LogWriter.ServerWriteLine(
string.Format("{0} was ignored from being loaded.", fileNameWithoutExtension), TraceLevel.Verbose);
continue;
}
try
{
Assembly assembly;
// The plugin assembly might have been resolved by another plugin assembly already, so no use to
// load it again, but we do still have to verify it and create plugin instances.
if (!loadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
{
byte[] pe = null;
try
{
var pdb = Path.ChangeExtension(fileInfo.FullName, ".pdb");
var symbols = File.Exists(pdb) ? File.ReadAllBytes(pdb) : null;
assembly = Assembly.Load(pe = File.ReadAllBytes(fileInfo.FullName), symbols);
}
catch (BadImageFormatException)
{
continue;
}
catch(FileLoadException)
{
if (pe is not null)
TryCheckArchitecture(fileInfo, pe);
throw; // don't consume the exception, only care about testing arch here
}
loadedAssemblies.Add(fileNameWithoutExtension, assembly);
}
if (!InvalidateAssembly(assembly, fileInfo.Name))
continue;
if (detector.MaliciousAssembly(assembly))
{
LogWriter.ServerWriteLine(string.Format("Assembly {0} {1} has been identified to the TShock Team as a dangerous plugin and needs to be removed.", assembly.GetName().Name, assembly.GetName().Version), TraceLevel.Error);
LogWriter.ServerWriteLine(string.Format("Continuing to use {0} may damage your server, your data, or your computer. For your safety, this plugin has been disabled.", assembly.GetName().Name), TraceLevel.Error);
continue;
}
foreach (Type type in assembly.GetExportedTypes())
{
if (!type.IsSubclassOf(typeof(TerrariaPlugin)) || !type.IsPublic || type.IsAbstract)
continue;
object[] customAttributes = type.GetCustomAttributes(typeof(ApiVersionAttribute), false);
if (customAttributes.Length == 0)
continue;
if (!IgnoreVersion)
{
var apiVersionAttribute = (ApiVersionAttribute)customAttributes[0];
Version apiVersion = apiVersionAttribute.ApiVersion;
if (apiVersion.Major != ApiVersion.Major || apiVersion.Minor != ApiVersion.Minor)
{
LogWriter.ServerWriteLine(
string.Format("Plugin \"{0}\" is designed for a different Server API version ({1}) and was ignored.",
type.FullName, apiVersion.ToString(2)), TraceLevel.Warning);
continue;
}
}
TerrariaPlugin pluginInstance;
try
{
Stopwatch initTimeWatch = new Stopwatch();
initTimeWatch.Start();
pluginInstance = (TerrariaPlugin)Activator.CreateInstance(type, game);
initTimeWatch.Stop();
pluginInitWatches.Add(pluginInstance, initTimeWatch);
}
catch (Exception ex)
{
// Broken plugins better stop the entire server init.
throw new InvalidOperationException(
string.Format("Could not create an instance of plugin class \"{0}\".", type.FullName), ex);
}
plugins.Add(new PluginContainer(pluginInstance));
}
}
catch (Exception ex)
{
// Broken assemblies / plugins better stop the entire server init.
throw new InvalidOperationException(
string.Format("Failed to load assembly \"{0}\".", fileInfo.Name), ex);
}
}
IOrderedEnumerable<PluginContainer> orderedPluginSelector =
from x in Plugins
orderby x.Plugin.Order, x.Plugin.Name
select x;
foreach (PluginContainer current in orderedPluginSelector)
{
Stopwatch initTimeWatch = pluginInitWatches[current.Plugin];
initTimeWatch.Start();
try
{
current.Initialize();
}
catch (Exception ex)
{
// Broken plugins better stop the entire server init.
throw new InvalidOperationException(string.Format(
"Plugin \"{0}\" has thrown an exception during initialization.", current.Plugin.Name), ex);
}
initTimeWatch.Stop();
LogWriter.ServerWriteLine(string.Format(
"Plugin {0} v{1} (by {2}) initiated.", current.Plugin.Name, current.Plugin.Version, current.Plugin.Author),
TraceLevel.Info);
}
if (Profiler.WrappedProfiler != null)
{
foreach (var pluginWatchPair in pluginInitWatches)
{
TerrariaPlugin plugin = pluginWatchPair.Key;
Stopwatch initTimeWatch = pluginWatchPair.Value;
Profiler.InputPluginInitTime(plugin, initTimeWatch.Elapsed);
}
}
}
internal static void UnloadPlugins()
{
var pluginUnloadWatches = new Dictionary<PluginContainer, Stopwatch>();
foreach (PluginContainer pluginContainer in plugins)
{
Stopwatch unloadWatch = new Stopwatch();
unloadWatch.Start();
try
{
pluginContainer.DeInitialize();
}
catch (Exception ex)
{
LogWriter.ServerWriteLine(string.Format(
"Plugin \"{0}\" has thrown an exception while being deinitialized:\n{1}", pluginContainer.Plugin.Name, ex),
TraceLevel.Error);
}
unloadWatch.Stop();
pluginUnloadWatches.Add(pluginContainer, unloadWatch);
}
foreach (PluginContainer pluginContainer in plugins)
{
Stopwatch unloadWatch = pluginUnloadWatches[pluginContainer];
unloadWatch.Start();
try
{
pluginContainer.Dispose();
}
catch (Exception ex)
{
LogWriter.ServerWriteLine(string.Format(
"Plugin \"{0}\" has thrown an exception while being disposed:\n{1}", pluginContainer.Plugin.Name, ex),
TraceLevel.Error);
}
unloadWatch.Stop();
Profiler.InputPluginUnloadTime(pluginContainer.Plugin, unloadWatch.Elapsed);
}
}
private static Assembly ResolveAssembly(string pluginsPath, string fileName)
{
try
{
string pluginPath = Path.Combine(pluginsPath, fileName + ".dll");
if (!File.Exists(pluginPath)) return null;
if (loadedAssemblies.TryGetValue(fileName, out var assembly)) return assembly;
var pdbPath = Path.ChangeExtension(pluginPath, ".pdb");
assembly = Assembly.Load(File.ReadAllBytes(pluginPath),
File.Exists(pdbPath) ? File.ReadAllBytes(pdbPath) : null);
// We just do this to return a proper error message incase this is a resolved plugin assembly
// referencing an old TerrariaServer version.
if (!InvalidateAssembly(assembly, fileName))
throw new InvalidOperationException(
"The assembly is referencing a version of TerrariaServer prior 1.14.");
loadedAssemblies.Add(fileName, assembly);
return assembly;
}
catch (Exception ex)
{
LogWriter.ServerWriteLine(
$"Error on resolving assembly \"{fileName}.dll\":\n{ex}",
TraceLevel.Error);
}
return null;
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string fileName = args.Name.Split(',')[0];
List<string> pluginsPaths = [ServerPluginsDirectoryPath, ..AdditionalPluginsPaths];
foreach (string pluginsPath in pluginsPaths)
{
Assembly assembly = ResolveAssembly(pluginsPath, fileName);
if (assembly != null) return assembly;
}
return null;
}
// Many types have changed with 1.14 and thus we won't even be able to check the ApiVersionAttribute of
// plugin classes of assemblies targeting a TerrariaServer prior 1.14 as they can not be loaded at all.
// We work around this by checking the referenced assemblies, if we notice a reference to the old
// TerrariaServer assembly, we expect the plugin assembly to be outdated.
private static bool InvalidateAssembly(Assembly assembly, string fileName)
{
AssemblyName[] referencedAssemblies = assembly.GetReferencedAssemblies();
AssemblyName terrariaServerReference = referencedAssemblies.FirstOrDefault(an => an.Name == "TerrariaServer");
if (terrariaServerReference != null && terrariaServerReference.Version == new Version(0, 0, 0, 0))
{
LogWriter.ServerWriteLine(
string.Format("Plugin assembly \"{0}\" was compiled for a Server API version prior 1.14 and was ignored.",
fileName), TraceLevel.Warning);
return false;
}
return true;
}
}
}