-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
520 lines (430 loc) · 21.1 KB
/
Program.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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Newtonsoft.Json.Linq;
using PInvoke;
namespace NetSplitter
{
public enum SplitterMode
{
Tcp,
Http
}
public enum BalancingMode
{
Random,
IPHash,
LeastConn
}
class DefaultLogger
{
public bool IsDebugEnabled => true;
public bool IsErrorEnabled => true;
public bool IsFatalEnabled => true;
public bool IsInfoEnabled => true;
public bool IsWarnEnabled => true;
public void Debug(object message)
{
Log("[D] " + message);
}
public void Debug(object message, Exception exception) => Debug((message.ToString() + " " + exception));
public void DebugFormat(string format, object arg0) => Debug(string.Format(format, arg0));
public void DebugFormat(string format, params object[] args) => Debug(string.Format(format, args));
public void DebugFormat(IFormatProvider provider, string format, params object[] args) => Debug(string.Format(provider, format, args));
public void DebugFormat(string format, object arg0, object arg1) => Debug(string.Format(format, arg0, arg1));
public void DebugFormat(string format, object arg0, object arg1, object arg2) => Debug(string.Format(format, arg0, arg1, arg2));
public void Error(object message)
{
Log("[E] " + message);
}
public void Error(object message, Exception exception) => Error((message.ToString() + " " + exception));
public void ErrorFormat(string format, object arg0) => Error(string.Format(format, arg0));
public void ErrorFormat(string format, params object[] args) => Error(string.Format(format, args));
public void ErrorFormat(IFormatProvider provider, string format, params object[] args) => Error(string.Format(provider, format, args));
public void ErrorFormat(string format, object arg0, object arg1) => Error(string.Format(format, arg0, arg1));
public void ErrorFormat(string format, object arg0, object arg1, object arg2) => Error(string.Format(format, arg0, arg1, arg2));
public void Fatal(object message)
{
Log("[F] " + message);
}
public void Fatal(object message, Exception exception) => Fatal((message.ToString() + " " + exception));
public void FatalFormat(string format, object arg0) => Fatal(string.Format(format, arg0));
public void FatalFormat(string format, params object[] args) => Fatal(string.Format(format, args));
public void FatalFormat(IFormatProvider provider, string format, params object[] args) => Fatal(string.Format(provider, format, args));
public void FatalFormat(string format, object arg0, object arg1) => Fatal(string.Format(format, arg0, arg1));
public void FatalFormat(string format, object arg0, object arg1, object arg2) => Fatal(string.Format(format, arg0, arg1, arg2));
public void Info(object message)
{
Log("[I] " + message);
}
public void Info(object message, Exception exception) => Info((message.ToString() + " " + exception));
public void InfoFormat(string format, object arg0) => Info(string.Format(format, arg0));
public void InfoFormat(string format, params object[] args) => Info(string.Format(format, args));
public void InfoFormat(IFormatProvider provider, string format, params object[] args) => Info(string.Format(provider, format, args));
public void InfoFormat(string format, object arg0, object arg1) => Info(string.Format(format, arg0, arg1));
public void InfoFormat(string format, object arg0, object arg1, object arg2) => Info(string.Format(format, arg0, arg1, arg2));
public void Warn(object message)
{
Log("[W] " + message);
}
public void Warn(object message, Exception exception) => Warn((message.ToString() + " " + exception));
public void WarnFormat(string format, object arg0) => Warn(string.Format(format, arg0));
public void WarnFormat(string format, params object[] args) => Warn(string.Format(format, args));
public void WarnFormat(IFormatProvider provider, string format, params object[] args) => Warn(string.Format(provider, format, args));
public void WarnFormat(string format, object arg0, object arg1) => Warn(string.Format(format, arg0, arg1));
public void WarnFormat(string format, object arg0, object arg1, object arg2) => Warn(string.Format(format, arg0, arg1, arg2));
private object mutex = new object();
private void Log(string message)
{
DateTime now = DateTime.Now;
lock (mutex)
{
Console.WriteLine(string.Format("[{0:HH:mm:ss}]{1}", now, message));
try
{
File.AppendAllText("NetSplitter.log", string.Format("[{0:dd/MM} {0:HH:mm:ss}]{1}{2}", now, message, Environment.NewLine));
}
catch { }
}
}
}
public static class Program
{
private const int defaultBufferSize = 1 * 1024 * 1024;
private const int defaultTimeout = 1000;
private const string settingsFileName = "Settings.json";
public static SplitterMode SplitterMode { get; private set; } = SplitterMode.Tcp;
public static BalancingMode BalancingMode { get; private set; } = BalancingMode.LeastConn;
public static ushort Port { get; private set; } = 0;
public static ulong BufferSize { get; private set; } = defaultBufferSize;
public static TimeSpan Timeout { get; private set; } = TimeSpan.FromMilliseconds(defaultTimeout);
private static readonly DefaultLogger logger = new DefaultLogger();
private static FileSystemWatcher fileSystemWatcher;
private static Kernel32.HandlerRoutine consoleCtrlHandler;
private static Dictionary<HostInfo, double> balancingTargets = new Dictionary<HostInfo, double>();
private static List<HostInfo> cloningTargets = new List<HostInfo>();
private static Splitter splitter;
private static bool running = true;
private static double balancingTargetsTotal;
private static Random balancingTargetsRandom = new Random();
private static ConcurrentDictionary<HostInfo, int> currentBalancing = new ConcurrentDictionary<HostInfo, int>();
private static ConcurrentDictionary<HostInfo, HostInfo> activeConnections = new ConcurrentDictionary<HostInfo, HostInfo>();
static void Main(string[] args)
{
Version version = Assembly.GetExecutingAssembly().GetName().Version;
Console.Title = $"NetSplitter {version}";
logger.Info($"--- NetSplitter {Assembly.GetExecutingAssembly().GetName().Version} ---");
logger.Debug("");
// Monitor settings file changes
fileSystemWatcher = new FileSystemWatcher(Environment.CurrentDirectory, settingsFileName);
fileSystemWatcher.Changed += (s, e) => OnReloadConfiguration();
fileSystemWatcher.Created += (s, e) => OnReloadConfiguration();
fileSystemWatcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.FileName;
fileSystemWatcher.EnableRaisingEvents = true;
OnReloadConfiguration();
if (Port == 0 || splitter == null)
{
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
return;
}
// Listen to control console handler
consoleCtrlHandler = eventType =>
{
if (running)
{
logger.Warn("Stopping NetSplitter, waiting for active connections to stop. Use Ctrl+C again to force quit");
running = false;
splitter.Stop();
return false;
}
else
{
Environment.Exit(0);
return true;
}
};
Console.CancelKeyPress += (s, e) => e.Cancel = !consoleCtrlHandler(0);
//if (Environment.OSVersion.Platform == PlatformID.Win32NT)
// Kernel32.SetConsoleCtrlHandler(consoleCtrlHandler, true);
// Wait for all connections to stop
while (running || activeConnections.Count > 0)
Thread.Sleep(100);
}
private static void OnReloadConfiguration()
{
if (!running)
return;
JObject settingsObject;
// Load JSON settings object
try
{
if (!File.Exists(settingsFileName))
throw new Exception($"Could not find {settingsFileName} file");
string settingsJson;
using (FileStream fileStream = File.Open(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader streamReader = new StreamReader(fileStream))
settingsJson = streamReader.ReadToEnd();
if (string.IsNullOrWhiteSpace(settingsJson))
return;
settingsObject = JObject.Parse(settingsJson);
}
catch (Exception ex)
{
logger.Warn($"Error while reloading {settingsFileName}. Last settings will be kept. " + ex);
return;
}
try
{
// Parse settings
Dictionary<HostInfo, double> newBalancingTargets = new Dictionary<HostInfo, double>();
JArray balancingArray = settingsObject["Balancing"] as JArray;
if (balancingArray != null)
{
foreach (JObject targetObject in balancingArray)
{
string hostname = (targetObject["Hostname"] as JValue)?.Value<string>();
ushort? port = (targetObject["Port"] as JValue)?.Value<ushort>();
double weight = (targetObject["Weight"] as JValue)?.Value<double>() ?? 1;
bool enabled = (targetObject["Enabled"] as JValue)?.Value<bool>() ?? true;
if (!enabled)
continue;
if (string.IsNullOrEmpty(hostname) || (port ?? 0) == 0)
throw new FormatException("One balancing target is not formatted correctly");
newBalancingTargets.Add(new HostInfo(hostname, port.Value), weight);
}
}
if (newBalancingTargets.Count == 0)
logger.Info("There are no balancing target defined. All connections will be skipped");
List<HostInfo> newCloningTargets = new List<HostInfo>();
JArray cloningArray = settingsObject["Cloning"] as JArray;
if (cloningArray != null)
{
foreach (JObject targetObject in cloningArray)
{
string hostname = (targetObject["Hostname"] as JValue)?.Value<string>();
ushort? port = (targetObject["Port"] as JValue)?.Value<ushort>();
bool enabled = (targetObject["Enabled"] as JValue)?.Value<bool>() ?? true;
if (!enabled)
continue;
if (string.IsNullOrEmpty(hostname) || (port ?? 0) == 0)
throw new FormatException("One cloning target is not formatted correctly");
newCloningTargets.Add(new HostInfo(hostname, port.Value));
}
}
settingsObject = settingsObject["Settings"] as JObject;
if (settingsObject == null)
throw new Exception("Settings must be defined");
ushort newPort = (settingsObject["Port"] as JValue)?.Value<ushort>() ?? 0;
ulong newBufferSize = (settingsObject["BufferSize"] as JValue)?.Value<ulong>() ?? defaultBufferSize;
int newTimeoutMs = (settingsObject["Timeout"] as JValue)?.Value<int>() ?? defaultTimeout;
if (newPort == 0)
throw new Exception("A listening port must be defined");
string newSplitterModeString = (settingsObject["Mode"] as JValue)?.Value<string>();
SplitterMode newSplitterMode;
if (string.IsNullOrEmpty(newSplitterModeString))
{
if (newPort == 80 || newPort == 1080 || newPort == 8080)
newSplitterMode = SplitterMode.Http;
else
newSplitterMode = SplitterMode.Tcp;
}
else if (!Enum.TryParse(newSplitterModeString, true, out newSplitterMode))
throw new Exception("Invalid splitter mode specified");
string newBalancingModeString = (settingsObject["Balancing"] as JValue)?.Value<string>();
BalancingMode newBalancingMode;
if (string.IsNullOrEmpty(newBalancingModeString))
{
if (newSplitterMode == SplitterMode.Http)
newBalancingMode = BalancingMode.IPHash;
else
newBalancingMode = BalancingMode.LeastConn;
}
else if (!Enum.TryParse(newBalancingModeString, true, out newBalancingMode))
throw new Exception("Invalid balancing mode specified");
// Apply settings if needed
if (newBalancingMode != BalancingMode)
{
BalancingMode = newBalancingMode;
if (Port != 0)
logger.Info($"Setting balancing mode: {BalancingMode}");
}
if (newBufferSize != BufferSize)
{
BufferSize = newBufferSize;
logger.Info($"Setting buffer size: {BufferSize}");
}
if (newTimeoutMs != (int)Timeout.TotalMilliseconds)
{
Timeout = TimeSpan.FromMilliseconds(newTimeoutMs);
logger.Info($"Setting timeout: {Timeout}");
}
Func<Dictionary<HostInfo, double>, int> balancingTargetHasher = b =>
{
int hash = 0x12345678;
foreach (var pair in b)
{
hash <<= 8;
hash ^= pair.Key.GetHashCode();
hash <<= 8;
hash ^= pair.Value.GetHashCode();
}
return hash;
};
if (balancingTargetHasher(balancingTargets) != balancingTargetHasher(newBalancingTargets))
{
Interlocked.Exchange(ref balancingTargets, newBalancingTargets);
logger.Info($"{newBalancingTargets.Count} balancing targets:");
foreach (var pair in newBalancingTargets)
logger.Info($"- {pair.Key} (Weight: {pair.Value})");
balancingTargetsTotal = newBalancingTargets.Sum(p => p.Value);
foreach (var pair in newBalancingTargets)
currentBalancing.GetOrAdd(pair.Key, 0);
}
Func<List<HostInfo>, int> cloningTargetHasher = b =>
{
int hash = 0x07654321;
foreach (HostInfo hostInfo in b)
{
hash <<= 8;
hash ^= hostInfo.GetHashCode();
}
return hash;
};
if (cloningTargetHasher(cloningTargets) != cloningTargetHasher(newCloningTargets))
{
Interlocked.Exchange(ref cloningTargets, newCloningTargets);
logger.Info($"{newCloningTargets.Count} cloning targets");
foreach (HostInfo hostInfo in newCloningTargets)
logger.Info($"- {hostInfo}");
}
if (newPort != Port || newSplitterMode != SplitterMode)
{
logger.Info($"Starting {newSplitterMode} splitter on port {newPort}");
splitter?.Stop();
try
{
Splitter newSplitter = null;
switch (newSplitterMode)
{
case SplitterMode.Tcp: newSplitter = new TcpSplitter(newPort, TargetBalancer, TargetCloner); break;
case SplitterMode.Http: newSplitter = new HttpSplitter(newPort, TargetBalancer, TargetCloner); break;
}
splitter = newSplitter;
}
catch
{
splitter?.Start();
throw;
}
splitter.HostConnected += Splitter_HostConnected;
splitter.HostDisconnected += Splitter_HostDisconnected;
try
{
splitter.Start();
}
catch (Exception ex)
{
logger.Warn($"Error while starting listener. " + ex);
return;
}
Port = newPort;
SplitterMode = newSplitterMode;
}
}
catch (Exception ex)
{
if (Port == 0)
{
logger.Warn($"Error while parsing {settingsFileName}. Exiting. " + ex);
}
else
{
logger.Warn($"Error while parsing {settingsFileName}. Last settings will be kept. " + ex);
}
return;
}
}
private static void Splitter_HostConnected(object sender, HostInfo source)
{
}
private static void Splitter_HostDisconnected(object sender, HostInfo source)
{
HostInfo target;
if (!activeConnections.TryRemove(source, out target))
return;
int targetConnections;
lock (currentBalancing)
{
targetConnections = currentBalancing[target] - 1;
currentBalancing[target] = targetConnections;
}
logger.Info($"{source} disconnected from {target} ({activeConnections.Count} total, {targetConnections} on target)");
}
private static HostInfo TargetBalancer(HostInfo source)
{
HostInfo target = null;
if (balancingTargets.Count == 1)
{
target = balancingTargets.Keys.First();
}
else if (balancingTargets.Count > 1)
{
Func<Random, HostInfo> randomSelector = random =>
{
double value = random.NextDouble() * balancingTargetsTotal;
double current = 0;
foreach (var pair in balancingTargets)
{
current += pair.Value;
if (value <= current)
return pair.Key;
}
return null;
};
if (BalancingMode == BalancingMode.Random)
{
target = randomSelector(balancingTargetsRandom);
}
else if (BalancingMode == BalancingMode.IPHash)
{
int hash = source.Hostname.GetHashCode();
Random random = new Random(hash);
target = randomSelector(random);
}
else if (BalancingMode == BalancingMode.LeastConn)
{
target = balancingTargets.OrderBy(p => currentBalancing[p.Key] / p.Value).FirstOrDefault().Key;
}
}
if (target != null)
{
activeConnections[source] = target;
int targetConnections;
lock (currentBalancing)
{
targetConnections = currentBalancing[target] + 1;
currentBalancing[target] = targetConnections;
}
logger.Info($"{source} connected to {target} ({activeConnections.Count} total, {targetConnections} on target)");
}
else
{
logger.Info($"No balancing target, {source} will be skipped");
}
return target;
}
private static IEnumerable<HostInfo> TargetCloner(HostInfo source)
{
return cloningTargets;
}
}
}