-
Notifications
You must be signed in to change notification settings - Fork 21
/
HttpServer.cs
330 lines (306 loc) · 12 KB
/
HttpServer.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
using DV.Utils;
using DV;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System;
using UnityEngine;
namespace DvMod.RemoteDispatch
{
public class HttpServer : MonoBehaviour
{
private static GameObject? rootObject;
private readonly HttpListener listener = new HttpListener();
public async void Start()
{
if (!listener.IsListening)
{
listener.Prefixes.Add($"http://*:{Main.settings.serverPort}/");
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous | AuthenticationSchemes.Basic;
listener.Realm = "DV Remote Dispatch";
Main.DebugLog(() => $"Starting HTTP server on port {Main.settings.serverPort}");
listener.Start();
}
while (listener.IsListening)
{
try
{
var context = await listener.GetContextAsync().ConfigureAwait(true);
if (CheckAuthentication(context))
{
_ = Task.Run(async () =>
{
try
{
await HandleRequest(context).ConfigureAwait(false);
}
catch (Exception e)
{
Main.DebugLog(() => $"Exception while handling HTTP request ({context.Request.Url}): {e}");
}
});
}
else
{
context.Response.Headers.Add("WWW-Authenticate", "Basic");
RenderEmpty(context, 401);
}
}
catch (ObjectDisposedException e) when (e.ObjectName == "listener")
{
// ignore when OnDestroy() is called to shutdown the server
}
}
}
public void OnDestroy()
{
if (listener.IsListening)
{
Main.DebugLog(() => "Stopping HTTP server");
listener.Stop();
listener.Prefixes.Clear();
}
}
private static bool CheckAuthentication(HttpListenerContext context)
{
string serverPassword = Main.settings.serverPassword;
return context.User?.Identity is HttpListenerBasicIdentity identity && (string.IsNullOrEmpty(serverPassword) || identity.Password == serverPassword);
}
private static async Task HandleRequest(HttpListenerContext context)
{
var request = context.Request;
if (request.Url.Segments.Length < 2)
{
context.Response.ContentType = ContentTypes.Html;
RenderResource(context, "index.html");
return;
}
switch (request.Url.Segments[1].TrimEnd('/'))
{
case "car":
HandleCarRequest(context);
break;
case "job":
Render200(context, ContentTypes.Json, JobData.GetAllJobDataJson());
break;
case "junction":
HandleJunctionRequest(context);
break;
case "junctionState":
Render200(context, ContentTypes.Json, Junctions.GetJunctionStateJSON());
break;
case "player":
var playerJson = PlayerData.GetPlayerDataJson();
if (playerJson != null)
Render200(context, ContentTypes.Json, playerJson);
else
RenderEmpty(context, 500);
break;
case "res":
RenderResource(context);
break;
case "track":
Render200(context, ContentTypes.Json, await RailTracks.GetTrackPointJSON().ConfigureAwait(false));
break;
case "trainset":
HandleTrainsetRequest(context);
break;
case "updates":
await HandleUpdatesRequest(context).ConfigureAwait(false);
break;
default:
RenderEmpty(context, 404);
break;
}
}
private static async void HandleCarRequest(HttpListenerContext context)
{
var segments = context.Request.Url.Segments;
if (segments.Length == 2 && context.Request.HttpMethod == "GET")
{
var allCarDataJson = CarData.GetAllCarDataJson();
Render200(context, allCarDataJson);
return;
}
if (segments.Length == 3 && context.Request.HttpMethod == "GET")
{
var carGuid = segments[2].TrimEnd('/');
var carDataJson = CarData.GetCarGuidDataJson(carGuid);
if (carDataJson == null)
RenderEmpty(context, 404);
else
Render200(context, carDataJson);
return;
}
if (segments.Length == 4 && segments[3] == "control" && context.Request.HttpMethod == "POST")
{
var carGuid = segments[2].TrimEnd('/');
var controller = LocoControl.GetLocoController(carGuid);
if (controller == null)
{
RenderEmpty(context, 404);
return;
}
if (!Main.settings.permissions.HasLocoControlPermission(context.User.Identity.Name))
{
RenderEmpty(context, 403);
return;
}
var success = await Updater.RunOnMainThread(() =>
LocoControl.RunCommand(controller, context.Request.QueryString)
).ConfigureAwait(false);
RenderEmpty(context, success ? 204 : 400);
}
RenderEmpty(context, 404);
}
private static async Task HandleUpdatesRequest(HttpListenerContext context)
{
if (context.Request.Url.Segments.Length < 3)
{
RenderEmpty(context, 404);
return;
}
var username = context.User?.Identity?.Name ?? "";
var sessionId = context.Request.Url.Segments[2];
Render200(context, ContentTypes.Json, await Sessions.GetUpdates(username, sessionId).ConfigureAwait(false));
}
private static bool IsValidJunctionId(int junctionId)
{
return junctionId >= 0 && junctionId < SingletonBehaviour<WorldData>.Instance.OrderedJunctions.Length;
}
private static async void HandleJunctionRequest(HttpListenerContext context)
{
var url = context.Request.Url;
switch (url.Segments.Length)
{
case 2:
Render200(context, ContentTypes.Json, Junctions.GetJunctionPointJSON());
break;
case 4:
var junctionIdString = url.Segments[2].TrimEnd('/');
if (int.TryParse(junctionIdString, out var junctionId) && url.Segments[3] == "toggle" && IsValidJunctionId(junctionId))
{
if (!Main.settings.permissions.HasJunctionPermission(context.User.Identity.Name))
{
RenderEmpty(context, 403);
return;
}
var newSelectedBranch = await Updater.RunOnMainThread(() =>
{
Main.DebugLog(() => $"Toggling J-{junctionId}.");
var junction = SingletonBehaviour<WorldData>.Instance.OrderedJunctions[junctionId];
junction.Switch(Junction.SwitchMode.REGULAR);
return junction.selectedBranch;
}).ConfigureAwait(false);
Render200(context, new JValue(newSelectedBranch));
return;
}
RenderEmpty(context, 404);
break;
default:
RenderEmpty(context, 404);
break;
}
}
public static void HandleTrainsetRequest(HttpListenerContext context)
{
var request = context.Request;
if (request.Url.Segments.Length < 3)
{
RenderEmpty(context, 404);
return;
}
var trainsetId = int.Parse(request.Url.Segments[2]);
Render200(context, CarData.GetTrainsetDataJson(trainsetId));
}
public static void Create()
{
if (rootObject == null)
{
rootObject = new GameObject();
GameObject.DontDestroyOnLoad(rootObject);
rootObject.AddComponent<HttpServer>();
}
}
public static void Destroy()
{
if (rootObject == null)
return;
// ensure server shuts down immediately, not at the end of the frame
DestroyImmediate(rootObject);
rootObject = null;
}
private static void RenderResource(HttpListenerContext context)
{
var resourceName = context.Request.Url.Segments[2];
var extension = Path.GetExtension(resourceName);
context.Response.ContentType = ContentTypes.ForExtension(extension);
RenderResource(context, resourceName);
}
private static void RenderResource(HttpListenerContext context, string resourceName)
{
var assembly = typeof(HttpServer).Assembly;
using var stream = assembly.GetManifestResourceStream(typeof(HttpServer), resourceName);
if (stream == null)
{
RenderEmpty(context, 404);
}
else
{
stream.CopyTo(context.Response.OutputStream);
context.Response.Close();
}
}
private static class ContentTypes
{
public const string Css = "text/css";
public const string Html = "text/html; charset=UTF-8";
public const string Json = "application/json";
public const string Javascript = "application/javascript";
public const string Png = "image/png";
public const string Svg = "image/svg+xml";
public static string ForExtension(string extension)
{
return extension switch
{
".css" => Css,
".js" => Javascript,
".json" => Json,
".png" => Png,
".svg" => Svg,
_ => "",
};
}
}
private static void Render200(HttpListenerContext context, JToken json)
{
Render200(context, ContentTypes.Json, JsonConvert.SerializeObject(json));
}
private static void Render200(HttpListenerContext context, string contentType, string s)
{
context.Response.ContentType = contentType;
var bytes = Encoding.UTF8.GetBytes(s);
if (bytes.Length > 128 && (context.Request.Headers.GetValues("Accept-Encoding")?.Contains("gzip") ?? false))
{
context.Response.Headers.Add("Content-Encoding", "gzip");
var mem = new MemoryStream(bytes);
using var gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress);
mem.CopyTo(gzip);
}
else
{
context.Response.Close(bytes, false);
}
}
private static void RenderEmpty(HttpListenerContext context, int statusCode)
{
context.Response.StatusCode = statusCode;
context.Response.Close();
}
}
}