aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/HttpServer.hx
blob: 66668a70c164eb7511fa923ba3c405eef1d18d15 (plain) (blame)
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
package server;

import haxe.io.Path;
import js.node.Buffer;
import js.node.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 sys.FileSystem;

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",
		"svg" => "image/svg+xml",
		"ico" => "image/x-icon",
		"wav" => "audio/wav",
		"mp3" => "audio/mpeg",
		"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"
	];

	static var dir:String;
	static var customDir:String;
	static var hasCustomRes = false;
	static var allowedLocalFiles:Map<String, Bool> = [];
	static var allowLocalRequests = false;
	static final CHUNK_SIZE = 1024 * 1024 * 5; // 5 MB

	public static function init(dir:String, ?customDir:String, allowLocalRequests:Bool):Void {
		HttpServer.dir = dir;
		if (customDir == null) return;
		HttpServer.customDir = customDir;
		hasCustomRes = FileSystem.exists(customDir);
		HttpServer.allowLocalRequests = allowLocalRequests;
	}

	public static 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 (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 == "/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;
		}

		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") {
				// replace ${textId} to localized strings
				data = cast localizeHtml(data.toString(), req.headers["accept-language"]);
			}
			res.end(data);
		});
	}

	static function getPath(dir:String, url:URL):String {
		var filePath = dir + url.pathname;
		filePath = filePath.urlDecode();
		if (!FileSystem.isDirectory(filePath)) return filePath;
		return Path.addTrailingSlash(filePath) + "index.html";
	}

	static function readFileError(err:Dynamic, res:ServerResponse, filePath:String):Void {
		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.');
		}
	}

	static function serveMedia(req:IncomingMessage, res:ServerResponse, filePath:String):Bool {
		if (!Fs.existsSync(filePath)) return false;
		final videoSize = Fs.statSync(filePath).size;
		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');
		// HTTP Status 206 for Partial Content
		res.statusCode = 206;
		// create video read stream for this particular chunk
		final videoStream = Fs.createReadStream(filePath, {start: cast start, end: cast end});
		// stream the video chunk to the client
		videoStream.pipe(res);
		res.on("error", () -> videoStream.destroy());
		res.on("close", () -> videoStream.destroy());
		return true;
	}

	static function parseRangeHeader(rangeHeader:String, videoSize:Float):{start:Float, end:Float} {
		final ranges = ~/[-=]/g.split(rangeHeader);
		var start = Std.parseFloat(ranges[1]);
		if (Utils.isOutOfRange(start, 0, videoSize - 1)) start = 0;
		var end = Std.parseFloat(ranges[2]);
		if (Math.isNaN(end)) end = start + CHUNK_SIZE;
		if (Utils.isOutOfRange(end, start, videoSize - 1)) end = videoSize - 1;
		return {
			start: start,
			end: end
		};
	}

	static function isMediaExtension(ext:String):Bool {
		return ext == "mp4" || ext == "webm" || ext == "mp3" || ext == "wav";
	}

	static final matchLang = ~/^[A-z]+/;
	static final matchVarString = ~/\${([A-z_]+)}/g;

	static function localizeHtml(data:String, lang:String):String {
		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;
	}

	static function proxyUrl(req:IncomingMessage, res:ServerResponse):Bool {
		final url = req.url.replace("/proxy?url=", "");
		final proxy = proxyRequest(url, req, res, proxyRes -> {
			final url = proxyRes.headers["location"] ?? return false;
			final proxy2 = proxyRequest(url, req, res, proxyRes -> false);
			if (proxy2 == null) {
				res.end('Proxy error: multiple redirects for url $url');
				return true;
			}
			req.pipe(proxy2);
			return true;
		});
		if (proxy == null) return false;
		req.pipe(proxy);
		return true;
	}

	static 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)) return;
			proxyRes.headers["Content-Type"] = "application/octet-stream";
			res.writeHead(proxyRes.statusCode, proxyRes.headers);
			proxyRes.pipe(res);
		});
		proxy.on("error", err -> {
			res.end('Proxy error: ${url.href}');
		});
		return proxy;
	}

	static function isChildOf(parent:String, child:String):Bool {
		final rel = JsPath.relative(parent, child);
		return rel.length > 0 && !rel.startsWith('..') && !JsPath.isAbsolute(rel);
	}

	static function getMimeType(ext:String):String {
		return mimeTypes[ext] ?? return "application/octet-stream";
	}

	static final ctrlCharacters = ~/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/g;

	static function safeDecodeURI(data:String):String {
		try {
			data = decodeURI(data);
		} catch (err) {
			data = "";
		}
		data = ctrlCharacters.replace(data, "");
		return data;
	}

	static inline function decodeURI(data:String):String {
		return js.Syntax.code("decodeURI({0})", data);
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage