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
|
package server;
import Types.UploadResponse;
import haxe.crypto.Sha256;
import haxe.io.Path;
import js.node.Buffer;
import js.node.Fs.Fs;
import js.node.Http;
import js.node.Https;
import js.node.Path as JsPath;
import js.node.http.ClientRequest;
import js.node.http.IncomingMessage;
import js.node.http.ServerResponse;
import js.node.url.URL;
import json2object.ErrorUtils;
import json2object.JsonParser;
import server.cache.Cache;
import sys.FileSystem;
@:structInit
private class HttpServerConfig {
public final dir:String;
public final customDir:String = null;
public final allowLocalRequests = false;
public final cache:Cache = null;
}
typedef GateRequest = {
password:String,
}
typedef AdminRegisterRequest = {
name:String,
password:String,
passwordConfirmation:String,
token:String,
}
class HttpServer {
static final mimeTypes = [
"html" => "text/html",
"js" => "text/javascript",
"css" => "text/css",
"json" => "application/json",
"png" => "image/png",
"jpg" => "image/jpeg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"svg" => "image/svg+xml",
"ico" => "image/x-icon",
"wav" => "audio/wav",
"mp3" => "audio/mpeg",
"ogg" => "audio/ogg",
"mp4" => "video/mp4",
"webm" => "video/webm",
"woff" => "application/font-woff",
"ttf" => "application/font-ttf",
"eot" => "application/vnd.ms-fontobject",
"otf" => "application/font-otf",
"wasm" => "application/wasm"
];
final main:Main;
final dir:String;
final customDir:String;
final hasCustomRes = false;
final allowedLocalFiles:Map<String, Bool> = [];
final allowLocalRequests = false;
final cache:Cache = null;
final CHUNK_SIZE = 1024 * 1024 * 5; // 5 MB
// temp media data while file is uploading to allow instant streaming
final uploadingFilesSizes:Map<String, Int> = [];
final uploadingFilesLastChunks:Map<String, Buffer> = [];
public function new(main:Main, config:HttpServerConfig):Void {
this.main = main;
dir = config.dir;
customDir = config.customDir;
allowLocalRequests = config.allowLocalRequests;
cache = config.cache;
if (customDir != null) hasCustomRes = FileSystem.exists(customDir);
}
public function serveFiles(req:IncomingMessage, res:ServerResponse):Void {
final url = try {
new URL(safeDecodeURI(req.url), "http://localhost");
} catch (e) {
new URL("/", "http://localhost");
}
var filePath = getPath(dir, url);
final ext = Path.extension(filePath).toLowerCase();
res.setHeader("accept-ranges", "bytes");
res.setHeader("content-type", getMimeType(ext));
if (req.method == "POST") {
if (cache != null) {
switch url.pathname {
case "/upload-last-chunk":
uploadFileLastChunk(req, res);
case "/upload":
uploadFile(req, res);
}
}
switch url.pathname {
case "/gate":
verifyGate(req, res);
case "/admin-register":
registerAdmin(req, res);
}
return;
}
if (allowLocalRequests && req.socket.remoteAddress == req.socket.localAddress
|| allowedLocalFiles[url.pathname]) {
if (isMediaExtension(ext)) {
allowedLocalFiles[url.pathname] = true;
if (serveMedia(req, res, url.pathname.urlDecode())) return;
}
}
if (!isChildOf(dir, filePath)) {
res.statusCode = 500;
var rel = JsPath.relative(dir, filePath);
res.end('Error getting the file: No access to $rel.');
return;
}
if (url.pathname == "/gate") {
if (!hasGatePassword() || hasValidGateCookie(req)) {
res.redirect("/");
return;
}
Fs.readFile('$dir/setup.html', (err:Dynamic, data:Buffer) -> {
data = Buffer.from(localizeHtml(data.toString(), req.headers["accept-language"]));
res.setHeader("content-type", getMimeType("html"));
res.end(data);
});
return;
}
if (url.pathname == "/admin-register") {
if (!hasAdminToken()) {
res.redirect("/");
return;
}
Fs.readFile('$dir/admin-register.html', (err:Dynamic, data:Buffer) -> {
if (err != null) {
readFileError(err, res, '$dir/admin-register.html');
return;
}
data = Buffer.from(localizeHtml(data.toString(), req.headers["accept-language"]));
res.setHeader("content-type", getMimeType("html"));
res.end(data);
});
return;
}
if (url.pathname == "/proxy") {
if (!proxyUrl(req, res)) res.end('Proxy error: ${req.url}');
return;
}
if (hasCustomRes) {
final path = getPath(customDir, url);
if (Fs.existsSync(path)) filePath = path;
final ext = Path.extension(filePath).toLowerCase();
res.setHeader("content-type", getMimeType(ext));
}
if (isMediaExtension(ext)) {
if (serveMedia(req, res, filePath)) return;
}
Fs.readFile(filePath, (err:Dynamic, data:Buffer) -> {
if (err != null) {
readFileError(err, res, filePath);
return;
}
if (ext == "html") {
if (hasGatePassword() && !hasValidGateCookie(req)) {
res.redirect("/gate");
return;
}
// replace ${textId} to localized strings
data = cast localizeHtml(data.toString(), req.headers["accept-language"]);
}
res.end(data);
});
}
function uploadFileLastChunk(req:IncomingMessage, res:ServerResponse) {
var fileName = try decodeURIComponent(req.headers["content-name"]) catch (e) "";
if (fileName.trim().length == 0) fileName = null;
final name = cache.getFreeFileName(fileName);
final filePath = cache.getFilePath(name);
final body:Array<Any> = [];
req.on("data", chunk -> body.push(chunk));
req.on("end", () -> {
final buffer = Buffer.concat(body);
uploadingFilesLastChunks[filePath] = buffer;
final json:UploadResponse = {
info: "File last chunk uploaded",
url: cache.getFileUrl(name)
}
res.status(200).json(json);
});
}
function uploadFile(req:IncomingMessage, res:ServerResponse) {
var fileName = try decodeURIComponent(req.headers["content-name"]) catch (e) "";
if (fileName.trim().length == 0) fileName = null;
final name = cache.getFreeFileName(fileName);
final filePath = cache.getFilePath(name);
final size = Std.parseInt(req.headers["content-length"]) ?? return;
inline function end(code:Int, json:UploadResponse):Void {
res.status(code).json(json);
uploadingFilesSizes.remove(filePath);
uploadingFilesLastChunks.remove(filePath);
}
if (size < cache.storageLimit) {
// do not remove older cache if file is out of limit anyway
cache.removeOlderCache(size);
}
if (cache.getFreeSpace() < size) {
end(413, { // Payload Too Large
info: cache.notEnoughSpaceErrorText,
errorId: "freeSpace",
});
cache.remove(name);
req.destroy();
final client = main.clients.getByName(name) ?? return;
main.serverMessage(client, cache.notEnoughSpaceErrorText);
return;
}
final stream = Fs.createWriteStream(filePath);
req.pipe(stream);
cache.add(name);
uploadingFilesSizes[filePath] = size;
stream.on("close", () -> {
end(200, {
info: "File write stream closed.",
});
});
stream.on("error", err -> {
trace(err);
end(500, {
info: "File write stream error.",
});
cache.remove(name);
});
req.on("error", err -> {
trace("Request Error:", err);
stream.destroy();
end(500, {
info: "File request error.",
});
cache.remove(name);
});
}
function verifyGate(req:IncomingMessage, res:ServerResponse) {
if (!hasGatePassword()) {
return res.redirect("/");
}
final bodyChunks:Array<Buffer> = [];
req.on("data", chunk -> {
bodyChunks.push(chunk);
});
req.on("end", () -> {
final body = Buffer.concat(bodyChunks).toString();
final jsonParser = new JsonParser<GateRequest>();
final jsonData = jsonParser.fromJson(body);
if (jsonParser.errors.length > 0) {
res.status(400).json({success: false});
return;
}
final password = jsonData.password;
if (password == main.config.gatePassword) {
final token = getGateToken();
res.setHeader("set-cookie", 'gate_auth=$token; Path=/; HttpOnly; SameSite=Strict');
res.status(200).json({success: true});
} else {
res.status(401).json({success: false});
}
});
}
function hasGatePassword():Bool {
final gp = main.config.gatePassword;
return gp != null && gp.length > 0;
}
function hasValidGateCookie(req:IncomingMessage):Bool {
final cookieHeader:String = req.headers["cookie"];
if (cookieHeader == null) return false;
final token = getGateToken();
final needle = 'gate_auth=$token';
for (cookie in cookieHeader.split(";")) {
if (cookie.trim() == needle) return true;
}
return false;
}
function getGateToken():String {
return Sha256.encode('gate_${main.config.gatePassword}_${main.config.salt}');
}
function hasAdminToken():Bool {
final t = main.config.adminToken;
return t != null && t.length > 0;
}
function registerAdmin(req:IncomingMessage, res:ServerResponse) {
if (!hasAdminToken()) {
res.status(403).json({success: false, error: "Admin registration is disabled"});
return;
}
final bodyChunks:Array<Buffer> = [];
req.on("data", chunk -> bodyChunks.push(chunk));
req.on("end", () -> {
final body = Buffer.concat(bodyChunks).toString();
final jsonParser = new JsonParser<AdminRegisterRequest>();
final jsonData = jsonParser.fromJson(body);
if (jsonParser.errors.length > 0) {
res.status(400).json({success: false, error: "Invalid request"});
return;
}
final name = jsonData.name.trim();
final password = jsonData.password;
final passwordConfirmation = jsonData.passwordConfirmation;
final token = jsonData.token;
if (token != main.config.adminToken) {
res.status(401).json({success: false, error: "Invalid admin token"});
return;
}
if (main.isBadClientName(name)) {
res.status(400).json({success: false, error: "Invalid username"});
return;
}
final min = Main.MIN_PASSWORD_LENGTH;
final max = Main.MAX_PASSWORD_LENGTH;
if (password.length < min || password.length > max) {
res.status(400).json({success: false, error: 'Password must be $min-$max characters'});
return;
}
if (password != passwordConfirmation) {
res.status(400).json({success: false, error: "Passwords do not match"});
return;
}
main.addAdmin(name, password);
res.status(200).json({success: true});
});
}
function getPath(dir:String, url:URL):String {
final filePath = dir.urlDecode() + decodeURIComponent(url.pathname);
if (!FileSystem.isDirectory(filePath)) return filePath;
return Path.addTrailingSlash(filePath) + "index.html";
}
function readFileError(err:Dynamic, res:ServerResponse, filePath:String):Void {
res.setHeader("content-type", getMimeType("html"));
if (err.code == "ENOENT") {
res.statusCode = 404;
var rel = JsPath.relative(dir, filePath);
res.end('File $rel not found.');
} else {
res.statusCode = 500;
res.end('Error getting the file: $err.');
}
}
function serveMedia(req:IncomingMessage, res:ServerResponse, filePath:String):Bool {
if (!Fs.existsSync(filePath)) return false;
var videoSize:Int = cast Fs.statSync(filePath).size;
// use future content length to start playing it before uploaded
if (uploadingFilesSizes.exists(filePath)) {
videoSize = uploadingFilesSizes[filePath];
}
final rangeHeader:String = req.headers["range"];
if (rangeHeader == null) {
res.statusCode = 200;
res.setHeader("content-length", '$videoSize');
final videoStream = Fs.createReadStream(filePath);
videoStream.pipe(res);
res.on("error", () -> videoStream.destroy());
res.on("close", () -> videoStream.destroy());
return true;
}
final range = parseRangeHeader(rangeHeader, videoSize);
final start = range.start;
final end = range.end;
final contentLength = end - start + 1;
res.setHeader("content-range", 'bytes $start-$end/$videoSize');
res.setHeader("content-length", '$contentLength');
res.statusCode = 206; // partial content
// check for last chunk cache for instant play while uploading
final buffer = uploadingFilesLastChunks[filePath];
if (buffer != null && end == videoSize - 1 && contentLength < buffer.byteLength) {
final bufferStart = (buffer.byteLength - contentLength).limitMin(0);
res.end(buffer.slice(bufferStart));
return true;
}
// stream the video chunk to the client
final videoStream = Fs.createReadStream(
filePath,
{start: start, end: end}
);
videoStream.pipe(res);
res.on("error", () -> videoStream.destroy());
res.on("close", () -> videoStream.destroy());
return true;
}
function parseRangeHeader(rangeHeader:String, videoSize:Int):{start:Int, end:Int} {
final ranges = ~/[-=]/g.split(rangeHeader);
var start = Std.parseInt(ranges[1]);
if (Utils.isOutOfRange(start, 0, videoSize - 1)) start = 0;
var end = Std.parseInt(ranges[2]);
if (end == null) end = start + CHUNK_SIZE;
if (Utils.isOutOfRange(end, start, videoSize - 1)) end = (videoSize - 1).limitMin(0);
return {
start: start,
end: end
};
}
function isMediaExtension(ext:String):Bool {
return switch ext {
case "mp4", "webm", "mp3", "ogg", "wav": true;
case _: false;
}
}
final matchLang = ~/^[A-z]+/;
final matchVarString = ~/\${([A-z_]+)}/g;
function localizeHtml(data:String, lang:String):String {
if (!data.contains("<!-- localization-template -->")) return data;
if (lang != null && matchLang.match(lang)) {
lang = matchLang.matched(0);
} else lang = "en";
data = matchVarString.map(data, (regExp) -> {
final key = regExp.matched(1);
return Lang.get(lang, key);
});
return data;
}
function proxyUrl(req:IncomingMessage, res:ServerResponse):Bool {
final url = req.url.replace("/proxy?url=", "");
final proxy = proxyRequest(url, req, res, proxyRes -> {
final redirectUrl = proxyRes.headers["location"] ?? return false;
final proxy2 = proxyRequest(redirectUrl, req, res, proxyRes -> false);
if (proxy2 == null) {
if (!res.headersSent) {
res.end('Proxy error: multiple redirects for url $redirectUrl');
}
return true;
}
req.pipe(proxy2);
req.on("error", () -> proxy2.destroy());
return true;
});
if (proxy == null) return false;
req.pipe(proxy);
req.on("error", () -> proxy.destroy());
return true;
}
function proxyRequest(
url:String,
req:IncomingMessage,
res:ServerResponse,
cancelProxyRequest:(proxyRes:IncomingMessage) -> Bool
):Null<ClientRequest> {
final url = try {
new URL(safeDecodeURI(url));
} catch (e) {
return null;
}
if (url.host == req.headers["host"]) return null;
final options = {
host: url.hostname,
port: Std.parseInt(url.port),
path: url.pathname + url.search,
method: req.method
};
req.headers["referer"] = url.toString();
req.headers["host"] = url.hostname;
final request = url.protocol == "https:" ? Https.request : Http.request;
final proxy = request(options, proxyRes -> {
if (cancelProxyRequest(proxyRes)) {
proxyRes.destroy();
return;
}
proxyRes.headers["content-type"] = "application/octet-stream";
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
// clean up when response ends
proxyRes.on("end", () -> {
if (!res.writableEnded) res.end();
});
});
proxy.on("error", err -> {
proxy.destroy();
if (!res.headersSent) {
res.end('Proxy error: ${url.href}');
}
});
// clean up when client disconnects (seeking/abort)
res.on("close", () -> {
if (!proxy.destroyed) proxy.destroy();
});
return proxy;
}
function isChildOf(parent:String, child:String):Bool {
final rel = JsPath.relative(parent, child);
return rel.length > 0 && !rel.startsWith("..") && !JsPath.isAbsolute(rel);
}
function getMimeType(ext:String):String {
return mimeTypes[ext] ?? "application/octet-stream";
}
final ctrlCharacters = ~/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/g;
function safeDecodeURI(data:String):String {
try {
data = decodeURI(data);
} catch (err) {
data = "";
}
data = ctrlCharacters.replace(data, "");
return data;
}
inline function decodeURI(data:String):String {
return js.Syntax.code("decodeURI({0})", data);
}
inline function decodeURIComponent(data:String):String {
return js.Syntax.code("decodeURIComponent({0})", data);
}
}
|