-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
212 lines (177 loc) · 7.38 KB
/
Program.cs
File metadata and controls
212 lines (177 loc) · 7.38 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
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Minechat.Server.Connection;
using Minechat.Server.Logging;
using Minechat.Server.Protocols;
using Serilog;
using Serilog.Events;
namespace Minechat.Server;
class Program
{
private const string CertFile = "server.pfx";
private const string CertPassword = "minechat";
private static readonly ConcurrentBag<ClientConnection> _connections = [];
private static CancellationTokenSource? _cts;
private static void BroadcastChatMessage(ChatMessagePayload payload, string? excludeConnectionId)
{
foreach (var conn in _connections)
{
if (conn.IsAuthenticated && (excludeConnectionId == null || conn.ConnectionId != excludeConnectionId))
{
try
{
var formatToUse = SelectFormatForClient(payload.Format, conn.SupportedFormats, conn.PreferredFormat);
var transformedPayload = new ChatMessagePayload(formatToUse, payload.Content);
conn.SendPacket(PacketTypes.CHAT_MESSAGE, transformedPayload);
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to send to connection {ConnectionId}", conn.ConnectionId);
}
}
}
}
private static string SelectFormatForClient(string originalFormat, string[]? supportedFormats, string? preferredFormat)
{
if (supportedFormats == null || supportedFormats.Length == 0)
return "components";
var formats = supportedFormats.ToHashSet();
if (preferredFormat != null && formats.Contains(preferredFormat))
return preferredFormat;
if (formats.Contains(originalFormat))
return originalFormat;
if (formats.Contains("commonmark"))
return "commonmark";
if (formats.Contains("components"))
return "components";
return "components";
}
static async Task Main(string[] args)
{
var port = args.Length > 0 && int.TryParse(args[0], out var p) ? p : ServerConfig.DEFAULT_PORT;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
ServerConfig.LOG_FILE_PATH,
rollingInterval: RollingInterval.Day,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
Log.Information("MineChat Echo Test Server v1.0.0");
var chatLogger = new ChatLogger();
_cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Log.Information("Shutdown signal received, closing connections...");
_cts.Cancel();
};
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
Log.Information("Process exiting, closing all connections...");
foreach (var conn in _connections)
{
conn.Close();
}
Log.CloseAndFlush();
};
var serverCert = GetOrCreateCertificate();
var listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Log.Information("Listening on TCP {Port} with TLS...", port);
Log.Information("Press Ctrl+C to stop");
try
{
while (!_cts.Token.IsCancellationRequested)
{
try
{
var client = await listener.AcceptTcpClientAsync(_cts.Token);
if (_connections.Count >= ServerConfig.MAX_CLIENTS)
{
Log.Warning("Max clients {MaxClients} reached, rejecting new connection from {RemoteEndPoint}",
ServerConfig.MAX_CLIENTS, client.Client.RemoteEndPoint);
client.Close();
continue;
}
Log.Information("Client connected: {RemoteEndPoint}", client.Client.RemoteEndPoint);
var connectionId = Guid.NewGuid().ToString("N")[..8];
var connection = new ClientConnection(client, serverCert, connectionId, _cts.Token,
TimeSpan.FromSeconds(ServerConfig.KEEP_ALIVE_TIMEOUT_SECONDS),
ServerConfig.PING_INTERVAL_SECONDS,
ServerConfig.CONNECTION_TIMEOUT_SECONDS,
chatLogger,
BroadcastChatMessage);
_connections.Add(connection);
_ = connection.RunAsync().ContinueWith(t =>
{
_connections.TryTake(out var _);
if (t.IsFaulted)
{
Log.Error(t.Exception, "Connection {ConnectionId} failed", connectionId);
}
});
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Log.Error(ex, "Accept error");
}
}
}
finally
{
Log.Information("Server shutting down...");
foreach (var conn in _connections)
{
conn.SendSystemDisconnect(SystemDisconnectReason.SHUTDOWN, "Server shutting down");
conn.Close();
}
listener.Stop();
Log.CloseAndFlush();
}
}
static X509Certificate2 GetOrCreateCertificate()
{
if (File.Exists(CertFile))
{
return new X509Certificate2(CertFile, CertPassword);
}
Log.Information("Generating self-signed certificate...");
var distinguishedName = new X500DistinguishedName("CN=localhost");
using var rsa = RSA.Create(2048);
var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment,
critical: true
)
);
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") },
critical: false
)
);
var sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName("localhost");
sanBuilder.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(sanBuilder.Build());
var utcNow = DateTimeOffset.UtcNow;
var certificate = request.CreateSelfSigned(
utcNow.AddMinutes(-5),
utcNow.AddYears(1)
);
var pfxBytes = certificate.Export(X509ContentType.Pfx, CertPassword);
File.WriteAllBytes(CertFile, pfxBytes);
Log.Information("Certificate saved to {CertFile}", CertFile);
return new X509Certificate2(CertFile, CertPassword);
}
}