2023-01-11 18:39:42 -05:00
|
|
|
import * as core from './core.js';
|
2022-06-18 13:39:08 -04:00
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let gHandlers = [];
|
|
|
|
let gSocketHandlers = [];
|
|
|
|
let gBadRequests = {};
|
2016-03-12 13:50:43 -05:00
|
|
|
|
2023-09-20 19:30:29 -04:00
|
|
|
const kRequestTimeout = 5000;
|
2022-06-17 14:51:24 -04:00
|
|
|
const kStallTimeout = 60000;
|
2022-06-06 21:00:50 -04:00
|
|
|
|
2016-03-12 13:50:43 -05:00
|
|
|
function logError(error) {
|
|
|
|
print("ERROR " + error);
|
2022-04-26 19:05:02 -04:00
|
|
|
if (error.stackTrace) {
|
|
|
|
print(error.stackTrace);
|
|
|
|
}
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function addHandler(handler) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let added = false;
|
|
|
|
for (let i in gHandlers) {
|
2016-03-12 13:50:43 -05:00
|
|
|
if (gHandlers[i].path == handler.path) {
|
|
|
|
gHandlers[i] = handler;
|
|
|
|
added = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!added) {
|
|
|
|
gHandlers.push(handler);
|
|
|
|
added = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function all(prefix, handler) {
|
|
|
|
addHandler({
|
|
|
|
owner: this,
|
|
|
|
path: prefix,
|
|
|
|
invoke: handler,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-04-10 20:09:21 -04:00
|
|
|
function registerSocketHandler(prefix, handler) {
|
|
|
|
gSocketHandlers.push({
|
|
|
|
owner: this,
|
|
|
|
path: prefix,
|
|
|
|
invoke: handler,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-03-12 13:50:43 -05:00
|
|
|
function Request(method, uri, version, headers, body, client) {
|
|
|
|
this.method = method;
|
2022-12-31 11:47:10 -05:00
|
|
|
let index = uri.indexOf("?");
|
2016-03-12 13:50:43 -05:00
|
|
|
if (index != -1) {
|
|
|
|
this.uri = uri.slice(0, index);
|
|
|
|
this.query = uri.slice(index + 1);
|
|
|
|
} else {
|
|
|
|
this.uri = uri;
|
|
|
|
this.query = undefined;
|
|
|
|
}
|
2022-04-26 19:05:02 -04:00
|
|
|
this.version = version || '';
|
2016-03-12 13:50:43 -05:00
|
|
|
this.headers = headers;
|
2022-01-08 20:36:29 -05:00
|
|
|
this.client = {peerName: client.peerName, tls: client.tls};
|
2016-03-12 13:50:43 -05:00
|
|
|
this.body = body;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
function findHandler(request) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let matchedHandler = null;
|
|
|
|
for (let name in gHandlers) {
|
|
|
|
let handler = gHandlers[name];
|
2016-03-12 13:50:43 -05:00
|
|
|
if (request.uri == handler.path || request.uri.slice(0, handler.path.length + 1) == handler.path + '/') {
|
|
|
|
matchedHandler = handler;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return matchedHandler;
|
|
|
|
}
|
|
|
|
|
2016-04-10 20:09:21 -04:00
|
|
|
function findSocketHandler(request) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let matchedHandler = null;
|
|
|
|
for (let name in gSocketHandlers) {
|
|
|
|
let handler = gSocketHandlers[name];
|
2016-04-10 20:09:21 -04:00
|
|
|
if (request.uri == handler.path || request.uri.slice(0, handler.path.length + 1) == handler.path + '/') {
|
|
|
|
matchedHandler = handler;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return matchedHandler;
|
|
|
|
}
|
|
|
|
|
2016-03-12 13:50:43 -05:00
|
|
|
function Response(request, client) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let kStatusText = {
|
2016-04-10 20:09:21 -04:00
|
|
|
101: "Switching Protocols",
|
2016-03-12 13:50:43 -05:00
|
|
|
200: 'OK',
|
|
|
|
303: 'See other',
|
2022-10-14 12:26:08 -04:00
|
|
|
304: 'Not Modified',
|
2022-11-30 19:50:06 -05:00
|
|
|
400: 'Bad Request',
|
2023-01-11 19:01:47 -05:00
|
|
|
401: 'Unauthorized',
|
2016-03-16 20:51:08 -04:00
|
|
|
403: 'Forbidden',
|
2016-03-12 13:50:43 -05:00
|
|
|
404: 'File not found',
|
|
|
|
500: 'Internal server error',
|
|
|
|
};
|
2022-12-31 11:47:10 -05:00
|
|
|
let _started = false;
|
|
|
|
let _finished = false;
|
|
|
|
let _keepAlive = false;
|
|
|
|
let _chunked = false;
|
2016-03-12 13:50:43 -05:00
|
|
|
return {
|
|
|
|
writeHead: function(status) {
|
|
|
|
if (_started) {
|
|
|
|
throw new Error("Response.writeHead called multiple times.");
|
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
let reason;
|
|
|
|
let headers;
|
2016-03-12 13:50:43 -05:00
|
|
|
if (arguments.length == 3) {
|
|
|
|
reason = arguments[1];
|
|
|
|
headers = arguments[2];
|
|
|
|
} else {
|
|
|
|
reason = kStatusText[status];
|
|
|
|
headers = arguments[1];
|
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
let lowerHeaders = {};
|
|
|
|
let requestVersion = request.version.split("/")[1].split(".");
|
|
|
|
let responseVersion = (requestVersion[0] >= 1 && requestVersion[0] >= 1) ? "1.1" : "1.0";
|
|
|
|
let headerString = "HTTP/" + responseVersion + " " + status + " " + reason + "\r\n";
|
2023-10-22 08:44:12 -04:00
|
|
|
headers['Server'] = `Tilde Friends/${version().number}`;
|
2022-12-31 11:47:10 -05:00
|
|
|
for (let i in headers) {
|
2016-03-12 13:50:43 -05:00
|
|
|
headerString += i + ": " + headers[i] + "\r\n";
|
|
|
|
lowerHeaders[i.toLowerCase()] = headers[i];
|
|
|
|
}
|
|
|
|
if ("connection" in lowerHeaders) {
|
|
|
|
_keepAlive = lowerHeaders["connection"].toLowerCase() == "keep-alive";
|
|
|
|
} else {
|
|
|
|
_keepAlive = ((request.version == "HTTP/1.0" && ("connection" in lowerHeaders && lowerHeaders["connection"].toLowerCase() == "keep-alive")) ||
|
|
|
|
(request.version == "HTTP/1.1" && (!("connection" in lowerHeaders) || lowerHeaders["connection"].toLowerCase() != "close")));
|
|
|
|
headerString += "Connection: " + (_keepAlive ? "keep-alive" : "close") + "\r\n";
|
|
|
|
}
|
|
|
|
_chunked = _keepAlive && !("content-length" in lowerHeaders);
|
|
|
|
if (_chunked) {
|
|
|
|
headerString += "Transfer-Encoding: chunked\r\n";
|
|
|
|
}
|
|
|
|
headerString += "\r\n";
|
|
|
|
_started = true;
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write(headerString).catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
},
|
|
|
|
end: function(data) {
|
|
|
|
if (_finished) {
|
|
|
|
throw new Error("Response.end called multiple times.");
|
|
|
|
}
|
|
|
|
if (data) {
|
|
|
|
if (_chunked) {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write(data.length.toString(16) + "\r\n" + data + "\r\n" + "0\r\n\r\n").catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
} else {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write(data).catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
} else if (_chunked) {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write("0\r\n\r\n").catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
_finished = true;
|
|
|
|
if (!_keepAlive) {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.shutdown().catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
},
|
|
|
|
reportError: function(error) {
|
|
|
|
if (!_started) {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write("HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n").catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
if (!_finished) {
|
2022-04-26 19:05:02 -04:00
|
|
|
client.write("500 Internal Server Error\r\n\r\n" + error?.stackTrace).catch(function() {});
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
logError(client.peerName + " - - [" + new Date() + "] " + error);
|
|
|
|
},
|
|
|
|
isConnected: function() { return client.isConnected; },
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleRequest(request, response) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let handler = findHandler(request);
|
2016-03-12 13:50:43 -05:00
|
|
|
|
|
|
|
print(request.client.peerName + " - - [" + new Date() + "] " + request.method + " " + request.uri + " " + request.version + " \"" + request.headers["user-agent"] + "\"");
|
|
|
|
|
|
|
|
if (handler) {
|
|
|
|
try {
|
2023-01-21 15:12:41 -05:00
|
|
|
Promise.resolve(handler.invoke(request, response)).catch(function(error) {
|
|
|
|
response.reportError(error);
|
|
|
|
request.client.close();
|
|
|
|
});
|
2016-03-12 13:50:43 -05:00
|
|
|
} catch (error) {
|
|
|
|
response.reportError(error);
|
2022-06-02 06:58:22 -04:00
|
|
|
request.client.close();
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});
|
|
|
|
response.end("No handler found for request: " + request.uri);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-10 20:09:21 -04:00
|
|
|
function handleWebSocketRequest(request, response, client) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let buffer = new Uint8Array(0);
|
2023-01-28 16:59:36 -05:00
|
|
|
let frame;
|
2022-12-31 11:47:10 -05:00
|
|
|
let frameOpCode = 0x0;
|
2016-04-10 20:09:21 -04:00
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let handler = findSocketHandler(request);
|
2016-04-10 20:09:21 -04:00
|
|
|
if (!handler) {
|
|
|
|
client.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
response.send = function(message, opCode) {
|
|
|
|
if (opCode === undefined) {
|
|
|
|
opCode = 0x2;
|
|
|
|
}
|
2016-12-21 15:19:23 -05:00
|
|
|
if (opCode == 0x1 && (typeof message == "string" || message instanceof String)) {
|
2022-01-26 20:15:54 -05:00
|
|
|
message = utf8Encode(message);
|
2016-12-21 15:19:23 -05:00
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
let fin = true;
|
|
|
|
let packet = [(fin ? (1 << 7) : 0) | (opCode & 0xf)];
|
|
|
|
let mask = false;
|
2016-04-10 20:09:21 -04:00
|
|
|
if (message.length < 126) {
|
2016-12-21 15:19:23 -05:00
|
|
|
packet.push((mask ? (1 << 7) : 0) | message.length);
|
2016-04-10 20:09:21 -04:00
|
|
|
} else if (message.length < (1 << 16)) {
|
2016-12-21 15:19:23 -05:00
|
|
|
packet.push((mask ? (1 << 7) : 0) | 126);
|
|
|
|
packet.push((message.length >> 8) & 0xff);
|
|
|
|
packet.push(message.length & 0xff);
|
2016-04-10 20:09:21 -04:00
|
|
|
} else {
|
2022-12-31 11:47:10 -05:00
|
|
|
let high = 0; //(message.length / (1 ** 32)) & 0xffffffff;
|
|
|
|
let low = message.length & 0xffffffff;
|
2016-12-21 15:19:23 -05:00
|
|
|
packet.push((mask ? (1 << 7) : 0) | 127);
|
2021-01-02 13:10:00 -05:00
|
|
|
packet.push((high >> 24) & 0xff);
|
|
|
|
packet.push((high >> 16) & 0xff);
|
|
|
|
packet.push((high >> 8) & 0xff);
|
|
|
|
packet.push((high >> 0) & 0xff);
|
|
|
|
packet.push((low >> 24) & 0xff);
|
|
|
|
packet.push((low >> 16) & 0xff);
|
|
|
|
packet.push((low >> 8) & 0xff);
|
|
|
|
packet.push(low & 0xff);
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
2016-12-21 15:19:23 -05:00
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let array = new Uint8Array(packet.length + message.length);
|
2016-12-21 15:19:23 -05:00
|
|
|
array.set(packet, 0);
|
|
|
|
array.set(message, packet.length);
|
2022-06-20 10:30:00 -04:00
|
|
|
try {
|
|
|
|
return client.write(array);
|
|
|
|
} catch (error) {
|
|
|
|
client.close();
|
|
|
|
throw error;
|
|
|
|
}
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
response.onMessage = null;
|
|
|
|
|
2022-10-04 21:20:47 -04:00
|
|
|
let extra_headers = handler.invoke(request, response);
|
2016-04-10 20:09:21 -04:00
|
|
|
|
|
|
|
client.read(function(data) {
|
|
|
|
if (data) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let newBuffer = new Uint8Array(buffer.length + data.length);
|
2016-12-21 15:19:23 -05:00
|
|
|
newBuffer.set(buffer, 0);
|
|
|
|
newBuffer.set(data, buffer.length);
|
|
|
|
buffer = newBuffer;
|
|
|
|
|
2021-01-02 13:10:00 -05:00
|
|
|
while (buffer.length >= 2) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let bits0 = buffer[0];
|
|
|
|
let bits1 = buffer[1];
|
2016-04-10 20:09:21 -04:00
|
|
|
if (bits1 & (1 << 7) == 0) {
|
|
|
|
// Unmasked message.
|
|
|
|
client.close();
|
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
let opCode = bits0 & 0xf;
|
|
|
|
let fin = bits0 & (1 << 7);
|
|
|
|
let payloadLength = bits1 & 0x7f;
|
|
|
|
let maskStart = 2;
|
2016-04-10 20:09:21 -04:00
|
|
|
|
|
|
|
if (payloadLength == 126) {
|
|
|
|
payloadLength = 0;
|
2022-12-31 11:47:10 -05:00
|
|
|
for (let i = 0; i < 2; i++) {
|
2016-04-10 20:09:21 -04:00
|
|
|
payloadLength <<= 8;
|
2016-12-21 15:19:23 -05:00
|
|
|
payloadLength |= buffer[2 + i];
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
maskStart = 4;
|
|
|
|
} else if (payloadLength == 127) {
|
|
|
|
payloadLength = 0;
|
2022-12-31 11:47:10 -05:00
|
|
|
for (let i = 0; i < 8; i++) {
|
2016-04-10 20:09:21 -04:00
|
|
|
payloadLength <<= 8;
|
2016-12-21 15:19:23 -05:00
|
|
|
payloadLength |= buffer[2 + i];
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
maskStart = 10;
|
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
let havePayload = buffer.length >= payloadLength + 2 + 4;
|
2016-04-10 20:09:21 -04:00
|
|
|
if (havePayload) {
|
2023-01-28 16:59:36 -05:00
|
|
|
let mask =
|
|
|
|
buffer[maskStart + 0] |
|
|
|
|
buffer[maskStart + 1] << 8 |
|
|
|
|
buffer[maskStart + 2] << 16 |
|
|
|
|
buffer[maskStart + 3] << 24;
|
2022-12-31 11:47:10 -05:00
|
|
|
let dataStart = maskStart + 4;
|
|
|
|
let payload = buffer.slice(dataStart, dataStart + payloadLength);
|
2023-01-28 16:59:36 -05:00
|
|
|
let decoded = maskBytes(payload, mask);
|
2016-12-21 15:19:23 -05:00
|
|
|
buffer = buffer.slice(dataStart + payloadLength);
|
2016-04-10 20:09:21 -04:00
|
|
|
|
2023-01-28 16:59:36 -05:00
|
|
|
if (frame) {
|
|
|
|
let newBuffer = new Uint8Array(frame.length + decoded.length);
|
|
|
|
newBuffer.set(frame, 0);
|
|
|
|
newBuffer.set(decoded, frame.length);
|
|
|
|
frame = newBuffer;
|
|
|
|
} else {
|
|
|
|
frame = decoded;
|
|
|
|
}
|
2016-12-22 12:38:21 -05:00
|
|
|
|
2016-04-10 20:09:21 -04:00
|
|
|
if (opCode) {
|
|
|
|
frameOpCode = opCode;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (fin) {
|
|
|
|
if (response.onMessage) {
|
|
|
|
response.onMessage({
|
2022-01-26 20:15:54 -05:00
|
|
|
data: frameOpCode == 0x1 ? utf8Decode(frame) : frame,
|
2016-04-10 20:09:21 -04:00
|
|
|
opCode: frameOpCode,
|
|
|
|
});
|
|
|
|
}
|
2023-01-28 16:59:36 -05:00
|
|
|
frame = undefined;
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
2021-01-02 13:10:00 -05:00
|
|
|
} else {
|
|
|
|
break;
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
}
|
2022-01-20 19:49:03 -05:00
|
|
|
} else {
|
|
|
|
response.onClose();
|
|
|
|
client.close();
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
client.onError(function(error) {
|
|
|
|
logError(client.peerName + " - - [" + new Date() + "] " + error);
|
2022-01-20 19:49:03 -05:00
|
|
|
response.onError(error);
|
2016-04-10 20:09:21 -04:00
|
|
|
});
|
|
|
|
|
2016-04-23 14:17:55 -04:00
|
|
|
let headers = {
|
2016-04-10 20:09:21 -04:00
|
|
|
"Upgrade": "websocket",
|
|
|
|
"Connection": "Upgrade",
|
|
|
|
"Sec-WebSocket-Accept": webSocketAcceptResponse(request.headers["sec-websocket-key"]),
|
2016-04-23 14:17:55 -04:00
|
|
|
};
|
|
|
|
if (request.headers["sec-websocket-version"] != "13") {
|
|
|
|
headers["Sec-WebSocket-Version"] = "13";
|
|
|
|
}
|
2022-10-04 21:20:47 -04:00
|
|
|
response.writeHead(101, Object.assign({}, headers, extra_headers));
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
function webSocketAcceptResponse(key) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let kMagic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
|
|
let kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
|
2023-01-28 16:59:36 -05:00
|
|
|
return base64Encode(sha1Digest(key + kMagic));
|
2016-04-10 20:09:21 -04:00
|
|
|
}
|
|
|
|
|
2022-04-26 19:05:02 -04:00
|
|
|
function badRequest(client, reason) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let now = new Date();
|
|
|
|
let count = 0;
|
|
|
|
let old = gBadRequests[client.peerName];
|
2022-04-26 19:05:02 -04:00
|
|
|
if (!old) {
|
|
|
|
gBadRequests[client.peerName] = {
|
2022-06-20 15:50:03 -04:00
|
|
|
expire: new Date(now.getTime() + 1 * 60 * 1000),
|
2022-04-26 19:05:02 -04:00
|
|
|
count: 1,
|
2022-06-06 22:08:06 -04:00
|
|
|
reason: reason,
|
2022-04-26 19:05:02 -04:00
|
|
|
};
|
|
|
|
count = 1;
|
|
|
|
} else {
|
|
|
|
old.count++;
|
2022-06-06 22:08:06 -04:00
|
|
|
old.reason = reason;
|
2022-04-26 19:05:02 -04:00
|
|
|
count = old.count;
|
|
|
|
}
|
|
|
|
new Response({version: '1.0'}, client).reportError(reason + ': ' + count);
|
|
|
|
client.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
function allowRequest(client) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let old = gBadRequests[client.peerName];
|
2022-04-26 19:05:02 -04:00
|
|
|
if (old) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let now = new Date();
|
2022-04-26 19:05:02 -04:00
|
|
|
if (old.expire < now) {
|
|
|
|
delete gBadRequests[client.peerName];
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
return old.count < 3;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-12 13:50:43 -05:00
|
|
|
function handleConnection(client) {
|
2022-04-26 19:05:02 -04:00
|
|
|
if (!allowRequest(client)) {
|
2022-06-06 22:08:06 -04:00
|
|
|
print('Rejecting client for too many bad requests: ', client.peerName, gBadRequests[client.peerName].reason);
|
2022-06-17 14:51:24 -04:00
|
|
|
client.info = 'rejected';
|
2022-04-26 19:05:02 -04:00
|
|
|
client.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-06-17 14:51:24 -04:00
|
|
|
client.info = 'accepted';
|
2022-12-31 11:47:10 -05:00
|
|
|
let inputBuffer = new Uint8Array(0);
|
|
|
|
let request;
|
|
|
|
let headers = {};
|
|
|
|
let parsing_header = true;
|
|
|
|
let bodyToRead = -1;
|
|
|
|
let body;
|
|
|
|
let readCount = 0;
|
|
|
|
let isWebsocket = false;
|
2022-06-06 21:00:50 -04:00
|
|
|
|
2023-09-20 19:30:29 -04:00
|
|
|
client.setActivityTimeout(kRequestTimeout);
|
2016-03-12 13:50:43 -05:00
|
|
|
|
|
|
|
function reset() {
|
|
|
|
request = undefined;
|
|
|
|
headers = {};
|
2022-12-31 11:47:10 -05:00
|
|
|
parsing_header = true;
|
2016-03-12 13:50:43 -05:00
|
|
|
bodyToRead = -1;
|
|
|
|
body = undefined;
|
2022-06-17 14:51:24 -04:00
|
|
|
client.info = 'reset';
|
2023-09-20 19:30:29 -04:00
|
|
|
client.setActivityTimeout(kRequestTimeout);
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function finish() {
|
2022-06-17 14:51:24 -04:00
|
|
|
client.info = 'finishing';
|
2022-12-31 11:47:10 -05:00
|
|
|
let requestObject = new Request(request[0], request[1], request[2], headers, body, client);
|
|
|
|
let response = new Response(requestObject, client);
|
2016-03-12 13:50:43 -05:00
|
|
|
try {
|
|
|
|
handleRequest(requestObject, response)
|
|
|
|
if (client.isConnected) {
|
|
|
|
reset();
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
response.reportError(error);
|
2022-06-02 06:58:22 -04:00
|
|
|
client.close();
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
client.onError(function(error) {
|
|
|
|
logError(client.peerName + " - - [" + new Date() + "] " + error);
|
|
|
|
});
|
|
|
|
|
|
|
|
client.read(function(data) {
|
2022-06-17 14:51:24 -04:00
|
|
|
readCount++;
|
2016-03-12 13:50:43 -05:00
|
|
|
if (data) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let newBuffer = new Uint8Array(inputBuffer.length + data.length);
|
2016-12-21 15:19:23 -05:00
|
|
|
newBuffer.set(inputBuffer, 0);
|
|
|
|
newBuffer.set(data, inputBuffer.length);
|
|
|
|
inputBuffer = newBuffer;
|
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
if (parsing_header)
|
|
|
|
{
|
2023-07-22 21:12:11 -04:00
|
|
|
let result = parseHttpRequest(inputBuffer, inputBuffer.length - data.length);
|
2022-12-31 11:47:10 -05:00
|
|
|
if (result) {
|
|
|
|
if (typeof result === 'number') {
|
|
|
|
if (result == -2) {
|
|
|
|
/* More. */
|
|
|
|
} else {
|
2023-10-15 12:55:25 -04:00
|
|
|
badRequest(client, `Bad request(parse=${result}, length=${inputBuffer.length - data.length}).`);
|
2022-12-31 11:47:10 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
} else if (typeof result === 'object') {
|
2023-09-20 19:30:29 -04:00
|
|
|
client.setActivityTimeout(kStallTimeout);
|
2022-12-31 11:47:10 -05:00
|
|
|
request = [
|
|
|
|
result.method,
|
|
|
|
result.path,
|
|
|
|
`HTTP/1.${result.minor_version}`,
|
|
|
|
];
|
2023-01-11 18:39:42 -05:00
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
headers = Object.fromEntries(Object.entries(result.headers).map(x => [x[0].toLowerCase(), x[1]]));
|
|
|
|
parsing_header = false;
|
|
|
|
inputBuffer = inputBuffer.slice(result.bytes_parsed);
|
|
|
|
|
2023-03-12 18:16:18 -04:00
|
|
|
if (!client.tls && tildefriends.https_port && core.globalSettings.http_redirect && !result.path.startsWith('/.well-known/')) {
|
2023-01-11 18:39:42 -05:00
|
|
|
let requestObject = new Request(request[0], request[1], request[2], headers, body, client);
|
|
|
|
let response = new Response(requestObject, client);
|
|
|
|
response.writeHead(303, {"Location": `${core.globalSettings.http_redirect}${result.path}`, "Content-Length": "0"});
|
|
|
|
response.end();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
if (headers["content-length"] != undefined) {
|
|
|
|
bodyToRead = parseInt(headers["content-length"]);
|
|
|
|
if (bodyToRead > 16 * 1024 * 1024) {
|
|
|
|
badRequest(client, 'Request too large: ' + bodyToRead + '.');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
body = new Uint8Array(bodyToRead);
|
|
|
|
client.info = 'waiting for body';
|
|
|
|
} else if (headers["connection"]
|
|
|
|
&& headers["connection"].toLowerCase().split(",").map(x => x.trim()).indexOf("upgrade") != -1
|
|
|
|
&& headers["upgrade"]
|
|
|
|
&& headers["upgrade"].toLowerCase() == "websocket") {
|
|
|
|
isWebsocket = true;
|
|
|
|
client.info = 'websocket';
|
|
|
|
let requestObject = new Request(request[0], request[1], request[2], headers, body, client);
|
|
|
|
let response = new Response(requestObject, client);
|
|
|
|
handleWebSocketRequest(requestObject, response, client);
|
|
|
|
/* Prevent the timeout from disconnecting us. */
|
2023-09-20 19:30:29 -04:00
|
|
|
client.setActivityTimeout();
|
2022-12-31 11:47:10 -05:00
|
|
|
} else {
|
|
|
|
finish();
|
|
|
|
}
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
2022-12-31 11:47:10 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!parsing_header && inputBuffer.length)
|
|
|
|
{
|
|
|
|
let offset = body.length - bodyToRead;
|
|
|
|
let length = Math.min(inputBuffer.length, body.length - offset);
|
|
|
|
if (inputBuffer.length > body.length - offset) {
|
|
|
|
body.set(inputBuffer.slice(0, length), offset);
|
|
|
|
inputBuffer = inputBuffer.slice(length);
|
2016-03-12 13:50:43 -05:00
|
|
|
} else {
|
2022-12-31 11:47:10 -05:00
|
|
|
body.set(inputBuffer, offset);
|
2023-01-01 13:12:42 -05:00
|
|
|
inputBuffer = inputBuffer.slice(inputBuffer.length);
|
2022-12-31 11:47:10 -05:00
|
|
|
}
|
|
|
|
bodyToRead -= length;
|
|
|
|
if (bodyToRead <= 0) {
|
|
|
|
finish();
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
}
|
2022-06-17 14:51:24 -04:00
|
|
|
} else {
|
|
|
|
client.info = 'EOF';
|
|
|
|
client.close();
|
2016-03-12 13:50:43 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let kBacklog = 8;
|
2023-10-26 12:41:57 -04:00
|
|
|
let kHost = platform() == 'haiku' ? 'localhost' : '::';
|
2016-03-12 13:50:43 -05:00
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let socket = new Socket();
|
2023-03-18 08:28:48 -04:00
|
|
|
socket.bind(kHost, tildefriends.http_port).then(function(port) {
|
|
|
|
print("bound to", port);
|
|
|
|
print("checking", tildefriends.args.out_http_port_file);
|
|
|
|
if (tildefriends.args.out_http_port_file) {
|
|
|
|
print("going to write the file");
|
|
|
|
File.writeFile(tildefriends.args.out_http_port_file, port.toString() + '\n').then(function(r) {
|
|
|
|
print("wrote port file", tildefriends.args.out_http_port_file, r);
|
|
|
|
}).catch(function() {
|
|
|
|
print("failed to write port file");
|
|
|
|
});
|
|
|
|
}
|
2023-02-05 21:29:00 -05:00
|
|
|
let listenResult = socket.listen(kBacklog, async function() {
|
|
|
|
try {
|
|
|
|
let client = await socket.accept();
|
|
|
|
client.noDelay = true;
|
|
|
|
handleConnection(client);
|
|
|
|
} catch (error) {
|
2021-01-02 13:10:00 -05:00
|
|
|
logError("[" + new Date() + "] accept error " + error);
|
2023-02-05 21:29:00 -05:00
|
|
|
}
|
2016-03-12 13:50:43 -05:00
|
|
|
});
|
|
|
|
}).catch(function(error) {
|
2021-01-02 13:10:00 -05:00
|
|
|
logError("[" + new Date() + "] bind error " + error);
|
2016-03-12 13:50:43 -05:00
|
|
|
});
|
|
|
|
|
2021-01-02 13:10:00 -05:00
|
|
|
if (tildefriends.https_port) {
|
2022-12-31 11:47:10 -05:00
|
|
|
let tls = {};
|
|
|
|
let secureSocket = new Socket();
|
2021-01-02 13:10:00 -05:00
|
|
|
secureSocket.bind(kHost, tildefriends.https_port).then(function() {
|
2022-01-04 20:58:12 -05:00
|
|
|
return secureSocket.listen(kBacklog, async function() {
|
|
|
|
try {
|
2022-12-31 11:47:10 -05:00
|
|
|
let client = await secureSocket.accept();
|
2023-02-05 21:29:00 -05:00
|
|
|
client.noDelay = true;
|
2022-01-08 20:36:29 -05:00
|
|
|
client.tls = true;
|
2017-10-12 19:29:33 -04:00
|
|
|
const kCertificatePath = "data/httpd/certificate.pem";
|
|
|
|
const kPrivateKeyPath = "data/httpd/privatekey.pem";
|
|
|
|
|
2022-12-31 11:47:10 -05:00
|
|
|
let stat = await Promise.all([
|
2022-01-04 20:58:12 -05:00
|
|
|
await File.stat(kCertificatePath),
|
|
|
|
await File.stat(kPrivateKeyPath),
|
|
|
|
]);
|
|
|
|
if (!tls.context ||
|
|
|
|
tls.certStat.mtime != stat[0].mtime ||
|
|
|
|
tls.certStat.size != stat[0].size ||
|
|
|
|
tls.keyStat.mtime != stat[1].mtime ||
|
|
|
|
tls.keyStat.size != stat[1].size) {
|
|
|
|
print("Reloading " + kCertificatePath + " and " + kPrivateKeyPath);
|
2022-12-31 11:47:10 -05:00
|
|
|
let privateKey = utf8Decode(await File.readFile(kPrivateKeyPath));
|
|
|
|
let certificate = utf8Decode(await File.readFile(kCertificatePath));
|
2022-01-04 20:58:12 -05:00
|
|
|
|
|
|
|
tls.context = new TlsContext();
|
|
|
|
tls.context.setPrivateKey(privateKey);
|
|
|
|
tls.context.setCertificate(certificate);
|
|
|
|
tls.certStat = stat[0];
|
|
|
|
tls.keyStat = stat[1];
|
|
|
|
}
|
2017-10-12 19:29:33 -04:00
|
|
|
|
2022-06-02 06:58:22 -04:00
|
|
|
let result = client.startTls(tls.context);
|
2022-01-04 20:58:12 -05:00
|
|
|
handleConnection(client);
|
2022-06-02 06:58:22 -04:00
|
|
|
return result;
|
2022-01-04 20:58:12 -05:00
|
|
|
} catch (error) {
|
|
|
|
logError("[" + new Date() + "] [" + client.peerName + "] " + error);
|
|
|
|
}
|
2016-03-12 13:50:43 -05:00
|
|
|
});
|
2017-10-12 19:29:33 -04:00
|
|
|
}).catch(function(error) {
|
2021-01-02 13:10:00 -05:00
|
|
|
logError("[" + new Date() + "] bind error " + error);
|
2016-03-12 13:50:43 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-06-18 13:39:08 -04:00
|
|
|
export { all, registerSocketHandler };
|