diff --git a/zefie_wtvp_minisrv/app.js b/zefie_wtvp_minisrv/app.js index 54609acf..64cdf56e 100644 --- a/zefie_wtvp_minisrv/app.js +++ b/zefie_wtvp_minisrv/app.js @@ -32,10 +32,10 @@ const vm = require('vm'); const debug = require('debug')('minisrv_main'); const express = require('express'); -var wtvirc = null; -var wtvnewsserver = null; - - +let wtvirc = null; +let wtvnewsserver = null; +let wtvmime = null; +let minisrv_config = null; process .on('SIGTERM', shutdown('SIGTERM')) @@ -111,9 +111,9 @@ function getServerDestinationPort(server) { function verifyServicePort(service_name, socket) { if (!minisrv_config.config.enable_port_isolation) return service_name; - var server = getSocketServer(socket); + const server = getSocketServer(socket); if (server) { - var socketPort = getServerDestinationPort(server); + const socketPort = getServerDestinationPort(server); if (minisrv_config.services[service_name]) { if (minisrv_config.services[service_name].port === socketPort) { if (minisrv_config.services[service_name].servicevault_dir) @@ -127,7 +127,7 @@ function verifyServicePort(service_name, socket) { } function getServiceByVaultDir(vault_dir) { - var res = vault_dir; + let res = vault_dir; Object.keys(minisrv_config.services).forEach((k) => { if (res != vault_dir) return; if (minisrv_config.services[k].servicevault_dir) { @@ -159,7 +159,7 @@ function configureService(service_name, service_obj, initial = false) { // minisrv_config service toString service_obj.toString = function (overrides) { - var self = Object.assign({}, this); + const self = Object.assign({}, this); if (overrides != null) { if (typeof (overrides) == 'object') { Object.keys(overrides).forEach(function (k) { @@ -203,8 +203,8 @@ function getServiceString(service, overrides = {}) { async function sendRawFile(socket, path) { if (!minisrv_config.config.debug_flags.quiet) console.debug(" * Found " + path + " to handle request (Direct File Mode) [Socket " + socket.id + "]"); - var contypes = wtvmime.getContentType(path); - var headers = "200 OK\n" + const contypes = wtvmime.getContentType(path); + let headers = "200 OK\n" headers += "Content-Type: " + contypes[0] + "\n"; headers += "wtv-modern-content-type" + contypes[1]; fs.readFile(path, null, function (err, data) { @@ -221,7 +221,7 @@ var runScriptInVM = function (script_data, user_contextObj = {}, privileged = fa // try to build a name for the script's debug() calls if (!debug_name) { // try to make the debug name - var debug_name = (filename) ? filename.split(path.sep) : null; + let debug_name = (filename) ? filename.split(path.sep) : null; if (debug_name) { if (wtvshared.isConfiguredService(debug_name[debug_name.length - 2])) // service:/filename @@ -233,7 +233,7 @@ var runScriptInVM = function (script_data, user_contextObj = {}, privileged = fa } // create global context object - var contextObj = { + const contextObj = { // node core variables and functions "console": console, // needed for per-script debugging "__dirname": __dirname, // needed by services such as wtv-flashrom and wtv-disk @@ -309,11 +309,11 @@ var runScriptInVM = function (script_data, user_contextObj = {}, privileged = fa break; case "wtv-admin": // wtv-admin needs util.isArray in validation of certain actions. - contextObj = { ...contextObj, "util": require("util") } + contextObj["util"] = require("util"); case "wtv-1800": case "wtv-flashrom": // these are special cases because the primary app already loaded this - contextObj = { ...contextObj, "WTVFlashrom": WTVFlashrom } + contextObj["WTVFlashrom"] = WTVFlashrom; break; } @@ -324,20 +324,17 @@ var runScriptInVM = function (script_data, user_contextObj = {}, privileged = fa } if (privileged) { - contextObj = { - ...contextObj, - "privileged": true, - "require": require, // this is dangerous but needed for some scripts at this time - "SessionStore": SessionStore, - "socket_sessions": socket_sessions, - "reloadConfig": reloadConfig, - "classPath": classPath - } + contextObj["privileged"] = true; + contextObj["require"] = require; // this is dangerous but needed for some scripts at this time + contextObj["SessionStore"] = SessionStore; + contextObj["socket_sessions"] = socket_sessions; + contextObj["reloadConfig"] = reloadConfig; + contextObj["classPath"] = classPath; } - var options = {}; - if (filename) options = { "filename": filename }; - var eval_ctx = new vm.Script(script_data, options) + const options = {}; + if (filename) options["filename"] = filename; + const eval_ctx = new vm.Script(script_data, options) try { eval_ctx.runInNewContext(contextObj, { "breakOnSigint": true @@ -361,12 +358,12 @@ async function handleCGI(executable, cgi_file, socket, request_headers, vault, s sendToClient(socket, errpage[0], errpage[1]); return; } - var env = wtvshared.cloneObj(process.env); + const env = wtvshared.cloneObj(process.env); env.QUERY_STRING = ""; - var request_data = []; - var split_req = request_headers.request.split(' '); + let request_data = []; + const split_req = request_headers.request.split(' '); request_data.method = split_req[0]; - var request_type = (request_headers.request_url.indexOf(":/")) ? request_headers.request_url.split(":/")[0] : 'http'; + let request_type = (request_headers.request_url.indexOf(":/")) ? request_headers.request_url.split(":/")[0] : 'http'; if (request_type != "http" && request_type != "https") { request_type = "wtvp"; request_data.host = minisrv_config.config.service_ip; @@ -410,7 +407,7 @@ async function handleCGI(executable, cgi_file, socket, request_headers, vault, s } env.SERVER_SIGNATURE = env.SERVER_SOFTWARE; env.ALL_RAW = request_headers.raw_headers; - var raw_header_split = env.ALL_RAW.split("\r\n"); + const raw_header_split = env.ALL_RAW.split("\r\n"); raw_header_split.forEach(function (header) { if (header) { header = header.split(": "); @@ -445,14 +442,14 @@ async function handleCGI(executable, cgi_file, socket, request_headers, vault, s delete env['PATH_INFO']; delete env['PATH_TRANSLATED']; } - - - var options = { 'cwd': vault, 'env': env, 'timeout': 120000, windowsHide: true, 'uid': process.getuid(), 'gid': process.getgid(), 'stdio': 'overlapped' }; + + + const options = { 'cwd': vault, 'env': env, 'timeout': 120000, windowsHide: true, 'uid': process.getuid(), 'gid': process.getgid(), 'stdio': 'overlapped' }; if (!minisrv_config.config.debug_flags.quiet) (executable == cgi_file) ? console.debug(" * Executing CGI:", executable) : console.debug(" * Executing CGI:", executable, cgi_file); - var cgi = (executable == cgi_file) ? spawn(cgi_file, options=options) : spawn(executable, [cgi_file], options) - var data = ""; - var error = ""; - + const cgi = (executable == cgi_file) ? spawn(cgi_file, options=options) : spawn(executable, [cgi_file], options) + let data = ""; + let error = ""; + if (request_headers['content-length'] && post_data) { cgi.stdin.write(post_data); cgi.stdin.end(); @@ -466,8 +463,8 @@ async function handleCGI(executable, cgi_file, socket, request_headers, vault, s }); cgi.on('close', function (code) { if (code == 0) { - var stdout = data.split("\r\n\r\n", 2); - var headers = stdout[0]; + const stdout = data.split("\r\n\r\n", 2); + let headers = stdout[0]; data = stdout[1]; headers = wtvshared.headerStringToObj(headers, true); if (!headers.Status) headers.Status = "200 OK"; @@ -477,7 +474,7 @@ async function handleCGI(executable, cgi_file, socket, request_headers, vault, s }); cgi.on('error', function (err) { console.error("CGI exec error", err); - var errpage = wtvshared.doErrorPage(500); + const errpage = wtvshared.doErrorPage(500); sendToClient(socket, errpage[0], errpage[1]); }); } @@ -488,12 +485,13 @@ async function handlePHP(socket, request_headers, php_file, vault, service_name, async function processPath(socket, service_vault_file_path, request_headers = [], service_name, shared_romcache = null, pc_services = false) { var headers, data = null; - var request_is_async = false; - var service_vault_found = false; - var service_path = unescape(service_vault_file_path); - var vaults_to_scan = service_vaults; - var usingSharedROMCache = false; - var contextObj = { + let request_is_async = false; + let service_vault_found = false; + let service_path = decodeURIComponent(service_vault_file_path); + let pc_service_name = null; + const vaults_to_scan = service_vaults; + let usingSharedROMCache = false; + const contextObj = { "privileged": false, "socket": socket, "session_data": ssid_sessions[socket.ssid], @@ -506,7 +504,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] // Normally any changes in the VM are discarded, but the rest of this function // requires reading some of the data back into the main application. // Here we define which ones to read back. - var updateFromVM = [ + const updateFromVM = [ // format: [ ourvarname, scriptsvarname ] ["headers", "headers"], // we need to be able to read the script's response headers ["data", "data"], // we need to be able to read the script's response data @@ -514,7 +512,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] ] if (pc_services) { - var pc_service_name = getServiceByVaultDir(service_name) + pc_service_name = getServiceByVaultDir(service_name) contextObj.pc_service_name = pc_service_name; if (minisrv_config.services[pc_service_name].service_vaults) { vaults_to_scan = vaults_to_scan.concat(minisrv_config.services[pc_service_name].service_vaults); @@ -522,7 +520,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } else { updateFromVM.push([`ssid_sessions['${socket.ssid}']`, "session_data"]); // user-specific session data from unprivileged scripts } - var privileged = false; + let privileged = false; if (minisrv_config.services[service_name]) privileged = (minisrv_config.services[service_name].privileged) ? true : false; else if (pc_services) privileged = (minisrv_config.services[pc_service_name].privileged) ? true : false; @@ -537,10 +535,10 @@ async function processPath(socket, service_vault_file_path, request_headers = [] if (!usingSharedROMCache) { if (minisrv_config.config.SharedROMCache && shared_romcache) { if (shared_romcache.includes(minisrv_config.config.SharedROMCache)) { - var service_path_presplit = shared_romcache.split(path.sep); + const service_path_presplit = shared_romcache.split(path.sep); service_path_presplit.splice(service_path_presplit.findIndex((element) => element === 'ROMCache'), 1); - var service_path_romcache = service_vault_dir + path.sep + service_path_presplit.join(path.sep); - var service_vault_file_path_romcache = wtvshared.returnAbsolutePath(wtvshared.makeSafePath(service_path_romcache)); + const service_path_romcache = service_vault_dir + path.sep + service_path_presplit.join(path.sep); + const service_vault_file_path_romcache = wtvshared.returnAbsolutePath(wtvshared.makeSafePath(service_path_romcache)); if (fs.existsSync(service_vault_file_path_romcache)) { service_path = service_path.replace(wtvshared.fixPathSlashes(minisrv_config.config.SharedROMCache), 'ROMCache'); service_vault_file_path = service_vault_file_path_romcache; @@ -556,10 +554,10 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } // deny access to catchall file name directly - var service_path_split = service_path.split("/"); - var service_path_request_file = service_path_split[service_path_split.length - 1]; + const service_path_split = service_path.split("/"); + const service_path_request_file = service_path_split[service_path_split.length - 1]; if (minisrv_config.config.catchall_file_name) { - var minisrv_catchall = null; + let minisrv_catchall = null; if (minisrv_config.services[service_name]) minisrv_catchall = minisrv_config.services[service_name].catchall_file_name || minisrv_config.config.catchall_file_name || null; else minisrv_catchall = minisrv_config.config.catchall_file_name || null; if (minisrv_catchall) { @@ -574,10 +572,9 @@ async function processPath(socket, service_vault_file_path, request_headers = [] if (service_vault_file_path.endsWith("/index")) { service_vault_file_path = getDirectoryIndex(service_vault_file_path.slice(0, -6)); } - var is_dir = false; - var file_exists = false; - // Clear variables to free memory - minisrv_catchall = service_path_split = service_path_request_file = null; + let is_dir = false; + let file_exists = false; + if (fs.existsSync(service_vault_file_path)) { file_exists = true; is_dir = fs.lstatSync(service_vault_file_path).isDirectory() @@ -595,13 +592,13 @@ async function processPath(socket, service_vault_file_path, request_headers = [] fs.readFile(service_vault_file_path + ".txt", 'Utf-8', function (err, file_raw) { if (file_raw.indexOf("\n\n") > 0) { // split headers and data by newline (unix format) - var file_raw_split = file_raw.split("\n\n"); + const file_raw_split = file_raw.split("\n\n"); headers = file_raw_split[0]; file_raw_split.shift(); data = file_raw_split.join("\n"); } else if (file_raw.indexOf("\r\n\r\n") > 0) { // split headers and data by carrage return + newline (windows format) - var file_raw_split = file_raw.split("\r\n\r\n"); + const file_raw_split = file_raw.split("\r\n\r\n"); headers = file_raw_split[0].replace(/\r/g, ""); file_raw_split.shift(); data = file_raw_split.join("\r\n"); @@ -625,9 +622,9 @@ async function processPath(socket, service_vault_file_path, request_headers = [] request_headers.service_file_path = service_vault_file_path + ".js"; // expose var service_dir for script path to the root of the wtv-service socket_sessions[socket.id].starttime = Math.floor(new Date().getTime() / 1000); - var script_data = fs.readFileSync(service_vault_file_path + ".js").toString(); + const script_data = fs.readFileSync(service_vault_file_path + ".js").toString(); - var vmResults = runScriptInVM(script_data, contextObj, privileged, service_vault_file_path + ".js"); + const vmResults = runScriptInVM(script_data, contextObj, privileged, service_vault_file_path + ".js"); // Here we read back certain data from the ServiceVault Script Context Object updateFromVM.forEach((item) => { try { @@ -660,14 +657,14 @@ async function processPath(socket, service_vault_file_path, request_headers = [] handlePHP(socket, request_headers, service_vault_file_path, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid]) return; } else { - var extra_path = service_vault_file_path.includes(".php") ? service_vault_file_path.slice(service_vault_file_path.lastIndexOf(".php") + 4) : ""; + const extra_path = service_vault_file_path.includes(".php") ? service_vault_file_path.slice(service_vault_file_path.lastIndexOf(".php") + 4) : ""; service_vault_file_path = service_vault_file_path.slice(0, service_vault_file_path.indexOf(".php") + 4); if (fs.existsSync(service_vault_file_path)) { service_vault_found = true; handlePHP(socket, request_headers, service_vault_file_path, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid], extra_path) return; } else if (service_vault_dir == vaults_to_scan[vaults_to_scan.length - 1]) { - var errpage = wtvshared.doErrorPage(404, null, null, pc_services); + const errpage = wtvshared.doErrorPage(404, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } @@ -675,7 +672,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } else { // php is not enabled, don't expose source code service_vault_found = true; - var errpage = wtvshared.doErrorPage(403, null, null, pc_services); + const errpage = wtvshared.doErrorPage(403, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } @@ -688,14 +685,14 @@ async function processPath(socket, service_vault_file_path, request_headers = [] handleCGI(service_vault_file_path, service_vault_file_path, socket, request_headers, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid]) return; } else { - var extra_path = service_vault_file_path.includes(".cgi") ? service_vault_file_path.slice(service_vault_file_path.lastIndexOf(".cgi") + 4) : ""; + const extra_path = service_vault_file_path.includes(".cgi") ? service_vault_file_path.slice(service_vault_file_path.lastIndexOf(".cgi") + 4) : ""; service_vault_file_path = service_vault_file_path.slice(0, service_vault_file_path.indexOf(".cgi") + 4); if (fs.existsSync(service_vault_file_path)) { service_vault_found = true; handleCGI(service_vault_file_path, service_vault_file_path, socket, request_headers, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid], extra_path) return; } else if (service_vault_dir == vaults_to_scan[vaults_to_scan.length - 1]) { - var errpage = wtvshared.doErrorPage(404, null, null, pc_services); + const errpage = wtvshared.doErrorPage(404, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } @@ -703,7 +700,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } else { // php is not enabled, don't expose source code service_vault_found = true; - var errpage = wtvshared.doErrorPage(403, null, null, pc_services); + const errpage = wtvshared.doErrorPage(403, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } @@ -726,10 +723,10 @@ async function processPath(socket, service_vault_file_path, request_headers = [] request_headers.raw_file = true; // process flashroms if (wtvshared.getFileExt(service_vault_file_path).toLowerCase() == "rom" || wtvshared.getFileExt(service_vault_file_path).toLowerCase() == "brom") { - var bf0app_update = false; - var request_path = request_headers.request_url.replace(service_name + ":/", ""); - var romtype = ssid_sessions[socket.ssid].get("wtv-client-rom-type"); - var bootver = ssid_sessions[socket.ssid].get("wtv-client-bootrom-version") + let bf0app_update = false; + const request_path = request_headers.request_url.replace(service_name + ":/", ""); + const romtype = ssid_sessions[socket.ssid].get("wtv-client-rom-type"); + const bootver = ssid_sessions[socket.ssid].get("wtv-client-bootrom-version") if ((romtype == "bf0app" || !romtype) && (bootver == "105" || !bootver)) { // assume old classic in flash mode, override user setting and send tellyscript @@ -793,25 +790,23 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } } else { // look for a catchall in the current path and all parent paths up until the service root - var service_config = ((pc_services) ? minisrv_config.services[pc_service_name] : minisrv_config.services[service_name]) || {}; + const service_config = ((pc_services) ? minisrv_config.services[pc_service_name] : minisrv_config.services[service_name]) || {}; if (minisrv_config.config.catchall_file_name || service_config['catchall_file_name']) { - var minisrv_catchall_file_name = service_config['catchall_file_name'] || minisrv_config.config.catchall_file_name || null; + const minisrv_catchall_file_name = service_config['catchall_file_name'] || minisrv_config.config.catchall_file_name || null; if (minisrv_catchall_file_name) { - var service_check_dir = service_vault_file_path.split(path.sep); + const service_check_dir = service_vault_file_path.split(path.sep); service_check_dir.pop(); // pop filename while (service_check_dir.join(path.sep) != service_vault_dir && service_check_dir.length > 0) { - var catchall_file = service_check_dir.join(path.sep) + path.sep + minisrv_catchall_file_name; + const catchall_file = service_check_dir.join(path.sep) + path.sep + minisrv_catchall_file_name; if (fs.existsSync(catchall_file)) { service_vault_found = true; if (!minisrv_config.config.debug_flags.quiet) console.debug(" * Found catchall at " + catchall_file + " to handle request (JS Interpreter Mode) [Socket " + socket.id + "]"); request_headers.service_file_path = catchall_file; if (catchall_file.endsWith(".js")) { - var script_data = fs.readFileSync(catchall_file).toString(); - - var vmResults = runScriptInVM(script_data, contextObj, privileged, catchall_file); - + const script_data = fs.readFileSync(catchall_file).toString(); + const vmResults = runScriptInVM(script_data, contextObj, privileged, catchall_file); updateFromVM.forEach((item) => { // Here we read back certain data from the ServiceVault Script Context Object try { @@ -836,24 +831,24 @@ async function processPath(socket, service_vault_file_path, request_headers = [] } else if (catchall_file.endsWith(".php")) { if (minisrv_config.config.php_enabled && minisrv_config.config.php_binpath) { request_is_async = true; - var extra_path = service_check_dir.join(path.sep) + path.sep + request_headers.request_url.replace(service_name + ":/", ""); + const extra_path = service_check_dir.join(path.sep) + path.sep + request_headers.request_url.replace(service_name + ":/", ""); if (!minisrv_config.config.debug_flags.quiet) console.debug(" * Found catchall at " + catchall_file + " to handle request (CGI Interpreter Mode) [Socket " + socket.id + "]"); handlePHP(socket, request_headers, catchall_file, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid], extra_path) } else { // php is not enabled, don't expose source code - var errpage = wtvshared.doErrorPage(403, null, null, pc_services); + const errpage = wtvshared.doErrorPage(403, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } } else if (catchall_file.endsWith(".cgi")) { if (minisrv_config.config.cgi_enabled) { request_is_async = true; - var extra_path = service_check_dir.join(path.sep) + path.sep + request_headers.request_url.replace(service_name + ":/", ""); + const extra_path = service_check_dir.join(path.sep) + path.sep + request_headers.request_url.replace(service_name + ":/", ""); if (!minisrv_config.config.debug_flags.quiet) console.debug(" * Found catchall at " + catchall_file + " to handle request (CGI Interpreter Mode) [Socket " + socket.id + "]"); handleCGI(catchall_file, catchall_file, socket, request_headers, service_vault_dir + path.sep + service_name, (pc_services) ? pc_service_name : service_name, (pc_services) ? null : ssid_sessions[socket.ssid], extra_path) } else { // cgi is not enabled, don't expose source code - var errpage = wtvshared.doErrorPage(403, null, null, pc_services); + const errpage = wtvshared.doErrorPage(403, null, null, pc_services); sendToClient(socket, errpage[0], errpage[1]); return; } @@ -872,7 +867,7 @@ async function processPath(socket, service_vault_file_path, request_headers = [] // either `request_is_async`, or `headers` and `data` MUST be defined by this point! }); } catch (e) { - var errpage = wtvshared.doErrorPage(400, null, null, pc_services); + const errpage = wtvshared.doErrorPage(400, null, null, pc_services); headers = errpage[0]; data = errpage[1]; if (pc_services) { @@ -884,12 +879,12 @@ async function processPath(socket, service_vault_file_path, request_headers = [] if (!request_is_async) { if (!service_vault_found) { console.error(" * Could not find a Service Vault for " + service_name + ":/" + service_path.replace(service_name + path.sep, "").replace(path.sep, '/')); - var errpage = wtvshared.doErrorPage(404, null, null, pc_services); + const errpage = wtvshared.doErrorPage(404, null, null, pc_services); headers = errpage[0]; data = errpage[1]; } if (headers == null && !request_is_async) { - var errpage = wtvshared.doErrorPage(400, null, null, pc_services); + const errpage = wtvshared.doErrorPage(400, null, null, pc_services); headers = errpage[0]; data = errpage[1]; console.error(" * Scripting or Data error: Headers were not defined. (headers,data) as follows:") @@ -913,9 +908,9 @@ function getDirectoryIndex(svpath) { } async function processURL(socket, request_headers, pc_services = false) { - var shortURL, headers, data, service_name; - var original_service_name = ""; - var allow_double_slash = false, enable_multi_query = false, use_external_proxy = false; + let shortURL, headers, data, service_name; + let original_service_name = ""; + let allow_double_slash = false, enable_multi_query = false, use_external_proxy = false; request_headers.query = {}; if (request_headers.request_url) { @@ -959,22 +954,22 @@ async function processURL(socket, request_headers, pc_services = false) { if (request_headers['wtv-request-type']) socket_sessions[socket.id].wtv_request_type = request_headers['wtv-request-type']; if (request_headers.post_data) { - var post_data_string = null; + let post_data_string = null; try { post_data_string = request_headers.post_data.toString(CryptoJS.enc.Utf8); // if not text this will probably throw an exception if (post_data_string) { if (post_data_string.indexOf('=')) { if (post_data_string.indexOf('&')) { - var qraw = post_data_string.split('&'); + const qraw = post_data_string.split('&'); if (qraw.length) { for (let i = 0; i < qraw.length; i++) { - var qraw_split = qraw[i].split("="); + const qraw_split = qraw[i].split("="); if (qraw_split.length === 2) { - var k = qraw_split[0]; - var data = unescape(qraw[i].split("=")[1].replace(/\+/g, "%20")); + const k = qraw_split[0]; + data = decodeURIComponent(qraw[i].split("=")[1].replace(/\+/g, "%20")); if (request_headers.query[k]) { if (typeof request_headers.query[k] === 'string') { - var keyarray = [request_headers.query[k]]; + const keyarray = [request_headers.query[k]]; request_headers.query[k] = keyarray; } if (wtvshared.isASCII(data)) request_headers.query[k].push(data); @@ -987,13 +982,13 @@ async function processURL(socket, request_headers, pc_services = false) { } } } else { - var qraw_split = post_data_string.split("="); + const qraw_split = post_data_string.split("="); if (qraw_split.length == 2) { - var k = qraw_split[0]; - var data = unescape(qraw_split[1].replace(/\+/g, "%20")); + const k = qraw_split[0]; + data = decodeURIComponent(qraw_split[1].replace(/\+/g, "%20")); if (request_headers.query[k]) { if (typeof request_headers.query[k] === 'string') { - var keyarray = [request_headers.query[k]]; + const keyarray = [request_headers.query[k]]; request_headers.query[k] = keyarray; } if (wtvshared.isASCII(data)) request_headers.query[k].push(data); @@ -1014,10 +1009,10 @@ async function processURL(socket, request_headers, pc_services = false) { // Apparently it is within WTVP spec to accept urls without a slash (eg wtv-home:home) // Here, we just reassemble the request URL as if it was a proper URL (eg wtv-home:/home) // we will allow this on any service except http(s) and ftp - var shortURL_split = shortURL.split(':'); - var shortURL_service_name = shortURL_split[0]; + const shortURL_split = shortURL.split(':'); + const shortURL_service_name = shortURL_split[0]; shortURL_split.shift(); - var shortURL_service_path = shortURL_split.join(":"); + const shortURL_service_path = shortURL_split.join(":"); shortURL = shortURL_service_name + ":/" + shortURL_service_path; } @@ -1070,20 +1065,20 @@ minisrv-no-mail-count: true`; } if (pc_services) { - var ssl = (socket.ssl) ? true : false; + const ssl = (socket.ssl) ? true : false; if (original_service_name == service_name) console.log(" * " + ((ssl) ? "SSL " : "") + "PC request on service " + service_name + " for " + request_headers.request_url, 'on', socket.id); else console.log(" * " + ((ssl) ? "SSL " : "") + "PC request on service " + original_service_name + " (Service Vault " + service_name + ") for " + request_headers.request_url, 'on', socket.id); } if ((shortURL.includes(':/')) && (!shortURL.includes('://') || (shortURL.includes('://') && allow_double_slash))) { - var ssid = socket.ssid; + let ssid = socket.ssid; if (ssid == null) { // prevent possible injection attacks via malformed SSID and filesystem SessionStore ssid = wtvshared.makeSafeSSID(request_headers["wtv-client-serial-number"]); if (ssid == "") ssid = null; } if (!pc_services) { - var reqverb = "Request"; + let reqverb = "Request"; if (request_headers.encrypted || request_headers.secure) reqverb = "Encrypted " + reqverb; if (ssid != null) { console.log(" * " + reqverb + " for " + request_headers.request_url + " from WebTV SSID " + (await wtvshared.filterSSID(ssid)), 'on', socket.id); @@ -1100,15 +1095,15 @@ minisrv-no-mail-count: true`; service_name = "wtv-star"; } else { // is actually a request on then wrong port - var errpage = wtvshared.doErrorPage(500, null, null, pc_services); + const errpage = wtvshared.doErrorPage(500, null, null, pc_services); socket_sessions[socket.id].close_me = true; sendToClient(socket, errpage[0], errpage[1]); return } } } - var urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL.split(':/')[1]); - var shared_romcache = null; + const urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL.split(':/')[1]); + let shared_romcache = null; if ((shortURL.includes(":/ROMCache/") || shortURL.includes("://ROMCache/")) && minisrv_config.config.enable_shared_romcache) { shared_romcache = wtvshared.fixPathSlashes(minisrv_config.config.SharedROMCache + path.sep + shortURL.split(':/')[1]); } @@ -1121,12 +1116,12 @@ minisrv-no-mail-count: true`; doHTTPProxy(socket, request_headers); } else if (shortURL.startsWith('ftp://')) { if (minisrv_config.config.debug_flags.show_headers) console.debug(" * Incoming FTP request on WTVP socket ID", socket.id, await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers)))); - var wtvftp = new WTVFTP(wtvshared, sendToClient); + const wtvftp = new WTVFTP(wtvshared, sendToClient); wtvftp.handleFTPRequest(socket, request_headers); } else if (shortURL.indexOf('file://') >= 0) { shortURL = shortURL.replace("file://",'').replace("romcache", "ROMCache"); service_name = "wtv-star"; - var urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL); + const urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL); processPath(socket, urlToPath, request_headers, service_name, shared_romcache, pc_services); } else if (pc_services) { // if a directory, request index @@ -1134,7 +1129,7 @@ minisrv-no-mail-count: true`; shared_romcache = wtvshared.fixPathSlashes(minisrv_config.config.SharedROMCache + path.sep + shortURL.split('/')[1] + '/' + shortURL.split('/')[2]); } if (shortURL.endsWith("/")) shortURL += "index"; - var urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL); + const urlToPath = wtvshared.fixPathSlashes(service_name + path.sep + shortURL); processPath(socket, urlToPath, request_headers, service_name, shared_romcache, pc_services); } else { if (request_headers.request.indexOf("HTTP/1.0") > 0) { @@ -1142,7 +1137,7 @@ minisrv-no-mail-count: true`; if (minisrv_config.config.debug_flags.show_headers) console.debug(" * Incoming HTTP/1.0 headers on WTVP socket ID", socket.id, await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers)))); else debug(" * Incoming HTTP/1.0 headers on WTVP socket ID", socket.id, await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers)))); - var errpage = wtvshared.doErrorPage(500, null, null, false, true); + const errpage = wtvshared.doErrorPage(500, null, null, false, true); headers = errpage[0]; data = '' socket_sessions[socket.id].close_me = true; @@ -1152,7 +1147,7 @@ minisrv-no-mail-count: true`; if (minisrv_config.config.debug_flags.show_headers) console.debug(" * Incoming Invalid headers on WTVP socket ID", socket.id, await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers)))); else debug(" * Incoming Invalid headers on WTVP socket ID", socket.id, await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers)))); - var errpage = wtvshared.doErrorPage(500, null, null, true, false); + const errpage = wtvshared.doErrorPage(500, null, null, true, false); headers = errpage[0]; data = '' socket_sessions[socket.id].close_me = true; @@ -1196,7 +1191,7 @@ function handleProxy(socket, request_type, request_headers, res, data) { // header pass-through whitelist, case insensitive comparsion to server, however, you should // specify the header case as you intend for the client - var headers = wtvshared.stripHeaders(res.headers, [ + const headers = wtvshared.stripHeaders(res.headers, [ 'Connection', 'Server', 'Date', @@ -1245,7 +1240,7 @@ function handleProxy(socket, request_type, request_headers, res, data) { if (request_type != "http" && request_type != "https") { // replace http and https links on non http/https protocol (for proto:// for example) - var data_t = Buffer.concat(data).toString().replaceAll("http://", request_type + "://").replaceAll("https://", request_type + "://"); + const data_t = Buffer.concat(data).toString().replaceAll("http://", request_type + "://").replaceAll("https://", request_type + "://"); data = [Buffer.from(data_t)] } } @@ -1264,7 +1259,7 @@ function handleProxy(socket, request_type, request_headers, res, data) { headers['wtv-explanation-url'] = minisrv_config.services['http']['wtv-explanation'][res.statusCode]; } } - var data_hex = Buffer.concat(data).toString('hex'); + const data_hex = Buffer.concat(data).toString('hex'); if (data_hex.startsWith("0d0a0d0a")) data_hex = data_hex.slice(8); if (data_hex.startsWith("0a0d0a")) data_hex = data_hex.slice(6); if (data_hex.startsWith("0a0a")) data_hex = data_hex.slice(4); @@ -1273,25 +1268,28 @@ function handleProxy(socket, request_type, request_headers, res, data) { async function doHTTPProxy(socket, request_headers) { // detect protocol name - var idx = request_headers.request_url.indexOf('/') - 1; + const idx = request_headers.request_url.indexOf('/') - 1; - var request_type = request_headers.request_url.slice(0, idx); + const request_type = request_headers.request_url.slice(0, idx); if (minisrv_config.config.debug_flags.show_headers) console.debug(request_type.toUpperCase() + " Proxy: Client Request Headers on socket ID", socket.id, (await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers))))); else debug(request_type.toUpperCase() + " Proxy: Client Request Headers on socket ID", socket.id, (await wtvshared.decodePostData(await wtvshared.filterRequestLog(await wtvshared.filterSSID(request_headers))))); + let proxy_agent; switch (request_type) { case "https": - var proxy_agent = https; + proxy_agent = https; break; case "http": case "proto": - var proxy_agent = http; + proxy_agent = http; break; } - var request_data = []; + let request_data = []; + let data = []; + request_data.method = request_headers.request.split(' ')[0]; - var request_url_split = request_headers.request.split(' ')[1].split('/'); + const request_url_split = request_headers.request.split(' ')[1].split('/'); request_data.host = request_url_split[2]; if (request_data.host.indexOf(':') > 0) { request_data.port = request_data.host.split(':')[1]; @@ -1304,7 +1302,7 @@ async function doHTTPProxy(socket, request_headers) { request_data.path = "/" + request_url_split.join('/'); if (request_data.method && request_data.host && request_data.path) { - var options = { + const options = { host: request_data.host, port: request_data.port, path: request_data.path, @@ -1338,7 +1336,7 @@ async function doHTTPProxy(socket, request_headers) { } } else { // configure connection to remote http proxy - var proxy_agent = http; + proxy_agent = http; options.host = minisrv_config.services[request_type].external_proxy_host; options.port = minisrv_config.services[request_type].external_proxy_port; options.path = request_headers.request.split(' ')[1]; @@ -1353,8 +1351,7 @@ async function doHTTPProxy(socket, request_headers) { } } const req = proxy_agent.request(options, function (res) { - var data = []; - var total_data = 0; + let total_data = 0; res.on('data', d => { data.push(d); @@ -1362,7 +1359,7 @@ async function doHTTPProxy(socket, request_headers) { if (total_data > 1024 * 1024 * parseFloat(minisrv_config.services[request_type].max_response_size || 16)) { console.warn(` * Response data exceeded ${minisrv_config.services[request_type].max_response_size || 16}MB limit, destroying...`); res.destroy(); - var errpage = wtvshared.doErrorPage(400, "The item chosen is too large to be used."); + const errpage = wtvshared.doErrorPage(400, "The item chosen is too large to be used."); sendToClient(socket, errpage[0], errpage[1]); } }) @@ -1384,16 +1381,15 @@ async function doHTTPProxy(socket, request_headers) { }); }).on('error', function (err) { // severe errors, such as unable to connect. - var errpage, headers, data = null; if (err.code == "ENOTFOUND" || err.message.indexOf("HostUnreachable") > 0) { - errpage = wtvshared.doErrorPage(400, `The publisher ${request_data.host} is unknown.`); + const errpage = wtvshared.doErrorPage(400, `The publisher ${request_data.host} is unknown.`); sendToClient(socket, errpage[0], errpage[1]); } else { if (minisrv_config.services[request_type].external_proxy_is_http1) { handleProxy(socket, request_type, request_headers, res, data); } else { console.error(" * Unhandled Proxy Request Error:", err); - errpage = wtvshared.doErrorPage(400); + const errpage = wtvshared.doErrorPage(400); sendToClient(socket, errpage[0], errpage[1]); } } @@ -1410,10 +1406,11 @@ async function doHTTPProxy(socket, request_headers) { } async function sendToClient(socket, headers_obj, data = null) { - var headers = ""; - var content_length = 0; - var eol = "\n"; - var timezone = "-0000"; + let headers = ""; + let content_length = 0; + const eol = "\n"; + let timezone = "-0000"; + let wtv_connection_close = false; if (typeof (data) === 'undefined' || data === null) data = ''; if (typeof (headers_obj) === 'string') { @@ -1425,7 +1422,7 @@ async function sendToClient(socket, headers_obj, data = null) { return; } if (!socket.res) { - var wtv_connection_close = (headers_obj["wtv-connection-close"]) ? true : false; + wtv_connection_close = (headers_obj["wtv-connection-close"]) ? true : false; if (typeof (headers_obj["wtv-connection-close"]) != 'undefined') delete headers_obj["wtv-connection-close"]; if (!headers_obj['minisrv-no-mail-count']) { @@ -1453,7 +1450,6 @@ async function sendToClient(socket, headers_obj, data = null) { headers_obj = wtvshared.moveObjectKey('Connection', 'Status', headers_obj); } - var content_length = 0; if (typeof data.length !== 'undefined') { content_length = data.length; } else if (typeof data.byteLength !== 'undefined') { @@ -1464,7 +1460,7 @@ async function sendToClient(socket, headers_obj, data = null) { if (headers_obj["raw_headers"]) { delete headers_obj["raw_headers"]; } - var contype_key = wtvshared.getCaseInsensitiveKey('content-type', headers_obj); + const contype_key = wtvshared.getCaseInsensitiveKey('content-type', headers_obj); if (contype_key) { if (socket.ssid && headers_obj[contype_key].indexOf(";") > 0) { // WebTV client @@ -1505,7 +1501,7 @@ async function sendToClient(socket, headers_obj, data = null) { // if client can do compression, see if its worth enabling // small files actually get larger, so don't compress them - var compression_type = 0; + let compression_type = 0; if (content_length >= 256) compression_type = wtvmime.shouldWeCompress(ssid_sessions[socket.ssid], headers_obj); if (socket_sessions[socket.id].request_headers) { if (socket_sessions[socket.id].request_headers.query) { @@ -1529,26 +1525,26 @@ async function sendToClient(socket, headers_obj, data = null) { // compress if needed if (compression_type > 0 && content_length > 0 && headers_obj['Status'].startsWith("200")) { - var uncompressed_content_length = content_length; + const uncompressed_content_length = content_length; switch (compression_type) { case 1: // wtv-lzpf implementation headers_obj["wtv-lzpf"] = 0; - var wtvcomp = new LZPF(); + const wtvcomp = new LZPF(); data = wtvcomp.compress(data); wtvcomp = null; // Makes the garbage gods happy so it cleans up our mess break; case 2: // zlib DEFLATE implementation - var zlib_options = { 'level': 9 }; + const zlib_options = { 'level': 9 }; if (uncompressed_content_length > 4194304) zlib_options.strategy = 2; headers_obj['Content-Encoding'] = 'deflate'; data = zlib.deflateSync(data, zlib_options); break; } - var compressed_content_length = 0; + let compressed_content_length = 0; if (content_length == 0 || compression_type != 1) { // ultimately send compressed content length compressed_content_length = data.byteLength; @@ -1557,8 +1553,8 @@ async function sendToClient(socket, headers_obj, data = null) { // ultimately send original content length if lzpf compressed_content_length = data.byteLength; } - var compression_ratio = (uncompressed_content_length / compressed_content_length).toFixed(2); - var compression_percentage = ((1 - (compressed_content_length / uncompressed_content_length)) * 100).toFixed(1); + const compression_ratio = (uncompressed_content_length / compressed_content_length).toFixed(2); + const compression_percentage = ((1 - (compressed_content_length / uncompressed_content_length)) * 100).toFixed(1); if (uncompressed_content_length != compressed_content_length) if (minisrv_config.config.debug_flags.debug) console.debug(" # Compression stats: Orig Size:", uncompressed_content_length, "~ Comp Size:", compressed_content_length, "~ Ratio:", compression_ratio, "~ Saved:", compression_percentage.toString() + "%"); } @@ -1617,7 +1613,7 @@ async function sendToClient(socket, headers_obj, data = null) { headers_obj = wtvshared.moveObjectKey("Content-length", "Content-type", headers_obj); // move Content-length to before Content-type // remove x-powered-by header if client is WebTV - var xpower = wtvshared.getCaseInsensitiveKey("x-powered-by", headers_obj); + let xpower = wtvshared.getCaseInsensitiveKey("x-powered-by", headers_obj); if (!xpower && socket.service_name) { // add X-Powered-By header if not WebTV and not already set xpower = 'X-Powered-By'; @@ -1678,7 +1674,7 @@ async function sendToClient(socket, headers_obj, data = null) { // send to client if (socket.res) { - var resCode = parseInt(headers_obj.Status.slice(0, 3)) || 500; + const resCode = parseInt(headers_obj.Status.slice(0, 3)) || 500; socket.res.writeHead(resCode, headers_obj); socket.res.end(data); if (minisrv_config.config.debug_flags.show_headers) console.debug(" * Outgoing PC headers on " + socket.service_name + " socket ID", socket.id, headers_obj); @@ -1686,7 +1682,7 @@ async function sendToClient(socket, headers_obj, data = null) { if (minisrv_config.config.debug_flags.quiet) console.debug(" * Sent response " + headers_obj.Status + " to PC client (Content-Type:", headers_obj['Content-type'], "~", headers_obj['Content-length'], "bytes)"); } else { - var toClient = null; + let toClient = null; if (typeof data == 'string') { toClient = headers + eol + data; sendToSocket(socket, Buffer.from(toClient)); @@ -1706,24 +1702,24 @@ async function sendToClient(socket, headers_obj, data = null) { } async function sendToSocket(socket, data) { - var chunk_size = 16384; - var can_write = true; - var close_socket = false; - var expected_data_out = 0; + const chunk_size = 16384; + let can_write = true; + let close_socket = false; + let expected_data_out = 0; while ((socket.bytesWritten == 0 || socket.bytesWritten != expected_data_out) && can_write) { if (expected_data_out === 0) expected_data_out = data.byteLength + (socket_sessions[socket.id].socket_total_written || 0); if (socket.bytesWritten == expected_data_out) break; - var data_left = (expected_data_out - socket.bytesWritten); + let data_left = (expected_data_out - socket.bytesWritten); // buffer size = lesser of chunk_size or size remaining - var buffer_size = (data_left >= chunk_size) ? chunk_size : data_left; + const buffer_size = (data_left >= chunk_size) ? chunk_size : data_left; if (buffer_size < 0) { socket.destroy(); close_socket = true; break; } - var offset = (data.byteLength - data_left); - var chunk = new Buffer.alloc(buffer_size); + const offset = (data.byteLength - data_left); + const chunk = new Buffer.alloc(buffer_size); data.copy(chunk, 0, offset, (offset + buffer_size)); can_write = socket.write(chunk); if (!can_write) { @@ -1752,7 +1748,7 @@ async function sendToSocket(socket, data) { function concatArrayBuffer(buffer1, buffer2) { if (!buffer1) return buffer2; if (!buffer2) return buffer1; - var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); + const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); tmp.set(new Uint8Array(buffer1), 0); tmp.set(new Uint8Array(buffer2), buffer1.byteLength); return tmp.buffer; @@ -1771,7 +1767,7 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq // This function sucks and needs to be rewritten - var headers = new Array(); + let headers = []; if (socket_sessions[socket.id]) { if (socket_sessions[socket.id].headers) { headers = socket_sessions[socket.id].headers; @@ -1823,7 +1819,7 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq var dec_data = CryptoJS.lib.WordArray.create(socket_sessions[socket.id].wtvsec.Decrypt(0, enc_data)); var secure_headers = await processRequest(socket, dec_data.toString(CryptoJS.enc.Hex), true, true); if (secure_headers) { - var headers = new Array(); + headers = []; headers.encrypted = true; Object.keys(secure_headers).forEach(function (k, v) { headers[k] = secure_headers[k]; @@ -1950,7 +1946,7 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq var dec_data = CryptoJS.lib.WordArray.create(socket_sessions[socket.id].wtvsec.Decrypt(0, enc_data)) if (!socket_sessions[socket.id].secure_buffer) socket_sessions[socket.id].secure_buffer = ""; socket_sessions[socket.id].secure_buffer += dec_data.toString(CryptoJS.enc.Hex); - var secure_headers = null; + let secure_headers = null; if (headers['request']) { if (headers['request'] == "GET") { if (socket_sessions[socket.id].secure_buffer.indexOf("0d0a0d0a") || socket_sessions[socket.id].secure_buffer.indexOf("0a0d0a") ||socket_sessions[socket.id].secure_buffer.indexOf("0a0a")) { @@ -2069,7 +2065,7 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq } if (socket_sessions[socket.id].post_data.length < (socket_sessions[socket.id].post_data_length * 2)) { new_header_obj = null; - var enc_data = CryptoJS.enc.Hex.parse(data_hex); + const enc_data = CryptoJS.enc.Hex.parse(data_hex); if (socket_sessions[socket.id].secure) { // decrypt if encrypted var dec_data = CryptoJS.lib.WordArray.create(socket_sessions[socket.id].wtvsec.Decrypt(0, enc_data)) @@ -2145,35 +2141,34 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq socket_sessions[socket.id].wtvsec.SecureOn(); socket_sessions[socket.id].secure = true; } - var enc_data = CryptoJS.enc.Hex.parse(data_hex); + const enc_data = CryptoJS.enc.Hex.parse(data_hex); + let dec_data; if (enc_data.sigBytes > 0) { if (!socket_sessions[socket.id].wtvsec) { - var errpage = wtvshared.doErrorPage(400); - var headers = errpage[0]; - headers += "wtv-visit: client:relog\n"; - data = errpage[1]; - sendToClient(socket, headers, data); + const errpage = wtvshared.doErrorPage(400); + const head = errpage[0] + "wtv-visit: client:relog\n"; + sendToClient(socket, head, errpage[1]); return; } - var str_test = enc_data.toString(CryptoJS.enc.Latin1); + const str_test = enc_data.toString(CryptoJS.enc.Latin1); if (isUnencryptedString(str_test)) { - var dec_data = enc_data; + dec_data = enc_data; } else { - var dec_data = CryptoJS.lib.WordArray.create(socket_sessions[socket.id].wtvsec.Decrypt(0, enc_data)); + dec_data = CryptoJS.lib.WordArray.create(socket_sessions[socket.id].wtvsec.Decrypt(0, enc_data)); } if (!socket_sessions[socket.id].secure_buffer) socket_sessions[socket.id].secure_buffer = ""; socket_sessions[socket.id].secure_buffer += dec_data.toString(CryptoJS.enc.Hex); - var secure_headers = null; + let secure_headers = null; if (headers['request']) { if (headers['request'] == "GET") { if (socket_sessions[socket.id].secure_buffer.indexOf("0d0a0d0a") || socket_sessions[socket.id].secure_buffer.indexOf("0a0d0a") || socket_sessions[socket.id].secure_buffer.indexOf("0a0a")) { secure_headers = await processRequest(socket, socket_sessions[socket.id].secure_buffer, true, true); } } else { - var secure_headers = await processRequest(socket, socket_sessions[socket.id].secure_buffer, true, true); + secure_headers = await processRequest(socket, socket_sessions[socket.id].secure_buffer, true, true); } } else { - var secure_headers = await processRequest(socket, socket_sessions[socket.id].secure_buffer, true, true); + secure_headers = await processRequest(socket, socket_sessions[socket.id].secure_buffer, true, true); } if (secure_headers) { delete socket_sessions[socket.id].secure_buffer; @@ -2198,25 +2193,19 @@ async function processRequest(socket, data_hex, skipSecure = false, encryptedReq } } } catch (e) { - var errpage = wtvshared.doErrorPage(400); - headers = errpage[0]; - data = errpage[1]; + const errpage = wtvshared.doErrorPage(400); socket.close_me = true; - sendToClient(socket, headers, data); + sendToClient(socket, errpage[0], errpage[1]); } } else { - var errpage = wtvshared.doErrorPage(400); - headers = errpage[0]; - data = errpage[1]; + const errpage = wtvshared.doErrorPage(400); socket.close_me = true; - sendToClient(socket, headers, data); + sendToClient(socket, errpage[0], errpage[1]); } } else { - var errpage = wtvshared.doErrorPage(400); - headers = errpage[0]; - data = errpage[1]; + const errpage = wtvshared.doErrorPage(400); socket.close_me = true; - sendToClient(socket, headers, data); + sendToClient(socket, errpage[0], errpage[1]); } } @@ -2235,7 +2224,7 @@ async function cleanupSocket(socket) { if (ssid_sessions[socket.ssid].get("wtv-used-8675309")) ssid_sessions[socket.ssid].delete("wtv-used-8675309"); // set timer to destroy entirety of session data if client does not return in X time - var timeout = 180000; // timeout is in milliseconds, default 180000 (3 min) .. be sure to allow time for dialup reconnections + const timeout = 180000; // timeout is in milliseconds, default 180000 (3 min) .. be sure to allow time for dialup reconnections // clear any existing timeout check if (ssid_sessions[socket.ssid].data_store.socket_check) clearTimeout(ssid_sessions[socket.ssid].data_store.socket_check); @@ -2327,10 +2316,9 @@ function getGitRevision() { return null; } } -var minisrv_config = null; function reloadConfig() { - var temp = { "version": minisrv_config.version } + const temp = { "version": minisrv_config.version } if (minisrv_config.config.git_commit) temp.git_commit = minisrv_config.config.git_commit; minisrv_config = wtvshared.readMiniSrvConfig(true, false, true); // snatches minisrv_config @@ -2349,18 +2337,19 @@ function reloadConfig() { } // SERVER START -var git_commit = getGitRevision() -var z_title = "zefie's wtv minisrv v" + require('./package.json').version; -var z_cgiver = "minisrv/" + require('./package.json').version; +const git_commit = getGitRevision() +let z_title = "zefie's wtv minisrv v" + require('./package.json').version; +const z_cgiver = "minisrv/" + require('./package.json').version; if (git_commit) z_title += " (git " + git_commit + ")"; console.log("**** Welcome to " + z_title + " ****"); console.log("**** Detected nodejs v" + process.versions.node + " ****") -var application_root = wtvshared.getAbsolutePath('', __dirname) +const application_root = wtvshared.getAbsolutePath('', __dirname) console.log("**** Application Root Path:", application_root, "****") + minisrv_config = wtvshared.getMiniSrvConfig(); // snatches minisrv_config -const wtvmime = new WTVMime(minisrv_config); +wtvmime = new WTVMime(minisrv_config); if (git_commit) { minisrv_config.config.git_commit = git_commit; @@ -2371,10 +2360,10 @@ if (!minisrv_config) { throw ("An error has occured while reading the configuration files."); } -var service_vaults = new Array(); +const service_vaults = []; if (minisrv_config.config.ServiceVaults) { Object.keys(minisrv_config.config.ServiceVaults).forEach(function (k) { - var service_vault = wtvshared.getAbsolutePath(minisrv_config.config.ServiceVaults[k]); + const service_vault = wtvshared.getAbsolutePath(minisrv_config.config.ServiceVaults[k]); service_vaults.push(service_vault); console.log(" * Configured Service Vault at", service_vault, "with priority", (parseInt(k) + 1)); }) @@ -2382,10 +2371,10 @@ if (minisrv_config.config.ServiceVaults) { throw ("ERROR: No Service Vaults defined!"); } -var service_deps = new Array(); +const service_deps = []; if (minisrv_config.config.ServiceDeps) { Object.keys(minisrv_config.config.ServiceDeps).forEach(function (k) { - var service_dep = wtvshared.getAbsolutePath(minisrv_config.config.ServiceDeps[k]); + const service_dep = wtvshared.getAbsolutePath(minisrv_config.config.ServiceDeps[k]); service_deps.push(service_dep); console.log(" * Configured Service Dependencies at", service_dep, "with priority", (parseInt(k) + 1)); }) @@ -2393,25 +2382,26 @@ if (minisrv_config.config.ServiceDeps) { throw ("ERROR: No Service Dependancies Directory (SessionDeps) defined!"); } +let SessionStore = null; if (minisrv_config.config.SessionStore) { - var SessionStore = wtvshared.getAbsolutePath(minisrv_config.config.SessionStore); + SessionStore = wtvshared.getAbsolutePath(minisrv_config.config.SessionStore); console.log(" * Configured Session Storage at", SessionStore); } else { throw ("ERROR: No Session Storage Directory (SessionStore) defined!"); } -var service_ip = minisrv_config.config.service_ip; +const service_ip = minisrv_config.config.service_ip; Object.keys(minisrv_config.services).forEach(function (k) { if (typeof(minisrv_config.services[k]) === 'function') return; if (configureService(k, minisrv_config.services[k], true)) { - var using_tls = (minisrv_config.services[k].pc_services && minisrv_config.services[k].https_cert && minisrv_config.services[k].use_https) ? true : false; + const using_tls = (minisrv_config.services[k].pc_services && minisrv_config.services[k].https_cert && minisrv_config.services[k].use_https) ? true : false; console.log(" * Configured Service:", k, "on Port", minisrv_config.services[k].port, "- Service Host:", minisrv_config.services[k].host + ((using_tls) ? " (TLS)" : ""), "- Mode:", (minisrv_config.services[k].pc_services) ? "HTTP" : "WTVP"); if (minisrv_config.services[k].local_nntp_port) { if (!wtvnewsserver) { const WTVNewsServer = require(classPath + "/WTVNewsServer.js"); - var local_nntp_using_auth = false; + let local_nntp_using_auth = false; if (minisrv_config.services[k].local_nntp_requires_auth) { local_nntp_using_auth = true; if (minisrv_config.services[k].local_auth) { @@ -2462,9 +2452,9 @@ if (!minisrv_config.config.service_splash_logo.includes(':')) minisrv_config.con minisrv_config.version = require('./package.json').version; if (minisrv_config.config.error_log_file) { - var error_log_stream = fs.createWriteStream(wtvshared.returnAbsolutePath(minisrv_config.config.error_log_file), { flags: 'a' }); - var process_stderr = process.stderr.write; - var writeError = function () { + const error_log_stream = fs.createWriteStream(wtvshared.returnAbsolutePath(minisrv_config.config.error_log_file), { flags: 'a' }); + const process_stderr = process.stderr.write; + const writeError = function () { process_stderr.apply(process.stderr, arguments); if (error_log_stream) error_log_stream.write.apply(error_log_stream, arguments); } @@ -2581,11 +2571,11 @@ Content-type: text/html`; }) server.post('*', (req, res) => { - var errpage = null; - var ssl = (req.socket.ssl) ? true : false; - var service_name = getServiceByPort(v); + let errpage = null; + const ssl = (req.socket.ssl) ? true : false; + const service_name = getServiceByPort(v); - var request_headers = {}; + let request_headers = {}; request_headers['request'] = "POST " + req.originalUrl + " HTTP/1.1"; request_headers.request_url = req.originalUrl; request_headers.raw_headers = "Request: "+request_headers['request']+"\r\n"; @@ -2595,7 +2585,7 @@ Content-type: text/html`; }); request_headers.query = req.query; - var host_name = (request_headers['host']) ? request_headers['host'] : null; + const host_name = (request_headers['host']) ? request_headers['host'] : null; if (host_name) { if (host_name.includes(":")) host_name = host_name.slice(0, host_name.indexOf(":")); @@ -2631,7 +2621,7 @@ Content-type: text/html`; else debug(" * Incoming " + ((ssl) ? "HTTPS" : "HTTP") + " PC POST Headers on", service_name, "socket ID", req.socket.id, wtvshared.filterRequestLog(request_headers)); if (!ssl && minisrv_config.services[service_name].force_https && minisrv_config.services[service_name].https_cert) { - var headers = `302 Moved + const headers = `302 Moved Location: https://${(minisrv_config.services[service_name].https_cert.domain) ? minisrv_config.services[service_name].https_cert.domain : minisrv_config.services[service_name].host}:${minisrv_config.services[service_name].port}${req.originalUrl} Content-type: text/html`; sendToClient(req.socket, headers); @@ -2641,7 +2631,7 @@ Content-type: text/html`; processURL(req.socket, request_headers, true) } } else { - var errpage = wtvshared.doErrorPage(404, "Service Not Found (" + service_name +")", null, true); + const errpage = wtvshared.doErrorPage(404, "Service Not Found (" + service_name +")", null, true); sendToClient(req.socket, errpage[0], errpage[1]); } }) @@ -2655,5 +2645,5 @@ Content-type: text/html`; if (bind_ports.length > 0) console.log(` * Started WTVP Server on port${bind_ports.length != 1 ? "s" : ""} ` + bind_ports.join(", ") + "..."); if (pc_bind_ports.length > 0) console.log(` * Started HTTP Server on port${pc_bind_ports.length != 1 ? "s" : ""} ` + pc_bind_ports.join(", ") + "..."); -var listening_ip_string = (minisrv_config.config.bind_ip != "0.0.0.0") ? "IP: " + minisrv_config.config.bind_ip : "all interfaces"; +const listening_ip_string = (minisrv_config.config.bind_ip != "0.0.0.0") ? "IP: " + minisrv_config.config.bind_ip : "all interfaces"; console.log(" * Listening on", listening_ip_string, "~", "Service IP:", service_ip); \ No newline at end of file