1
0
Fork 0
forked from svrjs/svrjs

Replace ES5-style functions with ES6-style ones

This commit is contained in:
Dorian Niemiec 2024-08-27 10:54:08 +02:00
parent 79f8f2ddf9
commit 5a3e6765f1
16 changed files with 107 additions and 107 deletions

View file

@ -41,16 +41,16 @@ try {
} }
} catch (err) { } catch (err) {
http2.__disabled__ = null; http2.__disabled__ = null;
http2.createServer = function () { http2.createServer = () => {
throw new Error("HTTP/2 support is not present"); throw new Error("HTTP/2 support is not present");
}; };
http2.createSecureServer = function () { http2.createSecureServer = () => {
throw new Error("HTTP/2 support is not present"); throw new Error("HTTP/2 support is not present");
}; };
http2.connect = function () { http2.connect = () => {
throw new Error("HTTP/2 support is not present"); throw new Error("HTTP/2 support is not present");
}; };
http2.get = function () { http2.get = () => {
throw new Error("HTTP/2 support is not present"); throw new Error("HTTP/2 support is not present");
}; };
} }
@ -58,13 +58,13 @@ let crypto = {
__disabled__: null, __disabled__: null,
}; };
let https = { let https = {
createServer: function () { createServer: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
connect: function () { connect: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
get: function () { get: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
}; };
@ -72,7 +72,7 @@ try {
crypto = require("crypto"); crypto = require("crypto");
https = require("https"); https = require("https");
} catch (err) { } catch (err) {
http2.createSecureServer = function () { http2.createSecureServer = () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}; };
} }
@ -390,10 +390,10 @@ try {
if (!process.stdout.isTTY && !inspectorURL) { if (!process.stdout.isTTY && !inspectorURL) {
// When stdout is not a terminal and not attached to an Node.JS inspector, disable it to improve performance of SVR.JS // When stdout is not a terminal and not attached to an Node.JS inspector, disable it to improve performance of SVR.JS
console.log = function () {}; console.log = () => {};
process.stdout.write = function () {}; process.stdout.write = () => {};
process.stdout._write = function () {}; process.stdout._write = () => {};
process.stdout._writev = function () {}; process.stdout._writev = () => {};
} }
let wwwrootError = null; let wwwrootError = null;
@ -467,7 +467,7 @@ let pubip = "";
function doIpRequest(isHTTPS, options) { function doIpRequest(isHTTPS, options) {
const ipRequest = (isHTTPS ? https : http).get(options, (res) => { const ipRequest = (isHTTPS ? https : http).get(options, (res) => {
ipRequest.removeAllListeners("timeout"); ipRequest.removeAllListeners("timeout");
res.on("data", function (d) { res.on("data", (d) => {
if (res.statusCode != 200) { if (res.statusCode != 200) {
ipRequestCompleted = true; ipRequestCompleted = true;
process.emit("ipRequestCompleted"); process.emit("ipRequestCompleted");
@ -480,14 +480,14 @@ function doIpRequest(isHTTPS, options) {
} else { } else {
let callbackDone = false; let callbackDone = false;
const dnsTimeout = setTimeout(function () { const dnsTimeout = setTimeout(() => {
callbackDone = true; callbackDone = true;
ipRequestCompleted = true; ipRequestCompleted = true;
process.emit("ipRequestCompleted"); process.emit("ipRequestCompleted");
}, 3000); }, 3000);
try { try {
dns.reverse(pubip, function (err, hostnames) { dns.reverse(pubip, (err, hostnames) => {
if (callbackDone) return; if (callbackDone) return;
clearTimeout(dnsTimeout); clearTimeout(dnsTimeout);
if (!err && hostnames.length > 0) domain = hostnames[0]; if (!err && hostnames.length > 0) domain = hostnames[0];
@ -503,7 +503,7 @@ function doIpRequest(isHTTPS, options) {
} }
}); });
}); });
ipRequest.on("error", function () { ipRequest.on("error", () => {
if (crypto.__disabled__ || ipRequestGotError) { if (crypto.__disabled__ || ipRequestGotError) {
ipRequestCompleted = true; ipRequestCompleted = true;
process.emit("ipRequestCompleted"); process.emit("ipRequestCompleted");
@ -511,7 +511,7 @@ function doIpRequest(isHTTPS, options) {
ipRequestGotError = true; ipRequestGotError = true;
} }
}); });
ipRequest.on("timeout", function () { ipRequest.on("timeout", () => {
if (crypto.__disabled__ || ipRequestGotError) { if (crypto.__disabled__ || ipRequestGotError) {
ipRequestCompleted = true; ipRequestCompleted = true;
process.emit("ipRequestCompleted"); process.emit("ipRequestCompleted");
@ -594,7 +594,7 @@ if (process.serverConfig.secure) {
) )
.toString(); .toString();
const sniNames = Object.keys(process.serverConfig.sni); const sniNames = Object.keys(process.serverConfig.sni);
sniNames.forEach(function (sniName) { sniNames.forEach((sniName) => {
if ( if (
typeof sniName === "string" && typeof sniName === "string" &&
sniName.match(/\*[^*.:]*\*[^*.:]*(?:\.|:|$)/) sniName.match(/\*[^*.:]*\*[^*.:]*(?:\.|:|$)/)
@ -806,7 +806,7 @@ if (!disableMods) {
crypto.__disabled__ === undefined crypto.__disabled__ === undefined
? "var crypto = require('crypto');\r\nvar https = require('https');\r\n" ? "var crypto = require('crypto');\r\nvar https = require('https');\r\n"
: "" : ""
}var stream = require(\'stream\');\r\nvar customvar1;\r\nvar customvar2;\r\nvar customvar3;\r\nvar customvar4;\r\n\r\nfunction Mod() {}\r\nMod.prototype.callback = function callback(req, res, serverconsole, responseEnd, href, ext, uobject, search, defaultpage, users, page404, head, foot, fd, elseCallback, configJSON, callServerError, getCustomHeaders, origHref, redirect, parsePostData, authUser) {\r\nreturn function () {\r\nvar disableEndElseCallbackExecute = false;\r\nfunction filterHeaders(e){var r={};return Object.keys(e).forEach((function(t){null!==e[t]&&void 0!==e[t]&&("object"==typeof e[t]?r[t]=JSON.parse(JSON.stringify(e[t])):r[t]=e[t])})),r}\r\nfunction checkHostname(e){if(void 0===e||"*"==e)return!0;if(req.headers.host&&0==e.indexOf("*.")&&"*."!=e){var r=e.substring(2);if(req.headers.host==r||req.headers.host.indexOf("."+r)==req.headers.host.length-r.length-1)return!0}else if(req.headers.host&&req.headers.host==e)return!0;return!1}\r\nfunction checkHref(e){return href==e||"win32"==os.platform()&&href.toLowerCase()==e.toLowerCase()}\r\n`; }var stream = require(\'stream\');\r\nvar customvar1;\r\nvar customvar2;\r\nvar customvar3;\r\nvar customvar4;\r\n\r\nfunction Mod() {}\r\nMod.prototype.callback = function callback(req, res, serverconsole, responseEnd, href, ext, uobject, search, defaultpage, users, page404, head, foot, fd, elseCallback, configJSON, callServerError, getCustomHeaders, origHref, redirect, parsePostData, authUser) {\r\nreturn () => {\r\nvar disableEndElseCallbackExecute = false;\r\nfunction filterHeaders(e){var r={};return Object.keys(e).forEach(((t) => {null!==e[t]&&void 0!==e[t]&&("object"==typeof e[t]?r[t]=JSON.parse(JSON.stringify(e[t])):r[t]=e[t])})),r}\r\nfunction checkHostname(e){if(void 0===e||"*"==e)return!0;if(req.headers.host&&0==e.indexOf("*.")&&"*."!=e){var r=e.substring(2);if(req.headers.host==r||req.headers.host.indexOf("."+r)==req.headers.host.length-r.length-1)return!0}else if(req.headers.host&&req.headers.host==e)return!0;return!1}\r\nfunction checkHref(e){return href==e||"win32"==os.platform()&&href.toLowerCase()==e.toLowerCase()}\r\n`;
const modfoot = const modfoot =
"\r\nif(!disableEndElseCallbackExecute) {\r\ntry{\r\nelseCallback();\r\n} catch(err) {\r\n}\r\n}\r\n}\r\n}\r\nmodule.exports = Mod;"; "\r\nif(!disableEndElseCallbackExecute) {\r\ntry{\r\nelseCallback();\r\n} catch(err) {\r\n}\r\n}\r\n}\r\n}\r\nmodule.exports = Mod;";
// Write the modified server side script to the temp folder // Write the modified server side script to the temp folder
@ -1109,7 +1109,7 @@ if (process.serverConfig.enableHTTP2 == true) {
// Load SNI contexts into HTTP server // Load SNI contexts into HTTP server
if (process.serverConfig.secure) { if (process.serverConfig.secure) {
try { try {
sniCredentials.forEach(function (sniCredentialsSingle) { sniCredentials.forEach((sniCredentialsSingle) => {
server.addContext(sniCredentialsSingle.name, { server.addContext(sniCredentialsSingle.name, {
cert: sniCredentialsSingle.cert, cert: sniCredentialsSingle.cert,
key: sniCredentialsSingle.key, key: sniCredentialsSingle.key,
@ -1151,7 +1151,7 @@ server.on("request", requestHandler);
server.on("checkExpectation", requestHandler); server.on("checkExpectation", requestHandler);
server.on("connect", proxyHandler); server.on("connect", proxyHandler);
server.on("clientError", clientErrorHandler); server.on("clientError", clientErrorHandler);
server.on("error", function (err) { server.on("error", (err) => {
serverErrorHandler(err, false, server, start); serverErrorHandler(err, false, server, start);
}); });
server.on("listening", () => { server.on("listening", () => {
@ -1160,14 +1160,14 @@ server.on("listening", () => {
}); });
if (process.serverConfig.secure) { if (process.serverConfig.secure) {
server.prependListener("connection", function (sock) { server.prependListener("connection", (sock) => {
sock.reallyDestroy = sock.destroy; sock.reallyDestroy = sock.destroy;
sock.destroy = function () { sock.destroy = () => {
sock.toDestroy = true; sock.toDestroy = true;
}; };
}); });
server.prependListener("tlsClientError", function (err, sock) { server.prependListener("tlsClientError", (err, sock) => {
if ( if (
err.code == "ERR_SSL_HTTP_REQUEST" || err.code == "ERR_SSL_HTTP_REQUEST" ||
err.message.indexOf("http request") != -1 err.message.indexOf("http request") != -1
@ -1176,13 +1176,13 @@ if (process.serverConfig.secure) {
sock._readableState = sock._parent._readableState; sock._readableState = sock._parent._readableState;
sock._writableState = sock._parent._writableState; sock._writableState = sock._parent._writableState;
sock._parent.toDestroy = false; sock._parent.toDestroy = false;
sock.pipe = function (a, b, c) { sock.pipe = (a, b, c) => {
sock._parent.pipe(a, b, c); sock._parent.pipe(a, b, c);
}; };
sock.write = function (a, b, c) { sock.write = (a, b, c) => {
sock._parent.write(a, b, c); sock._parent.write(a, b, c);
}; };
sock.end = function (a, b, c) { sock.end = (a, b, c) => {
sock._parent.end(a, b, c); sock._parent.end(a, b, c);
}; };
sock.destroyed = sock._parent.destroyed; sock.destroyed = sock._parent.destroyed;
@ -1190,7 +1190,7 @@ if (process.serverConfig.secure) {
sock.writable = sock._parent.writable; sock.writable = sock._parent.writable;
sock.remoteAddress = sock._parent.remoteAddress; sock.remoteAddress = sock._parent.remoteAddress;
sock.remotePort = sock._parent.remoteAddress; sock.remotePort = sock._parent.remoteAddress;
sock.destroy = function (a, b, c) { sock.destroy = (a, b, c) => {
try { try {
sock._parent.destroy(a, b, c); sock._parent.destroy(a, b, c);
sock.destroyed = sock._parent.destroyed; sock.destroyed = sock._parent.destroyed;
@ -1208,14 +1208,14 @@ if (process.serverConfig.secure) {
} }
}); });
server.prependListener("secureConnection", function (sock) { server.prependListener("secureConnection", (sock) => {
sock._parent.destroy = sock._parent.reallyDestroy; sock._parent.destroy = sock._parent.reallyDestroy;
delete sock._parent.reallyDestroy; delete sock._parent.reallyDestroy;
}); });
if (process.serverConfig.enableOCSPStapling && !ocsp._errored) { if (process.serverConfig.enableOCSPStapling && !ocsp._errored) {
server.on("OCSPRequest", function (cert, issuer, callback) { server.on("OCSPRequest", (cert, issuer, callback) => {
ocsp.getOCSPURI(cert, function (err, uri) { ocsp.getOCSPURI(cert, (err, uri) => {
if (err) return callback(err); if (err) return callback(err);
const req = ocsp.request.generate(cert, issuer); const req = ocsp.request.generate(cert, issuer);
@ -1306,10 +1306,10 @@ let commands = {
server.listening server.listening
) { ) {
try { try {
server.close(function () { server.close(() => {
if (server2.listening) { if (server2.listening) {
try { try {
server2.close(function () { server2.close(() => {
if (!process.removeFakeIPC) { if (!process.removeFakeIPC) {
if (typeof retcode == "number") { if (typeof retcode == "number") {
process.exit(retcode); process.exit(retcode);
@ -1458,7 +1458,7 @@ function SVRJSFork() {
// Add event listeners // Add event listeners
if (newWorker.on) { if (newWorker.on) {
newWorker.on("error", function (err) { newWorker.on("error", (err) => {
if (!exiting) if (!exiting)
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
"There was a problem when handling " + "There was a problem when handling " +
@ -1467,7 +1467,7 @@ function SVRJSFork() {
err.message, err.message,
); );
}); });
newWorker.on("exit", function () { newWorker.on("exit", () => {
if (!exiting && Object.keys(cluster.workers).length == 0) { if (!exiting && Object.keys(cluster.workers).length == 0) {
crashed = true; crashed = true;
SVRJSFork(); SVRJSFork();
@ -1497,8 +1497,8 @@ function forkWorkers(workersToFork, callback) {
SVRJSFork(); SVRJSFork();
} else { } else {
setTimeout( setTimeout(
(function (i) { ((i) => {
return function () { return () => {
SVRJSFork(); SVRJSFork();
if (i >= workersToFork - 1) callback(); if (i >= workersToFork - 1) callback();
}; };
@ -1690,7 +1690,7 @@ function start(init) {
/^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/, /^(?:0\.|1\.0\.|1\.1\.[0-9](?![0-9])|1\.1\.1[0-2](?![0-9]))/,
) )
) && ) &&
process.serverConfig.users.some(function (entry) { process.serverConfig.users.some((entry) => {
return entry.pbkdf2; return entry.pbkdf2;
}) })
) )
@ -1769,7 +1769,7 @@ function start(init) {
// Display mod and server-side JavaScript errors // Display mod and server-side JavaScript errors
if (process.isPrimary || process.isPrimary === undefined) { if (process.isPrimary || process.isPrimary === undefined) {
modLoadingErrors.forEach(function (modLoadingError) { modLoadingErrors.forEach((modLoadingError) => {
serverconsole.locwarnmessage( serverconsole.locwarnmessage(
`There was a problem while loading a "${String(modLoadingError.modName).replace(/[\r\n]/g, "")}" mod.`, `There was a problem while loading a "${String(modLoadingError.modName).replace(/[\r\n]/g, "")}" mod.`,
); );
@ -1930,7 +1930,7 @@ function start(init) {
let workersToFork = 1; let workersToFork = 1;
if (cluster.isPrimary === undefined) { if (cluster.isPrimary === undefined) {
setInterval(function () { setInterval(() => {
try { try {
saveConfig(); saveConfig();
serverconsole.locmessage("Configuration saved."); serverconsole.locmessage("Configuration saved.");
@ -1939,7 +1939,7 @@ function start(init) {
} }
}, 300000); }, 300000);
} else if (cluster.isPrimary) { } else if (cluster.isPrimary) {
setInterval(function () { setInterval(() => {
var allWorkers = Object.keys(cluster.workers); var allWorkers = Object.keys(cluster.workers);
var goodWorkers = []; var goodWorkers = [];
@ -1954,7 +1954,7 @@ function start(init) {
isWorkerHungUpBuff2 = true; isWorkerHungUpBuff2 = true;
cluster.workers[allWorkers[_id]].on("message", msgListener); cluster.workers[allWorkers[_id]].on("message", msgListener);
cluster.workers[allWorkers[_id]].send("\x14PINGPING"); cluster.workers[allWorkers[_id]].send("\x14PINGPING");
setTimeout(function () { setTimeout(() => {
if (isWorkerHungUpBuff2) { if (isWorkerHungUpBuff2) {
checkWorker(callback, _id + 1); checkWorker(callback, _id + 1);
} else { } else {
@ -1973,7 +1973,7 @@ function start(init) {
checkWorker(callback, _id + 1); checkWorker(callback, _id + 1);
} }
}; };
checkWorker(function () { checkWorker(() => {
const wN = Math.floor(Math.random() * goodWorkers.length); //Send a configuration saving message to a random worker. const wN = Math.floor(Math.random() * goodWorkers.length); //Send a configuration saving message to a random worker.
try { try {
if (cluster.workers[goodWorkers[wN]]) { if (cluster.workers[goodWorkers[wN]]) {
@ -1995,7 +1995,7 @@ function start(init) {
} }
if (!cluster.isPrimary && cluster.isPrimary !== undefined) { if (!cluster.isPrimary && cluster.isPrimary !== undefined) {
process.on("message", function (line) { process.on("message", (line) => {
try { try {
if (line == "") { if (line == "") {
// Does Nothing // Does Nothing
@ -2052,7 +2052,7 @@ function start(init) {
prompt: "", prompt: "",
}); });
rla.prompt(); rla.prompt();
rla.on("line", function (line) { rla.on("line", (line) => {
line = line.trim(); line = line.trim();
const argss = line.split(" "); const argss = line.split(" ");
const command = argss.shift(); const command = argss.shift();
@ -2083,7 +2083,7 @@ function start(init) {
closedMaster = true; closedMaster = true;
workersToFork = getWorkerCountToFork(); workersToFork = getWorkerCountToFork();
forkWorkers(workersToFork, function () { forkWorkers(workersToFork, () => {
SVRJSInitialized = true; SVRJSInitialized = true;
exiting = false; exiting = false;
serverconsole.climessage(`${name} workers restarted.`); serverconsole.climessage(`${name} workers restarted.`);
@ -2110,7 +2110,7 @@ function start(init) {
} }
}); });
if (command == "stop") { if (command == "stop") {
setTimeout(function () { setTimeout(() => {
commands[command](argss, serverconsole.climessage); commands[command](argss, serverconsole.climessage);
}, 50); }, 50);
} }
@ -2132,12 +2132,12 @@ function start(init) {
// Cluster forking code // Cluster forking code
if (cluster.isPrimary !== undefined && init) { if (cluster.isPrimary !== undefined && init) {
workersToFork = getWorkerCountToFork(); workersToFork = getWorkerCountToFork();
forkWorkers(workersToFork, function () { forkWorkers(workersToFork, () => {
SVRJSInitialized = true; SVRJSInitialized = true;
}); });
// Hangup check and restart // Hangup check and restart
setInterval(function () { setInterval(() => {
if (!closedMaster && !exiting) { if (!closedMaster && !exiting) {
let chksocket = {}; let chksocket = {};
if ( if (
@ -2167,21 +2167,21 @@ function start(init) {
timeout: 1620, timeout: 1620,
rejectUnauthorized: false, rejectUnauthorized: false,
}, },
function (res) { (res) => {
chksocket.removeAllListeners("timeout"); chksocket.removeAllListeners("timeout");
res.destroy(); res.destroy();
res.on("data", function () {}); res.on("data", () => {});
res.on("end", function () {}); res.on("end", () => {});
crashed = false; crashed = false;
}, },
) )
.on("error", function () { .on("error", () => {
if (!exiting) { if (!exiting) {
if (!crashed) SVRJSFork(); if (!crashed) SVRJSFork();
else crashed = false; else crashed = false;
} }
}) })
.on("timeout", function () { .on("timeout", () => {
if (!exiting) SVRJSFork(); if (!exiting) SVRJSFork();
crashed = true; crashed = true;
}); });
@ -2206,13 +2206,13 @@ function start(init) {
":" + ":" +
process.serverConfig.port.toString(), process.serverConfig.port.toString(),
); );
connection.on("error", function () { connection.on("error", () => {
if (!exiting) { if (!exiting) {
if (!crashed) SVRJSFork(); if (!crashed) SVRJSFork();
else crashed = false; else crashed = false;
} }
}); });
connection.setTimeout(1620, function () { connection.setTimeout(1620, () => {
if (!exiting) SVRJSFork(); if (!exiting) SVRJSFork();
crashed = true; crashed = true;
}); });
@ -2221,11 +2221,11 @@ function start(init) {
"x-svr-js-from-main-thread": "true", "x-svr-js-from-main-thread": "true",
"user-agent": generateServerString(true), "user-agent": generateServerString(true),
}); });
chksocket.on("response", function () { chksocket.on("response", () => {
connection.close(); connection.close();
crashed = false; crashed = false;
}); });
chksocket.on("error", function () { chksocket.on("error", () => {
if (!exiting) { if (!exiting) {
if (!crashed) SVRJSFork(); if (!crashed) SVRJSFork();
else crashed = false; else crashed = false;
@ -2254,21 +2254,21 @@ function start(init) {
}, },
timeout: 1620, timeout: 1620,
}, },
function (res) { (res) => {
chksocket.removeAllListeners("timeout"); chksocket.removeAllListeners("timeout");
res.destroy(); res.destroy();
res.on("data", function () {}); res.on("data", () => {});
res.on("end", function () {}); res.on("end", () => {});
crashed = false; crashed = false;
}, },
) )
.on("error", function () { .on("error", () => {
if (!exiting) { if (!exiting) {
if (!crashed) SVRJSFork(); if (!crashed) SVRJSFork();
else crashed = false; else crashed = false;
} }
}) })
.on("timeout", function () { .on("timeout", () => {
if (!exiting) SVRJSFork(); if (!exiting) SVRJSFork();
crashed = true; crashed = true;
}); });
@ -2281,8 +2281,8 @@ function start(init) {
!process.serverConfig.disableUnusedWorkerTermination && !process.serverConfig.disableUnusedWorkerTermination &&
cluster.isPrimary !== undefined cluster.isPrimary !== undefined
) { ) {
setTimeout(function () { setTimeout(() => {
setInterval(function () { setInterval(() => {
if (!closedMaster && !exiting) { if (!closedMaster && !exiting) {
const allWorkers = Object.keys(cluster.workers); const allWorkers = Object.keys(cluster.workers);
@ -2307,7 +2307,7 @@ function start(init) {
msgListener, msgListener,
); );
cluster.workers[allWorkers[_id]].send("\x14KILLPING"); cluster.workers[allWorkers[_id]].send("\x14KILLPING");
setTimeout(function () { setTimeout(() => {
if (isWorkerHungUpBuff) { if (isWorkerHungUpBuff) {
checkWorker(callback, _id + 1); checkWorker(callback, _id + 1);
} else { } else {
@ -2378,7 +2378,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
process.on("uncaughtException", crashHandlerMaster); process.on("uncaughtException", crashHandlerMaster);
process.on("unhandledRejection", crashHandlerMaster); process.on("unhandledRejection", crashHandlerMaster);
process.on("exit", function (code) { process.on("exit", (code) => {
try { try {
if (!configJSONRErr && !configJSONPErr) { if (!configJSONRErr && !configJSONPErr) {
saveConfig(); saveConfig();
@ -2414,14 +2414,14 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
} }
serverconsole.locmessage("Server closed with exit code: " + code); serverconsole.locmessage("Server closed with exit code: " + code);
}); });
process.on("warning", function (warning) { process.on("warning", (warning) => {
serverconsole.locwarnmessage(warning.message); serverconsole.locwarnmessage(warning.message);
if (generateErrorStack(warning)) { if (generateErrorStack(warning)) {
serverconsole.locwarnmessage("Stack:"); serverconsole.locwarnmessage("Stack:");
serverconsole.locwarnmessage(generateErrorStack(warning)); serverconsole.locwarnmessage(generateErrorStack(warning));
} }
}); });
process.on("SIGINT", function () { process.on("SIGINT", () => {
if (cluster.isPrimary !== undefined) { if (cluster.isPrimary !== undefined) {
exiting = true; exiting = true;
const allWorkers = Object.keys(cluster.workers); const allWorkers = Object.keys(cluster.workers);
@ -2453,7 +2453,7 @@ if (cluster.isPrimary || cluster.isPrimary === undefined) {
process.on("unhandledRejection", crashHandler); process.on("unhandledRejection", crashHandler);
// Warning handler // Warning handler
process.on("warning", function (warning) { process.on("warning", (warning) => {
serverconsole.locwarnmessage(warning.message); serverconsole.locwarnmessage(warning.message);
if (warning.stack) { if (warning.stack) {
serverconsole.locwarnmessage("Stack:"); serverconsole.locwarnmessage("Stack:");
@ -2469,7 +2469,7 @@ try {
serverconsole.locerrmessage(`There was a problem starting ${name}!!!`); serverconsole.locerrmessage(`There was a problem starting ${name}!!!`);
serverconsole.locerrmessage("Stack:"); serverconsole.locerrmessage("Stack:");
serverconsole.locerrmessage(generateErrorStack(err)); serverconsole.locerrmessage(generateErrorStack(err));
setTimeout(function () { setTimeout(() => {
process.exit(err.errno !== undefined ? err.errno : 1); process.exit(err.errno !== undefined ? err.errno : 1);
}, 10); }, 10);
} }

View file

@ -16,7 +16,7 @@ if (process.serverConfig.secure) {
getInitializePath(process.serverConfig.cert), getInitializePath(process.serverConfig.cert),
); );
forbiddenPaths.certificates.push(getInitializePath(process.serverConfig.key)); forbiddenPaths.certificates.push(getInitializePath(process.serverConfig.key));
Object.keys(process.serverConfig.sni).forEach(function (sniHostname) { Object.keys(process.serverConfig.sni).forEach((sniHostname) => {
forbiddenPaths.certificates.push( forbiddenPaths.certificates.push(
getInitializePath(process.serverConfig.sni[sniHostname].cert), getInitializePath(process.serverConfig.sni[sniHostname].cert),
); );

View file

@ -40,11 +40,11 @@ process.serverConfig.nonStandardCodes.forEach((nonStandardCodeRaw) => {
}); });
if (!cluster.isPrimary) { if (!cluster.isPrimary) {
passwordHashCacheIntervalId = setInterval(function () { passwordHashCacheIntervalId = setInterval(() => {
pbkdf2Cache = pbkdf2Cache.filter(function (entry) { pbkdf2Cache = pbkdf2Cache.filter((entry) => {
return entry.addDate > new Date() - 3600000; return entry.addDate > new Date() - 3600000;
}); });
scryptCache = scryptCache.filter(function (entry) { scryptCache = scryptCache.filter((entry) => {
return entry.addDate > new Date() - 3600000; return entry.addDate > new Date() - 3600000;
}); });
}, 1800000); }, 1800000);
@ -170,7 +170,7 @@ module.exports = (req, res, logFacilities, config, next) => {
// Function to check if passwords match // Function to check if passwords match
const checkIfPasswordMatches = (list, password, callback, _i) => { const checkIfPasswordMatches = (list, password, callback, _i) => {
if (!_i) _i = 0; if (!_i) _i = 0;
const cb = function (hash) { const cb = (hash) => {
if (hash == list[_i].pass) { if (hash == list[_i].pass) {
callback(true); callback(true);
} else if (_i >= list.length - 1) { } else if (_i >= list.length - 1) {
@ -191,7 +191,7 @@ module.exports = (req, res, logFacilities, config, next) => {
); );
return; return;
} else { } else {
cacheEntry = scryptCache.find(function (entry) { cacheEntry = scryptCache.find((entry) => {
return ( return (
entry.password == hashedPassword && entry.salt == list[_i].salt entry.password == hashedPassword && entry.salt == list[_i].salt
); );
@ -203,7 +203,7 @@ module.exports = (req, res, logFacilities, config, next) => {
password, password,
list[_i].salt, list[_i].salt,
64, 64,
function (err, derivedKey) { (err, derivedKey) => {
if (err) { if (err) {
res.error(500, err); res.error(500, err);
} else { } else {
@ -230,7 +230,7 @@ module.exports = (req, res, logFacilities, config, next) => {
); );
return; return;
} else { } else {
cacheEntry = pbkdf2Cache.find(function (entry) { cacheEntry = pbkdf2Cache.find((entry) => {
return ( return (
entry.password == hashedPassword && entry.salt == list[_i].salt entry.password == hashedPassword && entry.salt == list[_i].salt
); );
@ -244,7 +244,7 @@ module.exports = (req, res, logFacilities, config, next) => {
36250, 36250,
64, 64,
"sha512", "sha512",
function (err, derivedKey) { (err, derivedKey) => {
if (err) { if (err) {
res.error(500, err); res.error(500, err);
} else { } else {
@ -304,7 +304,7 @@ module.exports = (req, res, logFacilities, config, next) => {
let pbkdf2Count = 0; let pbkdf2Count = 0;
let scryptCount = 0; let scryptCount = 0;
if (!authcode.userList || authcode.userList.indexOf(username) > -1) { if (!authcode.userList || authcode.userList.indexOf(username) > -1) {
usernameMatch = config.users.filter(function (entry) { usernameMatch = config.users.filter((entry) => {
if (entry.scrypt) { if (entry.scrypt) {
scryptCount++; scryptCount++;
} else if (entry.pbkdf2) { } else if (entry.pbkdf2) {
@ -331,7 +331,7 @@ module.exports = (req, res, logFacilities, config, next) => {
} }
usernameMatch.push(fakeCredentials); usernameMatch.push(fakeCredentials);
} }
checkIfPasswordMatches(usernameMatch, password, function (authorized) { checkIfPasswordMatches(usernameMatch, password, (authorized) => {
try { try {
if (!authorized) { if (!authorized) {
if (bruteProtection) { if (bruteProtection) {

View file

@ -11,7 +11,7 @@ module.exports = (req, res, logFacilities, config, next) => {
) { ) {
fs.stat( fs.stat(
"." + decodeURIComponent(req.parsedURL.pathname), "." + decodeURIComponent(req.parsedURL.pathname),
function (err, stats) { (err, stats) => {
if (err || !stats.isDirectory()) { if (err || !stats.isDirectory()) {
try { try {
next(); next();

View file

@ -1,7 +1,7 @@
module.exports = (req, res, logFacilities, config, next) => { module.exports = (req, res, logFacilities, config, next) => {
if (!req.isProxy) { if (!req.isProxy) {
var hkh = config.getCustomHeaders(); var hkh = config.getCustomHeaders();
Object.keys(hkh).forEach(function (hkS) { Object.keys(hkh).forEach((hkS) => {
try { try {
res.setHeader(hkS, hkh[hkS]); res.setHeader(hkS, hkh[hkS]);
} catch (err) { } catch (err) {

View file

@ -61,7 +61,7 @@ module.exports = (req, res, logFacilities, config, next) => {
) { ) {
rewrittenURL = tempRewrittenURL; rewrittenURL = tempRewrittenURL;
try { try {
mapEntry.replacements.forEach(function (replacement) { mapEntry.replacements.forEach((replacement) => {
rewrittenURL = rewrittenURL.replace( rewrittenURL = rewrittenURL.replace(
createRegex(replacement.regex), createRegex(replacement.regex),
replacement.replacement, replacement.replacement,
@ -80,7 +80,7 @@ module.exports = (req, res, logFacilities, config, next) => {
}; };
// Rewrite URLs // Rewrite URLs
rewriteURL(req.url, config.rewriteMap, function (err, rewrittenURL) { rewriteURL(req.url, config.rewriteMap, (err, rewrittenURL) => {
if (err) { if (err) {
res.error(500, err); res.error(500, err);
return; return;

View file

@ -57,7 +57,7 @@ module.exports = (req, res, logFacilities, config, next) => {
config.enableDirectoryListing === undefined; config.enableDirectoryListing === undefined;
if (!config.enableDirectoryListingVHost) return main; if (!config.enableDirectoryListingVHost) return main;
let vhostP = null; let vhostP = null;
config.enableDirectoryListingVHost.every(function (vhost) { config.enableDirectoryListingVHost.every((vhost) => {
if ( if (
matchHostname(vhost.host, hostname) && matchHostname(vhost.host, hostname) &&
ipMatch(vhost.ip, localAddress) ipMatch(vhost.ip, localAddress)

View file

@ -35,7 +35,7 @@ module.exports = (req, res, logFacilities, config, next) => {
: req.url; : req.url;
let urlWithPostfix = preparedReqUrl3; let urlWithPostfix = preparedReqUrl3;
let postfixPrefix = ""; let postfixPrefix = "";
config.wwwrootPostfixPrefixesVHost.every(function (currentPostfixPrefix) { config.wwwrootPostfixPrefixesVHost.every((currentPostfixPrefix) => {
if (preparedReqUrl3.indexOf(currentPostfixPrefix) == 0) { if (preparedReqUrl3.indexOf(currentPostfixPrefix) == 0) {
if (currentPostfixPrefix.match(/\/+$/)) if (currentPostfixPrefix.match(/\/+$/))
postfixPrefix = currentPostfixPrefix.replace(/\/+$/, ""); postfixPrefix = currentPostfixPrefix.replace(/\/+$/, "");
@ -53,7 +53,7 @@ module.exports = (req, res, logFacilities, config, next) => {
return true; return true;
} }
}); });
config.wwwrootPostfixesVHost.every(function (postfixEntry) { config.wwwrootPostfixesVHost.every((postfixEntry) => {
if ( if (
matchHostname(postfixEntry.host) && matchHostname(postfixEntry.host) &&
ipMatch( ipMatch(

View file

@ -2,7 +2,7 @@ const fs = require("fs");
function deleteFolderRecursive(path) { function deleteFolderRecursive(path) {
if (fs.existsSync(path)) { if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file) { fs.readdirSync(path).forEach((file) => {
const curPath = path + "/" + file; const curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) { if (fs.statSync(curPath).isDirectory()) {
// recurse // recurse

View file

@ -34,7 +34,7 @@ function isForbiddenPath(decodedHref, match) {
); );
} }
if (typeof forbiddenPath === "object") { if (typeof forbiddenPath === "object") {
return forbiddenPath.some(function (forbiddenPathSingle) { return forbiddenPath.some((forbiddenPathSingle) => {
return ( return (
decodedHref === forbiddenPathSingle || decodedHref === forbiddenPathSingle ||
(os.platform() === "win32" && (os.platform() === "win32" &&
@ -61,7 +61,7 @@ function isIndexOfForbiddenPath(decodedHref, match) {
); );
} }
if (typeof forbiddenPath === "object") { if (typeof forbiddenPath === "object") {
return forbiddenPath.some(function (forbiddenPathSingle) { return forbiddenPath.some((forbiddenPathSingle) => {
return ( return (
decodedHref === forbiddenPathSingle || decodedHref === forbiddenPathSingle ||
decodedHref.indexOf(forbiddenPathSingle + "/") === 0 || decodedHref.indexOf(forbiddenPathSingle + "/") === 0 ||

View file

@ -5,7 +5,7 @@ function generateErrorStack(errorObject) {
// If the error stack starts with the error name, return the original stack (it is V8-style then). // If the error stack starts with the error name, return the original stack (it is V8-style then).
if ( if (
errorStack.some(function (errorStackLine) { errorStack.some((errorStackLine) => {
return errorStackLine.indexOf(errorObject.name) == 0; return errorStackLine.indexOf(errorObject.name) == 0;
}) })
) { ) {
@ -20,7 +20,7 @@ function generateErrorStack(errorObject) {
]; ];
// Process each line of the original error stack. // Process each line of the original error stack.
errorStack.forEach(function (errorStackLine) { errorStack.forEach((errorStackLine) => {
if (errorStackLine != "") { if (errorStackLine != "") {
// Split the line into function and location parts (if available). // Split the line into function and location parts (if available).
var errorFrame = errorStackLine.split("@"); var errorFrame = errorStackLine.split("@");

View file

@ -49,7 +49,7 @@ module.exports = (legacyMod) => {
const form = formidable(formidableOptions); const form = formidable(formidableOptions);
// Parse the request and process the fields and files // Parse the request and process the fields and files
form.parse(req, function (err, fields, files) { form.parse(req, (err, fields, files) => {
// If there was an error, call the server error function with status code determined by error // If there was an error, call the server error function with status code determined by error
if (err) { if (err) {
if (err.httpCode) res.error(err.httpCode); if (err.httpCode) res.error(err.httpCode);

View file

@ -6,13 +6,13 @@ let crypto = {
__disabled__: null, __disabled__: null,
}; };
let https = { let https = {
createServer: function () { createServer: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
connect: function () { connect: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
get: function () { get: () => {
throw new Error("Crypto support is not present"); throw new Error("Crypto support is not present");
}, },
}; };

View file

@ -43,7 +43,7 @@ function LOG(s) {
autoClose: false, autoClose: false,
}, },
); );
logFile.on("error", function (err) { logFile.on("error", (err) => {
if ( if (
!s.match( !s.match(
/^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: /, /^SERVER WARNING MESSAGE(?: \[Request Id: [0-9a-f]{6}\])?: There was a problem while saving logs! Logs will not be kept in log file\. Reason: /,
@ -238,16 +238,16 @@ var serverconsole = {
// Wrap around process.exit, so that log contents can be flushed. // Wrap around process.exit, so that log contents can be flushed.
process.unsafeExit = process.exit; process.unsafeExit = process.exit;
process.exit = function (code) { process.exit = (code) => {
if (logFile && logFile.writable && !logFile.pending) { if (logFile && logFile.writable && !logFile.pending) {
try { try {
logFile.close(function () { logFile.close(() => {
logFile = undefined; logFile = undefined;
logSync = true; logSync = true;
process.unsafeExit(code); process.unsafeExit(code);
}); });
if (process.isBun) { if (process.isBun) {
setInterval(function () { setInterval(() => {
if (!logFile.writable) { if (!logFile.writable) {
logFile = undefined; logFile = undefined;
logSync = true; logSync = true;
@ -255,7 +255,7 @@ process.exit = function (code) {
} }
}, 50); // Interval }, 50); // Interval
} }
setTimeout(function () { setTimeout(() => {
logFile = undefined; logFile = undefined;
logSync = true; logSync = true;
process.unsafeExit(code); process.unsafeExit(code);

View file

@ -3,7 +3,7 @@ function fixNodeMojibakeURL(string) {
var encoded = ""; var encoded = "";
//Encode URLs //Encode URLs
Buffer.from(string, "latin1").forEach(function (value) { Buffer.from(string, "latin1").forEach((value) => {
if (value > 127) { if (value > 127) {
encoded += encoded +=
"%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase(); "%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase();
@ -13,7 +13,7 @@ function fixNodeMojibakeURL(string) {
}); });
//Upper case the URL encodings //Upper case the URL encodings
return encoded.replace(/%[0-9a-f-A-F]{2}/g, function (match) { return encoded.replace(/%[0-9a-f-A-F]{2}/g, (match) => {
return match.toUpperCase(); return match.toUpperCase();
}); });
} }

View file

@ -61,7 +61,7 @@ function parseURL(uri, prepend) {
const parsedQuery = parsedURI[7] const parsedQuery = parsedURI[7]
.substring(1) .substring(1)
.match(/([^&=]*)(?:=([^&]*))?/g); .match(/([^&=]*)(?:=([^&]*))?/g);
parsedQuery.forEach(function (qp) { parsedQuery.forEach((qp) => {
if (qp.length > 0) { if (qp.length > 0) {
let parsedQP = qp.match(/([^&=]*)(?:=([^&]*))?/); let parsedQP = qp.match(/([^&=]*)(?:=([^&]*))?/);
if (parsedQP) { if (parsedQP) {