commit e122e7a6ae21afacac17803e9f2243b489cc1b42 Author: sysadmin Date: Sat Jul 29 20:32:17 2023 +0200 Initial commit diff --git a/.dirimages/archive.png b/.dirimages/archive.png new file mode 100644 index 0000000..3ebc995 Binary files /dev/null and b/.dirimages/archive.png differ diff --git a/.dirimages/audio.png b/.dirimages/audio.png new file mode 100644 index 0000000..5b6d4c5 Binary files /dev/null and b/.dirimages/audio.png differ diff --git a/.dirimages/bad.png b/.dirimages/bad.png new file mode 100644 index 0000000..115fb0e Binary files /dev/null and b/.dirimages/bad.png differ diff --git a/.dirimages/css.png b/.dirimages/css.png new file mode 100644 index 0000000..753b7c4 Binary files /dev/null and b/.dirimages/css.png differ diff --git a/.dirimages/directory.png b/.dirimages/directory.png new file mode 100644 index 0000000..9dcd620 Binary files /dev/null and b/.dirimages/directory.png differ diff --git a/.dirimages/diskimage.png b/.dirimages/diskimage.png new file mode 100644 index 0000000..4306ca2 Binary files /dev/null and b/.dirimages/diskimage.png differ diff --git a/.dirimages/fifo.png b/.dirimages/fifo.png new file mode 100644 index 0000000..79a24f7 Binary files /dev/null and b/.dirimages/fifo.png differ diff --git a/.dirimages/font.png b/.dirimages/font.png new file mode 100644 index 0000000..58942e9 Binary files /dev/null and b/.dirimages/font.png differ diff --git a/.dirimages/html.png b/.dirimages/html.png new file mode 100644 index 0000000..0bd2993 Binary files /dev/null and b/.dirimages/html.png differ diff --git a/.dirimages/hwdevice.png b/.dirimages/hwdevice.png new file mode 100644 index 0000000..3310396 Binary files /dev/null and b/.dirimages/hwdevice.png differ diff --git a/.dirimages/image.png b/.dirimages/image.png new file mode 100644 index 0000000..5c9d726 Binary files /dev/null and b/.dirimages/image.png differ diff --git a/.dirimages/important.png b/.dirimages/important.png new file mode 100644 index 0000000..b68e876 Binary files /dev/null and b/.dirimages/important.png differ diff --git a/.dirimages/javascript.png b/.dirimages/javascript.png new file mode 100644 index 0000000..3392699 Binary files /dev/null and b/.dirimages/javascript.png differ diff --git a/.dirimages/other.png b/.dirimages/other.png new file mode 100644 index 0000000..29c53a3 Binary files /dev/null and b/.dirimages/other.png differ diff --git a/.dirimages/php.png b/.dirimages/php.png new file mode 100644 index 0000000..93e9834 Binary files /dev/null and b/.dirimages/php.png differ diff --git a/.dirimages/return.png b/.dirimages/return.png new file mode 100644 index 0000000..83e9a2a Binary files /dev/null and b/.dirimages/return.png differ diff --git a/.dirimages/socket.png b/.dirimages/socket.png new file mode 100644 index 0000000..19bc9ca Binary files /dev/null and b/.dirimages/socket.png differ diff --git a/.dirimages/text.png b/.dirimages/text.png new file mode 100644 index 0000000..fc4cd51 Binary files /dev/null and b/.dirimages/text.png differ diff --git a/.dirimages/video.png b/.dirimages/video.png new file mode 100644 index 0000000..8d44d54 Binary files /dev/null and b/.dirimages/video.png differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..86e6d90 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +commit.sh diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ded992d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 DorianTech S.A. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/config.json b/config.json new file mode 100644 index 0000000..9090fe9 --- /dev/null +++ b/config.json @@ -0,0 +1,86 @@ +{ + "users": [], + "port": 80, + "pubport": 80, + "page404": "404.html", + "timestamp": 1680954429282, + "blacklist": [], + "nonStandardCodes": [], + "enableCompression": true, + "customHeaders": {}, + "enableHTTP2": false, + "enableLogging": true, + "enableDirectoryListing": true, + "enableDirectoryListingWithDefaultHead": false, + "serverAdministratorEmail": "[no contact information]", + "stackHidden": false, + "enableRemoteLogBrowsing": true, + "exposeServerVersion": true, + "disableServerSideScriptExpose": false, + "rewriteMap": [ + { + "definingRegex": "/\\/invoke500\\/\\?/", + "replacements": [ + { + "regex": "/\\/invoke500\\/\\?/", + "replacement": "/invoke500.svr?" + } + ] + }, + { + "definingRegex": "/\\/invoke500\\/.+\\//", + "replacements": [ + { + "regex": "/\\/\\?/", + "replacement": "&" + }, + { + "regex": "/invoke500\\//", + "replacement": "invoke500.svr?" + }, + { + "regex": "/\\/(?!invoke500.svr?)/", + "replacement": "" + } + ] + }, + { + "definingRegex": "/\\/invoke500\\/.+/", + "replacements": [ + { + "regex": "/\\?/", + "replacement": "&" + }, + { + "regex": "/invoke500\\//", + "replacement": "invoke500.svr?" + } + ] + }, + { + "definingRegex": "/\\/invoke500\\//", + "replacements": [ + { + "regex": "/\\/invoke500\\//", + "replacement": "/invoke500.svr" + } + ] + }, + { + "definingRegex": "/\\/invoke500$/", + "replacements": [ + { + "regex": "/\\/invoke500/", + "replacement": "/invoke500.svr" + } + ] + } + ], + "allowStatus": true, + "dontCompress": ["/.*\\.ipxe$/","/.*\\.img$/","/.*\\.iso$/"], + "enableIPSpoofing": false, + "secure": false, + "sni": {}, + "disableNonEncryptedServer": false, + "disableToHTTPSRedirect": false +} diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..c5d08a7 Binary files /dev/null and b/favicon.ico differ diff --git a/hexstrbase64/fail.png b/hexstrbase64/fail.png new file mode 100644 index 0000000..bbebb5d Binary files /dev/null and b/hexstrbase64/fail.png differ diff --git a/hexstrbase64/hexstrbase64/base64.js b/hexstrbase64/hexstrbase64/base64.js new file mode 100644 index 0000000..a995d36 --- /dev/null +++ b/hexstrbase64/hexstrbase64/base64.js @@ -0,0 +1,124 @@ +//Base64.js for hexstrbase64 library for Node.js +/* + * Copyright (c) 2012 Miles Shang + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * Usage: + * Set your settings: + * base64.settings.char62 = "-"; + * base64.settings.char63 = "_"; + * etc. + * + * Then: + * base64.encode(str) takes a string and returns the base64 encoding of it. + * base64.decode(str) does the reverse. + */ + +/* TODO: + * Add a "padding_mandatory" flag to check for bad padding in the decoder. + * Add test cases that throw errors. + */ + +var base64 = new Object(); + +base64.settings = { // defaults + "char62" : "+", + "char63" : "/", + "pad" : "=", + "ascii" : false +}; + +/* + * Settings: + * If "pad" is not null or undefined, then it will be used for encoding. + * + * If "ascii" is set to true, then the encoder + * will assume that plaintext is in 8-bit chars (the standard). + * In this case, for every 3 chars in plaintext, you get 4 chars of base64. + * Any non-8-bit chars will cause an error. + * Otherwise, assume that all plaintext can be in the full range + * of Javascript chars, i.e. 16 bits. Get 8 chars of base64 for 3 chars + * of plaintext. Any possible JS string can be encoded. + */ + +base64.encode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + for (var i = 0; i < str.length; ++i) { + var c_num = str.charCodeAt(i); + if (this.settings.ascii) + if (c_num >= 256) + throw "Not an 8-bit char."; + var c_bin = c_num.toString(2); + while (c_bin.length < (this.settings.ascii ? 8 : 16)) + c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= 6) { + var sextet = buf.slice(0, 6); + buf = buf.slice(6); + output += this.char_set.charAt(parseInt(sextet, 2)); + } + } + + if (buf) { // not empty + while (buf.length < 6) buf += "0"; + output += this.char_set.charAt(parseInt(buf, 2)); + } + + if (this.settings.pad) + while (output.length % (this.settings.ascii ? 4 : 8) != 0) + output += this.settings.pad; + + return output; +} + +base64.decode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + var bits = (this.settings.ascii ? 8 : 16); + for (var i = 0; i < str.length; ++i) { + if (str[i] == this.settings.pad) break; + var c_num = this.char_set.indexOf(str.charAt(i)); + if (c_num == -1) throw "Not base64."; + var c_bin = c_num.toString(2); + while (c_bin.length < 6) c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= bits) { + var octet = buf.slice(0, bits); + buf = buf.slice(bits); + output += String.fromCharCode(parseInt(octet, 2)); + } + } + return output; +} +module.exports = base64; \ No newline at end of file diff --git a/hexstrbase64/hexstrbase64/base64_browser.js b/hexstrbase64/hexstrbase64/base64_browser.js new file mode 100644 index 0000000..44dec66 --- /dev/null +++ b/hexstrbase64/hexstrbase64/base64_browser.js @@ -0,0 +1,123 @@ +//Base64.js for hexstrbase64 library for browser +/* + * Copyright (c) 2012 Miles Shang + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * Usage: + * Set your settings: + * base64.settings.char62 = "-"; + * base64.settings.char63 = "_"; + * etc. + * + * Then: + * base64.encode(str) takes a string and returns the base64 encoding of it. + * base64.decode(str) does the reverse. + */ + +/* TODO: + * Add a "padding_mandatory" flag to check for bad padding in the decoder. + * Add test cases that throw errors. + */ + +var base64 = new Object(); + +base64.settings = { // defaults + "char62" : "+", + "char63" : "/", + "pad" : "=", + "ascii" : false +}; + +/* + * Settings: + * If "pad" is not null or undefined, then it will be used for encoding. + * + * If "ascii" is set to true, then the encoder + * will assume that plaintext is in 8-bit chars (the standard). + * In this case, for every 3 chars in plaintext, you get 4 chars of base64. + * Any non-8-bit chars will cause an error. + * Otherwise, assume that all plaintext can be in the full range + * of Javascript chars, i.e. 16 bits. Get 8 chars of base64 for 3 chars + * of plaintext. Any possible JS string can be encoded. + */ + +base64.encode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + for (var i = 0; i < str.length; ++i) { + var c_num = str.charCodeAt(i); + if (this.settings.ascii) + if (c_num >= 256) + throw "Not an 8-bit char."; + var c_bin = c_num.toString(2); + while (c_bin.length < (this.settings.ascii ? 8 : 16)) + c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= 6) { + var sextet = buf.slice(0, 6); + buf = buf.slice(6); + output += this.char_set.charAt(parseInt(sextet, 2)); + } + } + + if (buf) { // not empty + while (buf.length < 6) buf += "0"; + output += this.char_set.charAt(parseInt(buf, 2)); + } + + if (this.settings.pad) + while (output.length % (this.settings.ascii ? 4 : 8) != 0) + output += this.settings.pad; + + return output; +} + +base64.decode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + var bits = (this.settings.ascii ? 8 : 16); + for (var i = 0; i < str.length; ++i) { + if (str[i] == this.settings.pad) break; + var c_num = this.char_set.indexOf(str.charAt(i)); + if (c_num == -1) throw "Not base64."; + var c_bin = c_num.toString(2); + while (c_bin.length < 6) c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= bits) { + var octet = buf.slice(0, bits); + buf = buf.slice(bits); + output += String.fromCharCode(parseInt(octet, 2)); + } + } + return output; +} \ No newline at end of file diff --git a/hexstrbase64/hexstrbase64/main.js b/hexstrbase64/hexstrbase64/main.js new file mode 100644 index 0000000..4f3d12d --- /dev/null +++ b/hexstrbase64/hexstrbase64/main.js @@ -0,0 +1,129 @@ +//Requires base64 +var base64 = require('./base64.js'); +var HexStrBase64Buffer = { + from: function(s, e) { + var type = e; + var value = ''; + if (e == 'base64') { + value = base64.decode(s); + } else if (e == 'hex') { + try { + var escaped = ""; + var hex = ""; + if(s.length%4 > 0) { + for(i=0;i<(4-(s.length%4));i++) { + hex += "0"; + } + } + hex += s; + for(var i = 0;i 4) { + result += hex.substring(hex.length-5,hex.length-1); + } else if(hex.length < 4) { + for(var j=0;j<=4-(hex.length%4);j++) { + result += "0"; + } + result += hex; + } + } + return result.split("undefined").join("").split("%").join(""); + } else { + //return Buffer.from(value, type).toString(en); + return Buffer.from(value,"utf8").toString(en); + } + } + //} + //function toString(en) { + //return toStringE(en,type); + //} + return { type: type, value: value, toString: toString }; + } +}; +var hexstrbase64 = { + strtobase64: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('base64'); + }, + base64tostr: function(b) { + return HexStrBase64Buffer.from(b, 'base64').toString('utf8'); + }, + strtohex: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('hex'); + }, + hextostr: function(h) { + return HexStrBase64Buffer.from(h, 'hex').toString('utf8'); + }, + hextobase64: function(h) { + return hexstrbase64.strtobase64(hexstrbase64.hextostr(h)); + }, + base64tohex: function(b) { + return hexstrbase64.strtohex(hexstrbase64.base64tostr(b)); + }, + cipher: function() { + this.strtobase64 = hexstrbase64.strtobase64; + this.base64tostr = hexstrbase64.base64tostr; + this.strtohex = hexstrbase64.strtohex; + this.hextostr = hexstrbase64.hextostr; + this.hextobase64 = hextobase64.hextobase64; + this.base64tohex = hextobase64.base64tohex; + }, + native: { + btoa: function(b) { + return hexstrbase64.strtobase64(b); + }, + atob: function(a) { + return hexstrbase64.base64tostr(a); + } + } +}; +module.exports = hexstrbase64; \ No newline at end of file diff --git a/hexstrbase64/hexstrbase64/main_browser.js b/hexstrbase64/hexstrbase64/main_browser.js new file mode 100644 index 0000000..a2b4531 --- /dev/null +++ b/hexstrbase64/hexstrbase64/main_browser.js @@ -0,0 +1,126 @@ +//Requires base64_browser.js +var HexStrBase64Buffer = { + from: function(s, e) { + var type = e; + var value = ''; + if (e == 'base64') { + value = base64.decode(s); + } else if (e == 'hex') { + try { + var escaped = ""; + var hex = ""; + if(s.length%4 > 0) { + for(i=0;i<(4-(s.length%4));i++) { + hex += "0"; + } + } + hex += s; + for(var i = 0;i 4) { + result += hex.substring(hex.length-5,hex.length-1); + } else if(hex.length < 4) { + for(var j=0;j<=4-(hex.length%4);j++) { + result += "0"; + } + result += hex; + } + } + return result.split("undefined").join("").split("%").join(""); + } else { + //return new TextDecoder(en).decode(new TextEncoder(type).encode(value)); + return new TextDecoder(en).decode(new TextEncoder("utf8").encode(value)); + } + } + //function toString(en) { + //return toStringE(en,type); + //} + return { type: type, value: value, toString: toString }; + } +}; +var hexstrbase64 = { + strtobase64: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('base64'); + }, + base64tostr: function(b) { + return HexStrBase64Buffer.from(b, 'base64').toString('utf8'); + }, + strtohex: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('hex'); + }, + hextostr: function(h) { + return HexStrBase64Buffer.from(h, 'hex').toString('utf8'); + }, + hextobase64: function(h) { + return hexstrbase64.strtobase64(hexstrbase64.hextostr(h)); + }, + base64tohex: function(b) { + return hexstrbase64.strtohex(hexstrbase64.base64tostr(b)); + }, + cipher: function() { + this.strtobase64 = hexstrbase64.strtobase64; + this.base64tostr = hexstrbase64.base64tostr; + this.strtohex = hexstrbase64.strtohex; + this.hextostr = hexstrbase64.hextostr; + this.hextobase64 = hextobase64.hextobase64; + this.base64tohex = hextobase64.base64tohex; + }, + native: { + btoa: function(b) { + return hexstrbase64.strtobase64(b); + }, + atob: function(a) { + return hexstrbase64.base64tostr(a); + } + } +}; \ No newline at end of file diff --git a/hexstrbase64/index.js b/hexstrbase64/index.js new file mode 100644 index 0000000..4ec8879 --- /dev/null +++ b/hexstrbase64/index.js @@ -0,0 +1,11 @@ +let hexstrbase64 = require("./hexstrbase64/main.js"); +function decodeBase(b) { + return hexstrbase64.native.atob(b); +} +function encodeStr(s) { + return hexstrbase64.native.btoa(s); +} +var m = Object.create(hexstrbase64); +m.decodeBase = decodeBase; +m.encodeBase = encodeStr; +module.exports = m; \ No newline at end of file diff --git a/hexstrbase64/ok.png b/hexstrbase64/ok.png new file mode 100644 index 0000000..1293b27 Binary files /dev/null and b/hexstrbase64/ok.png differ diff --git a/hexstrbase64/readme.css b/hexstrbase64/readme.css new file mode 100644 index 0000000..aa7c526 --- /dev/null +++ b/hexstrbase64/readme.css @@ -0,0 +1,8 @@ +.code { + border-width: 5px; + border-color: #BEBEBE; + border-style: solid; + color:black; + background-color: #7F7F7F; + font-family: Hack,Consolas,Monaco,monospace; +} \ No newline at end of file diff --git a/hexstrbase64/readme.html b/hexstrbase64/readme.html new file mode 100644 index 0000000..54a6a47 --- /dev/null +++ b/hexstrbase64/readme.html @@ -0,0 +1,31 @@ + + + + HexStrBase64 Readme + + + +

hexstrbase64

+

How to install?

+

Node.js

+
    +
  1. Download library from here.
  2. +
  3. Modify index.js
  4. +
  5. Write header in program (replace ./hexstrbase64 with your path to hexstrbase64 library):
  6. +
    + var hexstrbase64 = require("./hexstrbase64/index.js");
    +
    +
  7. Now hexstrbase64 library added to program!
  8. +
+

Browser Javascript

+
    +
  1. Download library from here.
  2. +
  3. Write this code in <head> element (replace hexstrbase64/ with your path to hexstrbase64 library):
  4. +
    + <script src="hexstrbase64/hexstrbase64/base64_browser.js"></script>
    + <script src="hexstrbase64/hexstrbase64/main_browser.js"></script> +
    +
  5. Now hexstrbase64 library added to HTML!
  6. +
+ + \ No newline at end of file diff --git a/hexstrbase64/test/base64.html b/hexstrbase64/test/base64.html new file mode 100644 index 0000000..18a02a0 --- /dev/null +++ b/hexstrbase64/test/base64.html @@ -0,0 +1,13 @@ + + + + + hexstrbase64 base64 test + + + + + + \ No newline at end of file diff --git a/hexstrbase64/test/base64.js b/hexstrbase64/test/base64.js new file mode 100644 index 0000000..c425403 --- /dev/null +++ b/hexstrbase64/test/base64.js @@ -0,0 +1,56 @@ +function nameObj(n, v) { + return {name:n, value:v}; +} + +function testStart() { + document.write(''); + document.write('hexstrbase64 base64 test'); + console.log("TESTING STARTED"); + for (var i = 0; i < 3; i++) { + document.write('

' + enccases[i].name + '

'); + console.log("SWITCH " + enccases[i].name); + for (var j = 0; j < 2; j++) { + document.write('

' + enccases[i].value[j].name + '

'); + console.log("CASE " + enccases[i].value[j].name); + console.log("MUST BE: " + enccases[i].value[j].value); + console.log("IS : " + hexstrbase64.strtobase64(enccases[i].value[j].name)); + if (hexstrbase64.strtobase64(enccases[i].value[j].name) == enccases[i].value[j].value) { + document.write('

Equals

'); + console.log("EQUALS"); + } else { + document.write('

Not Equals

'); + console.log("NOT EQUALS"); + } + console.log("CASE " + enccases[i].value[j].name + " ENDED"); + } + console.log("SWITCH " + enccases[i].name + " ENDED"); + } + console.log("TESTING ENDED"); +} + +var enccases = [ + nameObj('Ascii', [ + nameObj('Hello world!', 'AEgAZQBsAGwAbwAgAHcAbwByAGwAZAAh'), + nameObj('Lorem ipsum', 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQ==') + ]), + nameObj('Ascii More Than 64 Bytes', [ + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ac nisl a sollicitudin. Cras interdum dui turpis, non scelerisque.', + 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQAgAGQAbwBsAG8AcgAgAHMAaQB0ACAAYQBtAGUAdAAsACAAYwBvAG4AcwBlAGMAdABlAHQAdQByACAAYQBkAGkAcABpAHMAYwBpAG4AZwAgAGUAbABpAHQALgAgAFYAZQBzAHQAaQBiAHUAbAB1AG0AIABmAGUAcgBtAGUAbgB0AHUAbQAgAGEAYwAgAG4AaQBzAGwAIABhACAAcwBvAGwAbABpAGMAaQB0AHUAZABpAG4ALgAgAEMAcgBhAHMAIABpAG4AdABlAHIAZAB1AG0AIABkAHUAaQAgAHQAdQByAHAAaQBzACwAIABuAG8AbgAgAHMAYwBlAGwAZQByAGkAcwBxAHUAZQAu' + ), + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus volutpat ligula at pulvinar. Etiam consequat mi fringilla facilisis eleifend.', + 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQAgAGQAbwBsAG8AcgAgAHMAaQB0ACAAYQBtAGUAdAAsACAAYwBvAG4AcwBlAGMAdABlAHQAdQByACAAYQBkAGkAcABpAHMAYwBpAG4AZwAgAGUAbABpAHQALgAgAFAAaABhAHMAZQBsAGwAdQBzACAAZABhAHAAaQBiAHUAcwAgAHYAbwBsAHUAdABwAGEAdAAgAGwAaQBnAHUAbABhACAAYQB0ACAAcAB1AGwAdgBpAG4AYQByAC4AIABFAHQAaQBhAG0AIABjAG8AbgBzAGUAcQB1AGEAdAAgAG0AaQAgAGYAcgBpAG4AZwBpAGwAbABhACAAZgBhAGMAaQBsAGkAcwBpAHMAIABlAGwAZQBpAGYAZQBuAGQALg==' + ) + ]), + nameObj('Unicode UTF8', [ + nameObj( + 'DorianTech Hex String Base64转换器', + 'AEQAbwByAGkAYQBuAFQAZQBjAGgAIABIAGUAeAAgAFMAdAByAGkAbgBnACAAQgBhAHMAZQA2ADSPbGNiVmg=====' + ), + nameObj( + 'DorianTech Hex String Base64转换器,用于由DorianTech提供的Node.js', + 'AEQAbwByAGkAYQBuAFQAZQBjAGgAIABIAGUAeAAgAFMAdAByAGkAbgBnACAAQgBhAHMAZQA2ADSPbGNiVmj/DHUoTo51MQBEAG8AcgBpAGEAbgBUAGUAYwBoY9BPm3aEAE4AbwBkAGUALgBqAHM=====' + ) + ]) +]; \ No newline at end of file diff --git a/hexstrbase64/test/hex.html b/hexstrbase64/test/hex.html new file mode 100644 index 0000000..713dd6c --- /dev/null +++ b/hexstrbase64/test/hex.html @@ -0,0 +1,13 @@ + + + + + hexstrbase64 hex test + + + + + + \ No newline at end of file diff --git a/hexstrbase64/test/hex.js b/hexstrbase64/test/hex.js new file mode 100644 index 0000000..8a57a8a --- /dev/null +++ b/hexstrbase64/test/hex.js @@ -0,0 +1,56 @@ +function nameObj(n, v) { + return {name:n, value:v}; +} + +function testStart() { + document.write(''); + document.write('hexstrbase64 hex test'); + console.log("TESTING STARTED"); + for (var i = 0; i < 3; i++) { + document.write('

' + enccases[i].name + '

'); + console.log("SWITCH " + enccases[i].name); + for (var j = 0; j < 2; j++) { + document.write('

' + enccases[i].value[j].name + '

'); + console.log("CASE " + enccases[i].value[j].name); + console.log("MUST BE: " + enccases[i].value[j].value); + console.log("IS : " + hexstrbase64.strtohex(enccases[i].value[j].name)); + if (hexstrbase64.strtohex(enccases[i].value[j].name) == enccases[i].value[j].value) { + document.write('

Equals

'); + console.log("EQUALS"); + } else { + document.write('

Not Equals

'); + console.log("NOT EQUALS"); + } + console.log("CASE " + enccases[i].value[j].name + " ENDED"); + } + console.log("SWITCH " + enccases[i].name + " ENDED"); + } + console.log("TESTING ENDED"); +} + +var enccases = [ + nameObj('Ascii', [ + nameObj('Hello world!', '00480065006c006c006f00200077006f0072006c00640021'), + nameObj('Lorem ipsum', '004c006f00720065006d00200069007000730075006d') + ]), + nameObj('Ascii More Than 64 Bytes', [ + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ac nisl a sollicitudin. Cras interdum dui turpis, non scelerisque.', + '004c006f00720065006d00200069007000730075006d00200064006f006c006f0072002000730069007400200061006d00650074002C00200063006f006e00730065006300740065007400750072002000610064006900700069007300630069006e006700200065006c00690074002e00200056006500730074006900620075006c0075006d0020006600650072006d0065006e00740075006d0020006100630020006e00690073006c0020006100200073006f006c006c0069006300690074007500640069006e002e0020004300720061007300200069006e00740065007200640075006d00200064007500690020007400750072007000690073002C0020006e006f006e0020007300630065006c0065007200690073007100750065002e' + ), + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus volutpat ligula at pulvinar. Etiam consequat mi fringilla facilisis eleifend.', + '004c006f00720065006d00200069007000730075006d00200064006f006c006f0072002000730069007400200061006d00650074002C00200063006f006e00730065006300740065007400750072002000610064006900700069007300630069006e006700200065006c00690074002e002000500068006100730065006c006c007500730020006400610070006900620075007300200076006f006c007500740070006100740020006c006900670075006c0061002000610074002000700075006c00760069006e00610072002e00200045007400690061006d00200063006f006e0073006500710075006100740020006d00690020006600720069006e00670069006c006c006100200066006100630069006c006900730069007300200065006c0065006900660065006e0064002e' + ) + ]), + nameObj('Unicode UTF8', [ + nameObj( + 'DorianTech Hex String Base64转换器', + '0044006f007200690061006e0054006500630068002000480065007800200053007400720069006e006700200042006100730065003600348F6C63625668' + ), + nameObj( + 'DorianTech Hex String Base64转换器,用于由DorianTech提供的Node.js', + '0044006f007200690061006e0054006500630068002000480065007800200053007400720069006e006700200042006100730065003600348F6C63625668FF0C75284E8E75310044006f007200690061006e005400650063006863D04F9B7684004e006f00640065002e006a0073' + ) + ]) +]; \ No newline at end of file diff --git a/hexstrbase64/test/index.html b/hexstrbase64/test/index.html new file mode 100644 index 0000000..b0ae622 --- /dev/null +++ b/hexstrbase64/test/index.html @@ -0,0 +1,16 @@ + + + + hexstrbase64 test + + + + + + + \ No newline at end of file diff --git a/hviews.txt b/hviews.txt new file mode 100644 index 0000000..573541a --- /dev/null +++ b/hviews.txt @@ -0,0 +1 @@ +0 diff --git a/index.html b/index.html new file mode 100644 index 0000000..8bb0e4c --- /dev/null +++ b/index.html @@ -0,0 +1,130 @@ + + + + SVR.JS 3.4.17 + + + + + +

Welcome to SVR.JS 3.4.17

+
+ +
+

If you see this page, that means, that the server is properly working. You can further configure the server and replace index.html and tests.html pages with custom ones.

+

Default config.json looks like this:

+
+ + {
+   "users": [],
+   "port": 80,
+   "pubport": 80,
+   "page404": "404.html",
+   "timestamp": 1680954429282,
+   "blacklist": [],
+   "nonStandardCodes": [],
+   "enableCompression": true,
+   "customHeaders": {},
+   "enableHTTP2": false,
+   "enableLogging": true,
+   "enableDirectoryListing": true,
+   "enableDirectoryListingWithDefaultHead": false,
+   "serverAdministratorEmail": "[no contact information]",
+   "stackHidden": false,
+   "enableRemoteLogBrowsing": true,
+   "exposeServerVersion": true,
+   "disableServerSideScriptExpose": false,
+   "rewriteMap": [
+     {
+       "definingRegex": "/\\/invoke500\\/\\?/",
+       "replacements": dorians[
+         {
+           "regex": "/\\/invoke500\\/\\?/",
+           "replacement": "/invoke500.svr?"
+         }
+       ]
+     },
+     {
+       "definingRegex": "/\\/invoke500\\/.+\\//",
+       "replacements": [
+         {
+           "regex": "/\\/\\?/",
+           "replacement": "&"
+         },
+         {
+           "regex": "/invoke500\\//",
+           "replacement": "invoke500.svr?"
+         },
+         {
+           "regex": "/\\/(?!invoke500.svr?)/",
+           "replacement": ""
+         }
+       ]
+     },
+     {
+       "definingRegex": "/\\/invoke500\\/.+/",
+       "replacements": [
+         {
+           "regex": "/\\?/",
+           "replacement": "&"
+         },
+         {
+           "regex": "/invoke500\\//",
+           "replacement": "invoke500.svr?"
+         }
+       ]
+     },
+     {
+       "definingRegex": "/\\/invoke500\\//",
+       "replacements": [
+         {
+           "regex": "/\\/invoke500\\//",
+           "replacement": "/invoke500.svr"
+         }
+       ]
+     },
+     {
+       "definingRegex": "/\\/invoke500$/",
+       "replacements": [
+         {
+           "regex": "/\\/invoke500/",
+           "replacement": "/invoke500.svr"
+         }
+       ]
+     }
+   ],
+   "allowStatus": true,
+   "dontCompress": ["/.*\\.ipxe$/","/.*\\.img$/","/.*\\.iso$/"],
+   "enableIPSpoofing": false,
+   "secure": false,
+   "sni": {},
+   "disableNonEncryptedServer": false,
+   "disableToHTTPSRedirect": false
+ } +
+
+

Changes:

+
    +
  • Improved URL sanitizer.
  • +
  • Fixed bug with formidable wrapper.
  • +
+

Bugs:

+
    +
  • Some very old mods requiring hexstrbase64 will fail to load.
  • +
  • On first load server-side JavaScript will fail to load when SVR.JS is running on Bun.
  • +
+
+ Tests
+ Licenses
+ SVR.JS status page
+ More Information +
+
+ + + diff --git a/lib/hexstrbase64/fail.png b/lib/hexstrbase64/fail.png new file mode 100644 index 0000000..bbebb5d Binary files /dev/null and b/lib/hexstrbase64/fail.png differ diff --git a/lib/hexstrbase64/hexstrbase64/base64.js b/lib/hexstrbase64/hexstrbase64/base64.js new file mode 100644 index 0000000..a995d36 --- /dev/null +++ b/lib/hexstrbase64/hexstrbase64/base64.js @@ -0,0 +1,124 @@ +//Base64.js for hexstrbase64 library for Node.js +/* + * Copyright (c) 2012 Miles Shang + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * Usage: + * Set your settings: + * base64.settings.char62 = "-"; + * base64.settings.char63 = "_"; + * etc. + * + * Then: + * base64.encode(str) takes a string and returns the base64 encoding of it. + * base64.decode(str) does the reverse. + */ + +/* TODO: + * Add a "padding_mandatory" flag to check for bad padding in the decoder. + * Add test cases that throw errors. + */ + +var base64 = new Object(); + +base64.settings = { // defaults + "char62" : "+", + "char63" : "/", + "pad" : "=", + "ascii" : false +}; + +/* + * Settings: + * If "pad" is not null or undefined, then it will be used for encoding. + * + * If "ascii" is set to true, then the encoder + * will assume that plaintext is in 8-bit chars (the standard). + * In this case, for every 3 chars in plaintext, you get 4 chars of base64. + * Any non-8-bit chars will cause an error. + * Otherwise, assume that all plaintext can be in the full range + * of Javascript chars, i.e. 16 bits. Get 8 chars of base64 for 3 chars + * of plaintext. Any possible JS string can be encoded. + */ + +base64.encode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + for (var i = 0; i < str.length; ++i) { + var c_num = str.charCodeAt(i); + if (this.settings.ascii) + if (c_num >= 256) + throw "Not an 8-bit char."; + var c_bin = c_num.toString(2); + while (c_bin.length < (this.settings.ascii ? 8 : 16)) + c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= 6) { + var sextet = buf.slice(0, 6); + buf = buf.slice(6); + output += this.char_set.charAt(parseInt(sextet, 2)); + } + } + + if (buf) { // not empty + while (buf.length < 6) buf += "0"; + output += this.char_set.charAt(parseInt(buf, 2)); + } + + if (this.settings.pad) + while (output.length % (this.settings.ascii ? 4 : 8) != 0) + output += this.settings.pad; + + return output; +} + +base64.decode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + var bits = (this.settings.ascii ? 8 : 16); + for (var i = 0; i < str.length; ++i) { + if (str[i] == this.settings.pad) break; + var c_num = this.char_set.indexOf(str.charAt(i)); + if (c_num == -1) throw "Not base64."; + var c_bin = c_num.toString(2); + while (c_bin.length < 6) c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= bits) { + var octet = buf.slice(0, bits); + buf = buf.slice(bits); + output += String.fromCharCode(parseInt(octet, 2)); + } + } + return output; +} +module.exports = base64; \ No newline at end of file diff --git a/lib/hexstrbase64/hexstrbase64/base64_browser.js b/lib/hexstrbase64/hexstrbase64/base64_browser.js new file mode 100644 index 0000000..44dec66 --- /dev/null +++ b/lib/hexstrbase64/hexstrbase64/base64_browser.js @@ -0,0 +1,123 @@ +//Base64.js for hexstrbase64 library for browser +/* + * Copyright (c) 2012 Miles Shang + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * Usage: + * Set your settings: + * base64.settings.char62 = "-"; + * base64.settings.char63 = "_"; + * etc. + * + * Then: + * base64.encode(str) takes a string and returns the base64 encoding of it. + * base64.decode(str) does the reverse. + */ + +/* TODO: + * Add a "padding_mandatory" flag to check for bad padding in the decoder. + * Add test cases that throw errors. + */ + +var base64 = new Object(); + +base64.settings = { // defaults + "char62" : "+", + "char63" : "/", + "pad" : "=", + "ascii" : false +}; + +/* + * Settings: + * If "pad" is not null or undefined, then it will be used for encoding. + * + * If "ascii" is set to true, then the encoder + * will assume that plaintext is in 8-bit chars (the standard). + * In this case, for every 3 chars in plaintext, you get 4 chars of base64. + * Any non-8-bit chars will cause an error. + * Otherwise, assume that all plaintext can be in the full range + * of Javascript chars, i.e. 16 bits. Get 8 chars of base64 for 3 chars + * of plaintext. Any possible JS string can be encoded. + */ + +base64.encode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + for (var i = 0; i < str.length; ++i) { + var c_num = str.charCodeAt(i); + if (this.settings.ascii) + if (c_num >= 256) + throw "Not an 8-bit char."; + var c_bin = c_num.toString(2); + while (c_bin.length < (this.settings.ascii ? 8 : 16)) + c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= 6) { + var sextet = buf.slice(0, 6); + buf = buf.slice(6); + output += this.char_set.charAt(parseInt(sextet, 2)); + } + } + + if (buf) { // not empty + while (buf.length < 6) buf += "0"; + output += this.char_set.charAt(parseInt(buf, 2)); + } + + if (this.settings.pad) + while (output.length % (this.settings.ascii ? 4 : 8) != 0) + output += this.settings.pad; + + return output; +} + +base64.decode = function (str) { + this.char_set = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + + this.settings.char62 + this.settings.char63; + + var output = ""; // final output + var buf = ""; // binary buffer + var bits = (this.settings.ascii ? 8 : 16); + for (var i = 0; i < str.length; ++i) { + if (str[i] == this.settings.pad) break; + var c_num = this.char_set.indexOf(str.charAt(i)); + if (c_num == -1) throw "Not base64."; + var c_bin = c_num.toString(2); + while (c_bin.length < 6) c_bin = "0" + c_bin; + buf += c_bin; + + while (buf.length >= bits) { + var octet = buf.slice(0, bits); + buf = buf.slice(bits); + output += String.fromCharCode(parseInt(octet, 2)); + } + } + return output; +} \ No newline at end of file diff --git a/lib/hexstrbase64/hexstrbase64/main.js b/lib/hexstrbase64/hexstrbase64/main.js new file mode 100644 index 0000000..4f3d12d --- /dev/null +++ b/lib/hexstrbase64/hexstrbase64/main.js @@ -0,0 +1,129 @@ +//Requires base64 +var base64 = require('./base64.js'); +var HexStrBase64Buffer = { + from: function(s, e) { + var type = e; + var value = ''; + if (e == 'base64') { + value = base64.decode(s); + } else if (e == 'hex') { + try { + var escaped = ""; + var hex = ""; + if(s.length%4 > 0) { + for(i=0;i<(4-(s.length%4));i++) { + hex += "0"; + } + } + hex += s; + for(var i = 0;i 4) { + result += hex.substring(hex.length-5,hex.length-1); + } else if(hex.length < 4) { + for(var j=0;j<=4-(hex.length%4);j++) { + result += "0"; + } + result += hex; + } + } + return result.split("undefined").join("").split("%").join(""); + } else { + //return Buffer.from(value, type).toString(en); + return Buffer.from(value,"utf8").toString(en); + } + } + //} + //function toString(en) { + //return toStringE(en,type); + //} + return { type: type, value: value, toString: toString }; + } +}; +var hexstrbase64 = { + strtobase64: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('base64'); + }, + base64tostr: function(b) { + return HexStrBase64Buffer.from(b, 'base64').toString('utf8'); + }, + strtohex: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('hex'); + }, + hextostr: function(h) { + return HexStrBase64Buffer.from(h, 'hex').toString('utf8'); + }, + hextobase64: function(h) { + return hexstrbase64.strtobase64(hexstrbase64.hextostr(h)); + }, + base64tohex: function(b) { + return hexstrbase64.strtohex(hexstrbase64.base64tostr(b)); + }, + cipher: function() { + this.strtobase64 = hexstrbase64.strtobase64; + this.base64tostr = hexstrbase64.base64tostr; + this.strtohex = hexstrbase64.strtohex; + this.hextostr = hexstrbase64.hextostr; + this.hextobase64 = hextobase64.hextobase64; + this.base64tohex = hextobase64.base64tohex; + }, + native: { + btoa: function(b) { + return hexstrbase64.strtobase64(b); + }, + atob: function(a) { + return hexstrbase64.base64tostr(a); + } + } +}; +module.exports = hexstrbase64; \ No newline at end of file diff --git a/lib/hexstrbase64/hexstrbase64/main_browser.js b/lib/hexstrbase64/hexstrbase64/main_browser.js new file mode 100644 index 0000000..a2b4531 --- /dev/null +++ b/lib/hexstrbase64/hexstrbase64/main_browser.js @@ -0,0 +1,126 @@ +//Requires base64_browser.js +var HexStrBase64Buffer = { + from: function(s, e) { + var type = e; + var value = ''; + if (e == 'base64') { + value = base64.decode(s); + } else if (e == 'hex') { + try { + var escaped = ""; + var hex = ""; + if(s.length%4 > 0) { + for(i=0;i<(4-(s.length%4));i++) { + hex += "0"; + } + } + hex += s; + for(var i = 0;i 4) { + result += hex.substring(hex.length-5,hex.length-1); + } else if(hex.length < 4) { + for(var j=0;j<=4-(hex.length%4);j++) { + result += "0"; + } + result += hex; + } + } + return result.split("undefined").join("").split("%").join(""); + } else { + //return new TextDecoder(en).decode(new TextEncoder(type).encode(value)); + return new TextDecoder(en).decode(new TextEncoder("utf8").encode(value)); + } + } + //function toString(en) { + //return toStringE(en,type); + //} + return { type: type, value: value, toString: toString }; + } +}; +var hexstrbase64 = { + strtobase64: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('base64'); + }, + base64tostr: function(b) { + return HexStrBase64Buffer.from(b, 'base64').toString('utf8'); + }, + strtohex: function(s) { + return HexStrBase64Buffer.from(s, 'utf8').toString('hex'); + }, + hextostr: function(h) { + return HexStrBase64Buffer.from(h, 'hex').toString('utf8'); + }, + hextobase64: function(h) { + return hexstrbase64.strtobase64(hexstrbase64.hextostr(h)); + }, + base64tohex: function(b) { + return hexstrbase64.strtohex(hexstrbase64.base64tostr(b)); + }, + cipher: function() { + this.strtobase64 = hexstrbase64.strtobase64; + this.base64tostr = hexstrbase64.base64tostr; + this.strtohex = hexstrbase64.strtohex; + this.hextostr = hexstrbase64.hextostr; + this.hextobase64 = hextobase64.hextobase64; + this.base64tohex = hextobase64.base64tohex; + }, + native: { + btoa: function(b) { + return hexstrbase64.strtobase64(b); + }, + atob: function(a) { + return hexstrbase64.base64tostr(a); + } + } +}; \ No newline at end of file diff --git a/lib/hexstrbase64/index.js b/lib/hexstrbase64/index.js new file mode 100644 index 0000000..4ec8879 --- /dev/null +++ b/lib/hexstrbase64/index.js @@ -0,0 +1,11 @@ +let hexstrbase64 = require("./hexstrbase64/main.js"); +function decodeBase(b) { + return hexstrbase64.native.atob(b); +} +function encodeStr(s) { + return hexstrbase64.native.btoa(s); +} +var m = Object.create(hexstrbase64); +m.decodeBase = decodeBase; +m.encodeBase = encodeStr; +module.exports = m; \ No newline at end of file diff --git a/lib/hexstrbase64/ok.png b/lib/hexstrbase64/ok.png new file mode 100644 index 0000000..1293b27 Binary files /dev/null and b/lib/hexstrbase64/ok.png differ diff --git a/lib/hexstrbase64/readme.css b/lib/hexstrbase64/readme.css new file mode 100644 index 0000000..aa7c526 --- /dev/null +++ b/lib/hexstrbase64/readme.css @@ -0,0 +1,8 @@ +.code { + border-width: 5px; + border-color: #BEBEBE; + border-style: solid; + color:black; + background-color: #7F7F7F; + font-family: Hack,Consolas,Monaco,monospace; +} \ No newline at end of file diff --git a/lib/hexstrbase64/readme.html b/lib/hexstrbase64/readme.html new file mode 100644 index 0000000..54a6a47 --- /dev/null +++ b/lib/hexstrbase64/readme.html @@ -0,0 +1,31 @@ + + + + HexStrBase64 Readme + + + +

hexstrbase64

+

How to install?

+

Node.js

+
    +
  1. Download library from here.
  2. +
  3. Modify index.js
  4. +
  5. Write header in program (replace ./hexstrbase64 with your path to hexstrbase64 library):
  6. +
    + var hexstrbase64 = require("./hexstrbase64/index.js");
    +
    +
  7. Now hexstrbase64 library added to program!
  8. +
+

Browser Javascript

+
    +
  1. Download library from here.
  2. +
  3. Write this code in <head> element (replace hexstrbase64/ with your path to hexstrbase64 library):
  4. +
    + <script src="hexstrbase64/hexstrbase64/base64_browser.js"></script>
    + <script src="hexstrbase64/hexstrbase64/main_browser.js"></script> +
    +
  5. Now hexstrbase64 library added to HTML!
  6. +
+ + \ No newline at end of file diff --git a/lib/hexstrbase64/test/base64.html b/lib/hexstrbase64/test/base64.html new file mode 100644 index 0000000..18a02a0 --- /dev/null +++ b/lib/hexstrbase64/test/base64.html @@ -0,0 +1,13 @@ + + + + + hexstrbase64 base64 test + + + + + + \ No newline at end of file diff --git a/lib/hexstrbase64/test/base64.js b/lib/hexstrbase64/test/base64.js new file mode 100644 index 0000000..c425403 --- /dev/null +++ b/lib/hexstrbase64/test/base64.js @@ -0,0 +1,56 @@ +function nameObj(n, v) { + return {name:n, value:v}; +} + +function testStart() { + document.write(''); + document.write('hexstrbase64 base64 test'); + console.log("TESTING STARTED"); + for (var i = 0; i < 3; i++) { + document.write('

' + enccases[i].name + '

'); + console.log("SWITCH " + enccases[i].name); + for (var j = 0; j < 2; j++) { + document.write('

' + enccases[i].value[j].name + '

'); + console.log("CASE " + enccases[i].value[j].name); + console.log("MUST BE: " + enccases[i].value[j].value); + console.log("IS : " + hexstrbase64.strtobase64(enccases[i].value[j].name)); + if (hexstrbase64.strtobase64(enccases[i].value[j].name) == enccases[i].value[j].value) { + document.write('

Equals

'); + console.log("EQUALS"); + } else { + document.write('

Not Equals

'); + console.log("NOT EQUALS"); + } + console.log("CASE " + enccases[i].value[j].name + " ENDED"); + } + console.log("SWITCH " + enccases[i].name + " ENDED"); + } + console.log("TESTING ENDED"); +} + +var enccases = [ + nameObj('Ascii', [ + nameObj('Hello world!', 'AEgAZQBsAGwAbwAgAHcAbwByAGwAZAAh'), + nameObj('Lorem ipsum', 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQ==') + ]), + nameObj('Ascii More Than 64 Bytes', [ + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ac nisl a sollicitudin. Cras interdum dui turpis, non scelerisque.', + 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQAgAGQAbwBsAG8AcgAgAHMAaQB0ACAAYQBtAGUAdAAsACAAYwBvAG4AcwBlAGMAdABlAHQAdQByACAAYQBkAGkAcABpAHMAYwBpAG4AZwAgAGUAbABpAHQALgAgAFYAZQBzAHQAaQBiAHUAbAB1AG0AIABmAGUAcgBtAGUAbgB0AHUAbQAgAGEAYwAgAG4AaQBzAGwAIABhACAAcwBvAGwAbABpAGMAaQB0AHUAZABpAG4ALgAgAEMAcgBhAHMAIABpAG4AdABlAHIAZAB1AG0AIABkAHUAaQAgAHQAdQByAHAAaQBzACwAIABuAG8AbgAgAHMAYwBlAGwAZQByAGkAcwBxAHUAZQAu' + ), + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus volutpat ligula at pulvinar. Etiam consequat mi fringilla facilisis eleifend.', + 'AEwAbwByAGUAbQAgAGkAcABzAHUAbQAgAGQAbwBsAG8AcgAgAHMAaQB0ACAAYQBtAGUAdAAsACAAYwBvAG4AcwBlAGMAdABlAHQAdQByACAAYQBkAGkAcABpAHMAYwBpAG4AZwAgAGUAbABpAHQALgAgAFAAaABhAHMAZQBsAGwAdQBzACAAZABhAHAAaQBiAHUAcwAgAHYAbwBsAHUAdABwAGEAdAAgAGwAaQBnAHUAbABhACAAYQB0ACAAcAB1AGwAdgBpAG4AYQByAC4AIABFAHQAaQBhAG0AIABjAG8AbgBzAGUAcQB1AGEAdAAgAG0AaQAgAGYAcgBpAG4AZwBpAGwAbABhACAAZgBhAGMAaQBsAGkAcwBpAHMAIABlAGwAZQBpAGYAZQBuAGQALg==' + ) + ]), + nameObj('Unicode UTF8', [ + nameObj( + 'DorianTech Hex String Base64转换器', + 'AEQAbwByAGkAYQBuAFQAZQBjAGgAIABIAGUAeAAgAFMAdAByAGkAbgBnACAAQgBhAHMAZQA2ADSPbGNiVmg=====' + ), + nameObj( + 'DorianTech Hex String Base64转换器,用于由DorianTech提供的Node.js', + 'AEQAbwByAGkAYQBuAFQAZQBjAGgAIABIAGUAeAAgAFMAdAByAGkAbgBnACAAQgBhAHMAZQA2ADSPbGNiVmj/DHUoTo51MQBEAG8AcgBpAGEAbgBUAGUAYwBoY9BPm3aEAE4AbwBkAGUALgBqAHM=====' + ) + ]) +]; \ No newline at end of file diff --git a/lib/hexstrbase64/test/hex.html b/lib/hexstrbase64/test/hex.html new file mode 100644 index 0000000..713dd6c --- /dev/null +++ b/lib/hexstrbase64/test/hex.html @@ -0,0 +1,13 @@ + + + + + hexstrbase64 hex test + + + + + + \ No newline at end of file diff --git a/lib/hexstrbase64/test/hex.js b/lib/hexstrbase64/test/hex.js new file mode 100644 index 0000000..8a57a8a --- /dev/null +++ b/lib/hexstrbase64/test/hex.js @@ -0,0 +1,56 @@ +function nameObj(n, v) { + return {name:n, value:v}; +} + +function testStart() { + document.write(''); + document.write('hexstrbase64 hex test'); + console.log("TESTING STARTED"); + for (var i = 0; i < 3; i++) { + document.write('

' + enccases[i].name + '

'); + console.log("SWITCH " + enccases[i].name); + for (var j = 0; j < 2; j++) { + document.write('

' + enccases[i].value[j].name + '

'); + console.log("CASE " + enccases[i].value[j].name); + console.log("MUST BE: " + enccases[i].value[j].value); + console.log("IS : " + hexstrbase64.strtohex(enccases[i].value[j].name)); + if (hexstrbase64.strtohex(enccases[i].value[j].name) == enccases[i].value[j].value) { + document.write('

Equals

'); + console.log("EQUALS"); + } else { + document.write('

Not Equals

'); + console.log("NOT EQUALS"); + } + console.log("CASE " + enccases[i].value[j].name + " ENDED"); + } + console.log("SWITCH " + enccases[i].name + " ENDED"); + } + console.log("TESTING ENDED"); +} + +var enccases = [ + nameObj('Ascii', [ + nameObj('Hello world!', '00480065006c006c006f00200077006f0072006c00640021'), + nameObj('Lorem ipsum', '004c006f00720065006d00200069007000730075006d') + ]), + nameObj('Ascii More Than 64 Bytes', [ + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ac nisl a sollicitudin. Cras interdum dui turpis, non scelerisque.', + '004c006f00720065006d00200069007000730075006d00200064006f006c006f0072002000730069007400200061006d00650074002C00200063006f006e00730065006300740065007400750072002000610064006900700069007300630069006e006700200065006c00690074002e00200056006500730074006900620075006c0075006d0020006600650072006d0065006e00740075006d0020006100630020006e00690073006c0020006100200073006f006c006c0069006300690074007500640069006e002e0020004300720061007300200069006e00740065007200640075006d00200064007500690020007400750072007000690073002C0020006e006f006e0020007300630065006c0065007200690073007100750065002e' + ), + nameObj( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus volutpat ligula at pulvinar. Etiam consequat mi fringilla facilisis eleifend.', + '004c006f00720065006d00200069007000730075006d00200064006f006c006f0072002000730069007400200061006d00650074002C00200063006f006e00730065006300740065007400750072002000610064006900700069007300630069006e006700200065006c00690074002e002000500068006100730065006c006c007500730020006400610070006900620075007300200076006f006c007500740070006100740020006c006900670075006c0061002000610074002000700075006c00760069006e00610072002e00200045007400690061006d00200063006f006e0073006500710075006100740020006d00690020006600720069006e00670069006c006c006100200066006100630069006c006900730069007300200065006c0065006900660065006e0064002e' + ) + ]), + nameObj('Unicode UTF8', [ + nameObj( + 'DorianTech Hex String Base64转换器', + '0044006f007200690061006e0054006500630068002000480065007800200053007400720069006e006700200042006100730065003600348F6C63625668' + ), + nameObj( + 'DorianTech Hex String Base64转换器,用于由DorianTech提供的Node.js', + '0044006f007200690061006e0054006500630068002000480065007800200053007400720069006e006700200042006100730065003600348F6C63625668FF0C75284E8E75310044006f007200690061006e005400650063006863D04F9B7684004e006f00640065002e006a0073' + ) + ]) +]; \ No newline at end of file diff --git a/lib/hexstrbase64/test/index.html b/lib/hexstrbase64/test/index.html new file mode 100644 index 0000000..b0ae622 --- /dev/null +++ b/lib/hexstrbase64/test/index.html @@ -0,0 +1,16 @@ + + + + hexstrbase64 test + + + + + + + \ No newline at end of file diff --git a/licenses/.index.html.kate-swp b/licenses/.index.html.kate-swp new file mode 100644 index 0000000..d9b6320 Binary files /dev/null and b/licenses/.index.html.kate-swp differ diff --git a/licenses/asap.txt b/licenses/asap.txt new file mode 100644 index 0000000..ba18c61 --- /dev/null +++ b/licenses/asap.txt @@ -0,0 +1,21 @@ + +Copyright 2009–2014 Contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + diff --git a/licenses/asn1.js-rfc2560.txt b/licenses/asn1.js-rfc2560.txt new file mode 100644 index 0000000..e69de29 diff --git a/licenses/asn1.js-rfc5280.txt b/licenses/asn1.js-rfc5280.txt new file mode 100644 index 0000000..e69de29 diff --git a/licenses/asn1.js.txt b/licenses/asn1.js.txt new file mode 100644 index 0000000..e69de29 diff --git a/licenses/async.txt b/licenses/async.txt new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/licenses/async.txt @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/licenses/bn.js.txt b/licenses/bn.js.txt new file mode 100644 index 0000000..c328f04 --- /dev/null +++ b/licenses/bn.js.txt @@ -0,0 +1,19 @@ +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/call-bind.txt b/licenses/call-bind.txt new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/licenses/call-bind.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/chownr.txt b/licenses/chownr.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/chownr.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/dezalgo.txt b/licenses/dezalgo.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/dezalgo.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/formidable.txt b/licenses/formidable.txt new file mode 100644 index 0000000..5e7ad11 --- /dev/null +++ b/licenses/formidable.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011-present Felix Geisendörfer, and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/fs-minipass.txt b/licenses/fs-minipass.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/fs-minipass.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/function-bind.txt b/licenses/function-bind.txt new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/licenses/function-bind.txt @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/licenses/get-intrinsic.txt b/licenses/get-intrinsic.txt new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/licenses/get-intrinsic.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/graceful-fs.txt b/licenses/graceful-fs.txt new file mode 100644 index 0000000..9d2c803 --- /dev/null +++ b/licenses/graceful-fs.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/has-symbols.txt b/licenses/has-symbols.txt new file mode 100644 index 0000000..df31cbf --- /dev/null +++ b/licenses/has-symbols.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/has.txt b/licenses/has.txt new file mode 100644 index 0000000..ae7014d --- /dev/null +++ b/licenses/has.txt @@ -0,0 +1,22 @@ +Copyright (c) 2013 Thiago de Arruda + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/hexoid.txt b/licenses/hexoid.txt new file mode 100644 index 0000000..fa6089f --- /dev/null +++ b/licenses/hexoid.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/index.html b/licenses/index.html new file mode 100644 index 0000000..64063b5 --- /dev/null +++ b/licenses/index.html @@ -0,0 +1,357 @@ + + + + SVR.JS 3.4.17 Licenses + + + + + +

SVR.JS 3.4.17 Licenses

+

SVR.JS 3.4.17

+
+ MIT License
+
+ Copyright (c) 2020 DorianTech S.A.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
+

Packages used by SVR.JS 3.4.17 and utilities

+
+
License: MIT
+
+ asap +
+
+ High-priority task queue for Node.js and browsers +
+
+
+
License: MIT
+
+ asn1.js (by Fedor Indutny) +
+
+ ASN.1 encoder and decoder +
+
+
+
License: MIT
+
+ asn1.js-rfc2560 (by Fedor Indutny) +
+
+ RFC2560 structures for asn1.js +
+
+
+
License: MIT
+
+ asn1.js-rfc5280 (by Felix Hanley) +
+
+ RFC5280 extension structures for asn1.js +
+
+
+
License: MIT
+
+ async (by Caolan McMahon) +
+
+ Higher-order functions and common patterns for asynchronous code +
+
+
+
License: MIT
+
+ bn.js (by Fedor Indutny) +
+
+ Big number implementation in pure javascript +
+
+
+
License: MIT
+
+ call-bind (by Jordan Harband) +
+
+ Robustly `.call.bind()` a function +
+
+
+
License: ISC
+
+ chownr (by Isaac Z. Schlueter) +
+
+ like `chown -R` +
+
+
+
License: ISC
+
+ dezalgo (by Isaac Z. Schlueter) +
+
+ Contain async insanity so that the dark pony lord doesn't eat souls +
+
+
+
License: MIT
+ +
+ A node.js module for parsing form data, especially file uploads.
+ Required by SVR.JS. Patched to work with Node.JS 8.x +
+
+
+
License: ISC
+
+ fs-minipass (by Isaac Z. Schlueter) +
+
+ fs read and write streams based on minipass
+ Patched to work with Bun +
+
+
+
License: MIT
+
+ function-bind (by Raynos) +
+
+ Implementation of Function.prototype.bind +
+
+
+
License: MIT
+
+ get-intrinsic (by Jordan Harband) +
+
+ Get and robustly cache all JS language-level intrinsics at first require time +
+
+
+
License: ISC
+ +
+ A drop-in replacement for fs, making various improvements.
+ Required by SVR.JS. +
+
+
+
License: MIT
+
+ has (by Thiago de Arruda) +
+
+ Object.prototype.hasOwnProperty.call shortcut +
+
+
+
License: MIT
+
+ has-symbols (by Jordan Harband) +
+
+ Determine if the JS environment has Symbol support. Supports spec, or shams. +
+
+
+
License: MIT
+
+ hexoid (by Luke Edwards) +
+
+ A tiny (190B) and extremely fast utility to generate random IDs of fixed length +
+
+
+
License: ISC
+
+ inherits +
+
+ Browser-friendly inheritance fully compatible with standard node.js inherits() +
+
+
+
License: MIT
+
+ mime-db +
+
+ Media Type Database +
+
+
+
License: MIT
+ +
+ The ultimate javascript content-type utility.
+ Required by SVR.JS. +
+
+
+
License: ISC
+ +
+ minimalistic-assert === +
+
+
+
License: ISC
+
+ minipass (by Isaac Z. Schlueter) +
+
+ minimal implementation of a PassThrough stream +
+
+
+
License: MIT
+
+ minizlib (by Isaac Z. Schlueter) +
+
+ A small fast zlib stream built on minipass and Node.js's zlib binding. +
+
+
+
License: MIT
+
+ mkdirp +
+
+ Recursively mkdir, like `mkdir -p` +
+
+
+
License: MIT
+
+ object-inspect (by James Halliday) +
+
+ string representations of objects in node and the browser +
+
+
+
License: MIT
+
+ ocsp (by Fedor Indutny) +
+
+ OCSP Stapling implementation
+ Required by SVR.JS. +
+
+
+
License: ISC
+
+ once (by Isaac Z. Schlueter) +
+
+ Run a function exactly one time +
+
+
+
License: MIT
+
+ pretty-bytes (by Sindre Sorhus) +
+
+ Convert bytes to a human readable string: 1337 → 1.34 kB
+ Required by SVR.JS. +
+
+
+
License: BSD-3
+
+ qs +
+
+ A querystring parser that supports nesting and arrays, with a depth limit +
+
+
+
License: MIT
+
+ side-channel (by Jordan Harband) +
+
+ Store information about any JS value in a side channel. Uses WeakMap if available. +
+
+
+
License: MIT
+
+ simple-lru-cache (by Gabriel Eisbruch) +
+
+ node-simple-lru-cache ===================== +
+
+
+
License: ISC
+
+ tar (by Isaac Z. Schlueter) +
+
+ tar for node
+ Required by SVR.JS. +
+
+
+
License: ISC
+
+ wrappy (by Isaac Z. Schlueter) +
+
+ Callback wrapping utility +
+
+
+
License: ISC
+
+ yallist (by Isaac Z. Schlueter) +
+
+ Yet Another Linked List +
+
+
+ + + diff --git a/licenses/inherits.txt b/licenses/inherits.txt new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/licenses/inherits.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/licenses/mime-db.txt b/licenses/mime-db.txt new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/licenses/mime-db.txt @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/licenses/mime-types.txt b/licenses/mime-types.txt new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/licenses/mime-types.txt @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/minimalistic-assert.txt b/licenses/minimalistic-assert.txt new file mode 100644 index 0000000..adca66b --- /dev/null +++ b/licenses/minimalistic-assert.txt @@ -0,0 +1,13 @@ +Copyright 2015 Calvin Metcalf + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/licenses/minipass.txt b/licenses/minipass.txt new file mode 100644 index 0000000..20a4762 --- /dev/null +++ b/licenses/minipass.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) npm, Inc. and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/minizlib.txt b/licenses/minizlib.txt new file mode 100644 index 0000000..ffce738 --- /dev/null +++ b/licenses/minizlib.txt @@ -0,0 +1,26 @@ +Minizlib was created by Isaac Z. Schlueter. +It is a derivative work of the Node.js project. + +""" +Copyright Isaac Z. Schlueter and Contributors +Copyright Node.js contributors. All rights reserved. +Copyright Joyent, Inc. and other Node contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" diff --git a/licenses/mkdirp.txt b/licenses/mkdirp.txt new file mode 100644 index 0000000..13fcd15 --- /dev/null +++ b/licenses/mkdirp.txt @@ -0,0 +1,21 @@ +Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) + +This project is free software released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/licenses/object-inspect.txt b/licenses/object-inspect.txt new file mode 100644 index 0000000..ca64cc1 --- /dev/null +++ b/licenses/object-inspect.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/ocsp.txt b/licenses/ocsp.txt new file mode 100644 index 0000000..8aa2645 --- /dev/null +++ b/licenses/ocsp.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) [year] [fullname] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/once.txt b/licenses/once.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/once.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/pretty-bytes.txt b/licenses/pretty-bytes.txt new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/licenses/pretty-bytes.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/qs.txt b/licenses/qs.txt new file mode 100644 index 0000000..fecf6b6 --- /dev/null +++ b/licenses/qs.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/side-channel.txt b/licenses/side-channel.txt new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/licenses/side-channel.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/simple-lru-cache.txt b/licenses/simple-lru-cache.txt new file mode 100644 index 0000000..1b60e29 --- /dev/null +++ b/licenses/simple-lru-cache.txt @@ -0,0 +1,19 @@ +Copyright (c) 2013 Mercadolibre.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/licenses/tar.txt b/licenses/tar.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/tar.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/wrappy.txt b/licenses/wrappy.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/wrappy.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/licenses/yallist.txt b/licenses/yallist.txt new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/licenses/yallist.txt @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/loghighlight.js b/loghighlight.js new file mode 100644 index 0000000..a934a27 --- /dev/null +++ b/loghighlight.js @@ -0,0 +1,50 @@ +//SVR.JS LOG HIGHLIGHTER + +var readline = require("readline"); +var process = require("process"); + +var args = process.argv; +for (var i = (process.argv[0].indexOf("node") > -1 || process.argv[0].indexOf("bun") > -1 ? 2 : 1); i < args.length; i++) { + if (args[i] == "-h" || args[i] == "--help" || args[i] == "-?" || args[i] == "/h" || args[i] == "/?") { + console.log("SVR.JS log highlighter usage:"); + console.log(" | node loghighlight.js [-h] [--help] [-?] [/h] [/?]"); + console.log("-h -? /h /? --help -- Displays help"); + process.exit(0); + } else { + console.log("Unrecognized argument: " + args[i]); + console.log("SVR.JS log highlighter usage:"); + console.log(" | node loghighlight.js [-h] [--help] [-?] [/h] [/?]"); + console.log("-h -? /h /? --help -- Displays help"); + process.exit(1); + } +} + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: false, + prompt: '' +}); +rl.prompt(); +rl.on('line', (line) => { + viewLog([line]); +}); + +function viewLog(log) { + if(log[log.length-1] == "") log.pop(); + if(log[0] == "") log.shift(); + for(var i=0;i -1 || process.argv[0].indexOf("bun") > -1 ? 2 : 1); i < args.length; i++) { + if (args[i] == "-h" || args[i] == "--help" || args[i] == "-?" || args[i] == "/h" || args[i] == "/?") { + console.log("SVR.JS log viewer usage:"); + console.log("node logviewer.js [-h] [--help] [-?] [/h] [/?]"); + console.log("-h -? /h /? --help -- Displays help"); + process.exit(0); + } else { + console.log("Unrecognized argument: " + args[i]); + console.log("SVR.JS log viewer usage:"); + console.log("node logviewer.js [-h] [--help] [-?] [/h] [/?]"); + console.log("-h -? /h /? --help -- Displays help"); + process.exit(1); + } +} + +var logo = ["","",""," \u001b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&%"," &&\u001b[38;5;243m(((((\u001b[38;5;242m(\u001b[38;5;243m(((\u001b[38;5;241m##(###\u001b[38;5;243m(\u001b[38;5;241m##\u001b[38;5;243m((((((((((((((((((((((\u001b[38;5;143m*\u001b[38;5;243m(((\u001b[38;5;101m/\u001b[38;5;143m/\u001b[38;5;243m(((\u001b[38;5;185m*\u001b[38;5;243m((\u001b[38;5;242m(\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;243m((((((\u001b[38;5;242m(\u001b[38;5;243m(((((((\u001b[38;5;241m#\u001b[38;5;243m(((((((((((((((((((((((((\u001b[38;5;011m***\u001b[38;5;244m(\u001b[38;5;185m*\u001b[38;5;011m***\u001b[38;5;243m(\u001b[38;5;011m***\u001b[38;5;243m((\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&&&\u001b[38;5;243m((((((((((((((((((((((((((((((((((((((((((((((((((\u001b[38;5;002m&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&\u001b[38;5;243m((((((((((((((((((((((((((((((((((((((((((((((((((((\u001b[38;5;002m&&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;243m((((((\u001b[38;5;241m###\u001b[38;5;243m(((((\u001b[38;5;241m#\u001b[38;5;243m((\u001b[38;5;241m##\u001b[38;5;243m(((((((((((((((((((((\u001b[38;5;011m****\u001b[38;5;015m \u001b[38;5;243m(\u001b[38;5;011m***\u001b[38;5;243m((\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&&\u001b[38;5;243m((((((((((((((((((((((((((((((((((((((((((((((((((((\u001b[38;5;002m&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&%\u001b[38;5;243m((((((((((((((((((((((((((((((((((((((((((((((((\u001b[38;5;065m#\u001b[38;5;002m&&&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;243m((((((\u001b[38;5;242m(\u001b[38;5;243m(((((((\u001b[38;5;241m(\u001b[38;5;243m((((\u001b[38;5;242m(\u001b[38;5;243m((((((((((((((((((((\u001b[38;5;015m \u001b[38;5;143m/\u001b[38;5;187m.\u001b[38;5;015m \u001b[38;5;243m(\u001b[38;5;015m \u001b[38;5;243m((\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&&\u001b[38;5;243m(((((\u001b[38;5;242m(\u001b[38;5;243m(((((((\u001b[38;5;241m#\u001b[38;5;243m(((((((((((((((((((((((((((((((((((((((\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&&&&\u001b[38;5;010m########################################\u001b[38;5;071m#\u001b[38;5;002m&&&&&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&\u001b[38;5;010m##############################################\u001b[38;5;002m&&&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&\u001b[38;5;010m##################################################\u001b[38;5;002m&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&\u001b[38;5;010m####\u001b[38;5;016m@@@@@@\u001b[38;5;010m#\u001b[38;5;016m@@\u001b[38;5;010m####\u001b[38;5;016m@@\u001b[38;5;040m#\u001b[38;5;010m#\u001b[38;5;016m@@@@@@@\u001b[38;5;010m###########\u001b[38;5;016m@@\u001b[38;5;010m##\u001b[38;5;016m@@@@@@\u001b[38;5;010m###\u001b[38;5;002m&&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;083m/\u001b[38;5;010m###\u001b[38;5;016m@@\u001b[38;5;010m#######\u001b[38;5;016m@@\u001b[38;5;010m###\u001b[38;5;016m@\u001b[38;5;233m@\u001b[38;5;010m##\u001b[38;5;016m@@\u001b[38;5;010m####\u001b[38;5;016m@@\u001b[38;5;010m##########\u001b[38;5;016m@@\u001b[38;5;010m#\u001b[38;5;016m@@\u001b[38;5;010m#########\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;010m#######\u001b[38;5;022m@\u001b[38;5;016m@@@@\u001b[38;5;010m##\u001b[38;5;016m@@\u001b[38;5;010m#\u001b[38;5;016m@@\u001b[38;5;010m###\u001b[38;5;016m@@@@@@@\u001b[38;5;010m#######\u001b[38;5;016m@\u001b[38;5;010m###\u001b[38;5;016m@@\u001b[38;5;010m####\u001b[38;5;040m#\u001b[38;5;016m@@@@\u001b[38;5;010m###\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&\u001b[38;5;114m*\u001b[38;5;010m###\u001b[38;5;016m@@\u001b[38;5;010m###\u001b[38;5;002m&\u001b[38;5;016m@@\u001b[38;5;010m###\u001b[38;5;016m@@@\u001b[38;5;010m####\u001b[38;5;016m@@\u001b[38;5;010m####\u001b[38;5;016m@@\u001b[38;5;010m##\u001b[38;5;016m@@\u001b[38;5;010m#\u001b[38;5;034m%\u001b[38;5;010m#\u001b[38;5;016m@@@@\u001b[38;5;010m##\u001b[38;5;016m@@\u001b[38;5;034m%\u001b[38;5;010m###\u001b[38;5;016m@@\u001b[38;5;010m###\u001b[38;5;002m&&"," \u001b[38;5;m&\u001b[38;5;002m&&\u001b[38;5;010m####################################################\u001b[38;5;002m&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&\u001b[38;5;010m##################################################\u001b[38;5;002m&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&\u001b[38;5;010m##############################################\u001b[38;5;002m&&&&&&"," \u001b[38;5;m&\u001b[38;5;002m&&&&&&&&\u001b[38;5;010m########################################\u001b[38;5;002m&&&&&&&&&"," \u001b[38;5;m#\u001b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"," \u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///"," ////\u001b[38;5;247m*\u001b[38;5;246m///"," \u001b[38;5;208m////////"," \u001b[38;5;m&\u001b[38;5;208m(((((/(((("," \u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;208m/(/(((/(((/\u001b[38;5;137m/\u001b[38;5;246m//\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///\u001b[38;5;247m*\u001b[38;5;246m///"," //\u001b[38;5;247m*\u001b[38;5;246m///////\u001b[38;5;247m*\u001b[38;5;246m///////\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;208m/(((((/((((\u001b[38;5;137m/\u001b[38;5;246m//\u001b[38;5;247m*\u001b[38;5;246m///////\u001b[38;5;247m*\u001b[38;5;246m///////\u001b[38;5;247m*"," *\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;208m(/(/(/(/(/\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*\u001b[38;5;246m/\u001b[38;5;247m*"," \u001b[38;5;208m((((/(((","","","","\u001b[0m"]; + +for(var i=0;i ' +}); +console.log("Options:"); +for(var i=0;i { + var op = line.trim(); + if(op == "") { + rl.prompt(); + return; + } + var opn = parseInt(op); + rl.close(); + if(options[op]) { + options[op].callback(); + } else { + console.log("Invalid option."); + prompt(options); + } +}); +} + + +function viewLog(log) { + if(log[log.length-1] == "") log.pop(); + if(log[0] == "") log.shift(); + for(var i=0;i ' +}); +console.log("Input filter:"); +rl2.prompt(); +rl2.on('line', (line) => { + rl2.close(); + viewFilteredWorkerLogs(line); +}); +} + +var mainOptions = [ + {name: "View latest master log", callback: viewMasterLogs}, + {name: "View 5 latest worker logs", callback: viewWorkerLogs}, + {name: "View filtered worker logs (latest 20 logs)", callback: viewFilteredWorkerLogsPrompt}, + {name: "Exit log viewer", callback: function(){console.log("Bye!");process.exit(0);}} +] + +prompt(mainOptions); diff --git a/mods/primitiveanalytics.tar.gz b/mods/primitiveanalytics.tar.gz new file mode 100644 index 0000000..af6c34f Binary files /dev/null and b/mods/primitiveanalytics.tar.gz differ diff --git a/powered.png b/powered.png new file mode 100644 index 0000000..56a8049 Binary files /dev/null and b/powered.png differ diff --git a/serverSideScript.js b/serverSideScript.js new file mode 100644 index 0000000..747a3c8 --- /dev/null +++ b/serverSideScript.js @@ -0,0 +1,90 @@ +//Server-side Javascript (Node.js) +//This implementation uses Node.js, which powers SVR.JS. +//This implementation contains elements specific for SVR.JS mods: +// req - A server request instance +// res - A server response instance +// serverconsole - A console output object for SVR.JS +// responseEnd - Response ending method of SVR.JS +// href - Request URL without query +// ext - File extension of requested file +// uobject - Request URL object +// search - Request URL queries +// defaultPage - An index page location (deprecated, always returns 'index.json') +// users - A list of users (deprecated) +// page404 - 404 Not Found page location +// head - A head of server response +// foot - A foot of server response +// fd - A response body used by responseEnd method +// elseCallback - Method summoning SVR.JS internal callbacks +// callServerError - Method to end with server error +// getCustomHeaders - Method to get headers defined in config.json file +// origHref - Original request URL without query (before URL rewriting) +// redirect - Method to redirect. +// parsePostData - Method to parse POST data. +//Along with elements added by this implementation: +// disableEndElseCallbackExecute - Determines execution of elseCallback on end +// filterHeaders - Removes invalid HTTP/1.0 headers +// customvar1, customvar2, customvar3, customvar4 - Custom variables +//Built-in libraries: +// http +// https +// readline +// os +// url +// hexstrbase64 +// fs +// path +// crypto +// stream +//If you send response remember and don't use disableEndElseCallbackExecute, use "return;", or else SVR.JS will crash. +//If you use proxy, use filterHeaders to remove HTTP/2.0 headers, which are invalid in HTTP/1.0. +//If you type no code, elseCallback is executed. +//Below we have example script, which serves dynamic content. +disableEndElseCallbackExecute = true; //Avoid crashing on async. +var headers = getCustomHeaders(); //Headers +if(!fs.existsSync(__dirname + "/../temp/requestCounter")) { + fs.writeFileSync(__dirname + "/../temp/requestCounter","0"); //Reset counter +} +headers["Content-Type"] = 'text/html; charset=utf-8' //HTML output +if(href == "/hello.svr") { + fs.readFile(__dirname + "/../temp/requestCounter", (err,data) => { + if(err) throw err; + var requestCounter = parseInt(data.toString()); //Counter + fs.writeFile(__dirname + "/../temp/requestCounter",(requestCounter + 1).toString(),() => { + //Increase value of counter + }); + res.writeHead(200, "OK", headers); //Write Head + res.end("SVR.JS ServerSide Test

Hello World!

This is a test from server-side JavaScript. This test is executed " + requestCounter.toString() + " times from taking server up." + (req.headers.origin == undefined ? "" : " This request is done from a proxy.") + "

SVR.JS/" + configJSON.version + ' (' + os.platform()[0].toUpperCase() + os.platform().slice(1) + ')' + (req.headers.host == undefined ? "" : " on " + req.headers.host) + "

"); //Write response + serverconsole.resmessage("Client successfully recieved content."); //Log into SVR.JS + return; //Prevent SVR.JS from crashing + }); +} else if(href == "/proxy.svr") { + callServerError(403,"SVR.JS-exampleproxy"); //Server error + serverconsole.errmessage("Client fails to recieve content."); //Log into SVR.JS +} else if(href.indexOf("/proxy.svr/") == 0) { + var hdrs = req.headers; + hdrs["Host"] = (href.split("/")[2] == "this" ? req.headers.host : href.split("/")[2]); + hdrs["Origin"] = (req.headers.host == undefined ? "" : req.headers.host); + var options = { + hostname: (href.split("/")[2] == "this" ? req.headers.host.split(":")[0] : href.split("/")[2].split(":")[0]), + port: (href.split("/")[2] == "this" ? req.headers.host.split(":")[1] : (href.split("/")[2].split(":")[1] == undefined ? 80 : href.split("/")[2].split(":")[1])), + path: req.url.replace("/proxy.svr/" + href.split("/")[2],""), + method: req.method, + headers: filterHeaders(hdrs) + }; + var proxy = http.request(options, function (sres) { + res.writeHead(sres.statusCode, sres.headers) + sres.pipe(res, { + end: true + }); + }); + proxy.on("error",(ex) => { + callServerError(500,"SVR.JS-exampleproxy",ex.stack); //Server error + serverconsole.errmessage("Client fails to recieve content."); //Log into SVR.JS + }); + req.pipe(proxy, { + end: true + }); +} else { + elseCallback(); //Load SVR.JS internal callbacks +} diff --git a/svr.js b/svr.js new file mode 100644 index 0000000..0223eaf --- /dev/null +++ b/svr.js @@ -0,0 +1,4828 @@ +//DorianTech HTTP Server +//Uses Content-Type and Content-Length +//Events calling: +//| +//+--request +//| +//+--connect +//| +//+--error +// +//APIs: +// - https +// - readline +// - os +// - http +// - url +// - fs +// - path +// - hexstrbase64 +// - crypto +// - svrmodpack +// - graceful-fs +// - formidable +if (typeof require === "undefined") { + if (typeof ActiveXObject !== "undefined" && typeof WScript !== "undefined") { + var shell = new ActiveXObject("WScript.Shell"); + shell.Popup("SVR.JS doesn't work on Windows Script Host. SVR.JS requires use of Node.JS (or compatible JS runtime).", undefined, "Can't start SVR.JS", 16); + WScript.quit(); + } else { + if (typeof alert !== "undefined" && typeof document !== "undefined") { + alert("SVR.JS doesn't work on web browser. SVR.JS requires use of Node.JS (or compatible JS runtime)."); + } + if (typeof document !== "undefined") { + throw new Error("SVR.JS doesn't work on web browser. SVR.JS requires use of Node.JS (or compatible JS runtime)."); + } else { + throw new Error("SVR.JS doesn't work on Deno/QuickJS. SVR.JS requires use of Node.JS (or compatible JS runtime)."); + } + } +} +var secure = false; +var disableMods = false; +var logo = ["", "", "", " \x1b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " &&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&\x1b[38;5;243m((((((\x1b[38;5;241m###########\x1b[38;5;243m(((((((((((((((((((((((\x1b[38;5;011m***\x1b[38;5;243m(\x1b[38;5;011m***\x1b[38;5;243m(\x1b[38;5;011m***\x1b[38;5;243m((\x1b[38;5;002m&&", " \x1b[38;5;002m&&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&\x1b[38;5;243m((((((\x1b[38;5;241m###########\x1b[38;5;243m(((((((((((((((((((((((\x1b[38;5;011m***\x1b[38;5;243m(\x1b[38;5;015m \x1b[38;5;243m(\x1b[38;5;011m***\x1b[38;5;243m((\x1b[38;5;002m&&", " \x1b[38;5;002m&&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&\x1b[38;5;243m((((((\x1b[38;5;241m###########\x1b[38;5;243m(((((((((((((((((((((((\x1b[38;5;015m \x1b[38;5;243m(\x1b[38;5;015m \x1b[38;5;243m(\x1b[38;5;015m \x1b[38;5;243m((\x1b[38;5;002m&&", " \x1b[38;5;002m&&&\x1b[38;5;243m(((((((((((((((((((((((((((((((((((((((((((((((((((\x1b[38;5;002m&&&", " \x1b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " \x1b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " \x1b[38;5;002m&&&&&&&&\x1b[38;5;010m#########################################\x1b[38;5;002m&&&&&&&&", " \x1b[38;5;002m&&&&&\x1b[38;5;010m###############################################\x1b[38;5;002m&&&&&", " \x1b[38;5;002m&&&\x1b[38;5;010m###################################################\x1b[38;5;002m&&&", " \x1b[38;5;002m&&\x1b[38;5;010m####\x1b[38;5;016m@@@@@@\x1b[38;5;010m#\x1b[38;5;016m@@@\x1b[38;5;010m###\x1b[38;5;016m@@@\x1b[38;5;010m#\x1b[38;5;016m@@@@@@@\x1b[38;5;010m###########\x1b[38;5;016m@@\x1b[38;5;010m##\x1b[38;5;016m@@@@@@\x1b[38;5;010m####\x1b[38;5;002m&&", " \x1b[38;5;002m&&\x1b[38;5;010m###\x1b[38;5;016m@@\x1b[38;5;010m#######\x1b[38;5;016m@@\x1b[38;5;010m###\x1b[38;5;016m@@\x1b[38;5;010m##\x1b[38;5;016m@@\x1b[38;5;010m####\x1b[38;5;016m@@\x1b[38;5;010m##########\x1b[38;5;016m@@\x1b[38;5;010m#\x1b[38;5;016m@@\x1b[38;5;010m#########\x1b[38;5;002m&&", " \x1b[38;5;002m&&\x1b[38;5;010m######\x1b[38;5;040m#\x1b[38;5;016m@@@@\x1b[38;5;010m##\x1b[38;5;016m@@\x1b[38;5;010m#\x1b[38;5;016m@@\x1b[38;5;010m###\x1b[38;5;016m@@@@@@@\x1b[38;5;010m#######\x1b[38;5;016m@@\x1b[38;5;010m##\x1b[38;5;016m@@\x1b[38;5;010m####\x1b[38;5;040m#\x1b[38;5;016m@@@@\x1b[38;5;010m###\x1b[38;5;002m&&", " \x1b[38;5;002m&&\x1b[38;5;010m###\x1b[38;5;016m@@\x1b[38;5;034m%\x1b[38;5;010m###\x1b[38;5;016m@@\x1b[38;5;010m###\x1b[38;5;016m@@@\x1b[38;5;010m####\x1b[38;5;016m@@\x1b[38;5;010m####\x1b[38;5;016m@@\x1b[38;5;010m##\x1b[38;5;016m@@\x1b[38;5;010m###\x1b[38;5;016m@@@@\x1b[38;5;010m##\x1b[38;5;016m@@\x1b[38;5;034m%\x1b[38;5;010m###\x1b[38;5;016m@@\x1b[38;5;010m###\x1b[38;5;002m&&", " \x1b[38;5;002m&&\x1b[38;5;010m#####################################################\x1b[38;5;002m&&", " \x1b[38;5;002m&&&\x1b[38;5;010m###################################################\x1b[38;5;002m&&&", " \x1b[38;5;002m&&&&&\x1b[38;5;010m###############################################\x1b[38;5;002m&&&&&", " \x1b[38;5;002m&&&&&&&&\x1b[38;5;010m#########################################\x1b[38;5;002m&&&&&&&&", " \x1b[38;5;002m&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&", " \x1b[38;5;246m///////", " ///////", " \x1b[38;5;208m((((/))))", " \x1b[38;5;208m(((((/)))))", " \x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m/\x1b[38;5;208m(((((/)))))\x1b[38;5;246m//\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m///\x1b[38;5;247m*\x1b[38;5;246m/", " //\x1b[38;5;247m*\x1b[38;5;246m///////\x1b[38;5;247m*\x1b[38;5;246m///////\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m/\x1b[38;5;208m(((((/)))))\x1b[38;5;246m//\x1b[38;5;247m*\x1b[38;5;246m///////\x1b[38;5;247m*\x1b[38;5;246m///////\x1b[38;5;247m*\x1b[38;5;246m//", " *\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;208m(((((/)))))\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*\x1b[38;5;246m/\x1b[38;5;247m*", " \x1b[38;5;208m((((/))))", "", "", "", "\x1b[0m"]; + +var fs = require("fs"); + +function factoryReset() { + console.log("Removing logs..."); + deleteFolderRecursive(__dirname + "/log"); + fs.mkdirSync(__dirname + "/log"); + console.log("Removing temp folder..."); + deleteFolderRecursive(__dirname + "/temp"); + fs.mkdirSync(__dirname + "/temp"); + console.log("Removing configuration file..."); + fs.unlinkSync("config.json"); + console.log("Done!"); + process.exit(0); +} + +function deleteFolderRecursive(path) { + if (fs.existsSync(path)) { + fs.readdirSync(path).forEach(function (file) { + var curPath = path + "/" + file; + if (fs.statSync(curPath).isDirectory()) { // recurse + deleteFolderRecursive(curPath); + } else { // delete file + fs.unlinkSync(curPath); + } + }); + fs.rmdirSync(path); + } +} + +var os = require("os"); +var version = "3.4.17"; +var singlethreaded = false; + +if (process.versions) process.versions.svrjs = version; //Inject SVR.JS into process.versions + +var args = process.argv; +for (var i = (process.argv[0].indexOf("node") > -1 || process.argv[0].indexOf("bun") > -1 ? 2 : 1); i < args.length; i++) { + if (args[i] == "-h" || args[i] == "--help" || args[i] == "-?" || args[i] == "/h" || args[i] == "/?") { + console.log("SVR.JS usage:"); + console.log("node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]"); + console.log("-h -? /h /? --help -- Displays help"); + console.log("--clean -- Cleans files, that SVR.JS created"); + console.log("--reset -- Resets SVR.JS to factory settings (WARNING: DANGEROUS)"); + console.log("--secure -- Runs HTTPS server"); + console.log("--disable-mods -- Disables mods (safe mode)"); + console.log("--single-threaded -- Run single-threaded"); + console.log("-v --version -- Display server version"); + process.exit(0); + } else if (args[i] == "--secure") { + secure = true; + } else if (args[i] == "-v" || args[i] == "--version") { + console.log("SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")"); + process.exit(0); + } else if (args[i] == "--clean") { + console.log("Removing logs..."); + deleteFolderRecursive(__dirname + "/log"); + fs.mkdirSync(__dirname + "/log"); + console.log("Removing temp folder..."); + deleteFolderRecursive(__dirname + "/temp"); + fs.mkdirSync(__dirname + "/temp"); + console.log("Done!"); + process.exit(0); + } else if (args[i] == "--reset") { + factoryReset(); + } else if (args[i] == "--disable-mods") { + disableMods = true; + } else if (args[i] == "--single-threaded") { + singlethreaded = true; + } else { + console.log("Unrecognized argument: " + args[i]); + console.log("SVR.JS usage:"); + console.log("node svr.js [-h] [--help] [-?] [/h] [/?] [--secure] [--reset] [--clean] [--disable-mods] [--single-threaded] [-v] [--version]"); + console.log("-h -? /h /? --help -- Displays help"); + console.log("--clean -- Cleans files, that SVR.JS created"); + console.log("--reset -- Resets SVR.JS to factory settings (WARNING: DANGEROUS)"); + console.log("--secure -- Runs HTTPS server"); + console.log("--disable-mods -- Disables mods (safe mode)"); + console.log("--single-threaded -- Run single-threaded"); + console.log("-v --version -- Display server version"); + process.exit(1); + } +} + +var readline = require("readline"); +var net = require("net"); +var child_process = require("child_process"); +var cluster = {}; +if (!singlethreaded) { + try { + // Import cluster module + var cluster = require("cluster"); + } catch (ex) { + // Clustering is not supported! + } + + // Cluster & IPC shim for Bun + if (process.isBun && cluster.isMaster === undefined) { + cluster.isMaster = !process.env.NODE_UNIQUE_ID; + cluster.isWorker = !cluster.isMaster; + + if (cluster.isWorker) { + // Shim the cluster.worker object for worker processes + cluster.worker = { + id: parseInt(process.env.NODE_UNIQUE_ID), + process: process, + isDead: function () { + return false; + }, + send: function (message, b, c, d) { + process.send(message, b, c, d); + } + }; + + if (!process.send) { + // Shim the process.send function for worker processes + var net = require("net"); + var os = require("os"); + var path = require("path"); + + // Create a fake IPC server to receive messages + var fakeIPCServer = net.createServer(function (socket) { + var receivedData = ""; + + socket.on("data", function (data) { + receivedData += data.toString(); + }); + + socket.on("end", function () { + process.emit("message", receivedData); + }); + }).listen(os.platform() === "win32" ? path.join("\\\\?\\pipe", __dirname, "temp/.W" + process.pid + ".ipc") : (__dirname + "/temp/.W" + process.pid + ".ipc")); + + process.send = function (message) { + // Create a fake IPC connection to send messages + var fakeIPCConnection = net.createConnection(os.platform() === "win32" ? path.join("\\\\?\\pipe", __dirname, "temp/.P" + process.pid + ".ipc") : (__dirname + "/temp/.P" + process.pid + ".ipc"), function () { + fakeIPCConnection.end(message); + }); + }; + } + } + + // Custom implementation for cluster.fork() + cluster._workersCounter = 1; + cluster.workers = {}; + cluster.fork = function (env) { + var child_process = require("child_process"); + var newEnvironment = JSON.parse(JSON.stringify(env ? env : process.env)); + newEnvironment.NODE_UNIQUE_ID = cluster._workersCounter; + var newArguments = JSON.parse(JSON.stringify(process.argv)); + var command = newArguments.shift(); + var newWorker = child_process.spawn(command, newArguments, { + env: newEnvironment, + stdio: ["inherit", "inherit", "inherit", "ipc"] + }); + + newWorker.process = newWorker; + newWorker.isDead = function () { + return newWorker.exitCode !== null || newWorker.killed; + }; + newWorker.id = newEnvironment.NODE_UNIQUE_ID; + + function checkSendImplementation(worker) { + var sendImplemented = true; + + if (!worker.send) { + sendImplemented = false; + } + + try { + eval("'use strict';(" + String(worker.send).replace(/console\.log *\( *(["'])ChildProcess\.prototype\.send\(\) - Sorry! Not implemented yet\1 *\) *;?/, "throw new Error(\"NOT IMPLEMENTED\"); //") + ")(undefined)"); + } catch (ex) { + if (ex.message === "NOT IMPLEMENTED") { + sendImplemented = false; + } + } + + return sendImplemented; + } + + if (!checkSendImplementation(newWorker)) { + // Create a fake IPC server for worker process to receive messages + var fakeWorkerIPCServer = net.createServer(function (socket) { + var receivedData = ""; + + socket.on("data", function (data) { + receivedData += data.toString(); + }); + + socket.on("end", function () { + newWorker.emit("message", receivedData); + }); + }).listen(os.platform() === "win32" ? path.join("\\\\?\\pipe", __dirname, "temp/.P" + newWorker.process.pid + ".ipc") : (__dirname + "/temp/.P" + newWorker.process.pid + ".ipc")); + + // Cleanup when worker process exits + newWorker.on("exit", function () { + fakeWorkerIPCServer.close(); + delete cluster.workers[newWorker.id]; + }); + + newWorker.send = function (message, fakeParam2, fakeParam3, fakeParam4, tries) { + if (!tries) tries = 0; + + try { + // Create a fake IPC connection to send messages to worker process + var fakeWorkerIPCConnection = net.createConnection(os.platform() === "win32" ? path.join("\\\\?\\pipe", __dirname, "temp/.W" + newWorker.process.pid + ".ipc") : (__dirname + "/temp/.W" + newWorker.process.pid + ".ipc"), function () { + fakeWorkerIPCConnection.end(message); + }); + } catch (ex) { + if (tries > 25) throw ex; + + setTimeout(function () { + newWorker.send(message, undefined, undefined, tries + 1); + }, 10); + } + }; + } + + cluster.workers[newWorker.id] = newWorker; + cluster._workersCounter++; + return newWorker; + }; + } +} + +var bruteForceDb = {}; + +var SVRJSInitialized = false; +var exiting = false; +var crashed = false; + +function SVRJSFork() { + //Log + if (SVRJSInitialized) serverconsole.locmessage("Starting next thread, because previous one hung up/crashed..."); + //Fork new worker + var newWorker = cluster.fork(); + newWorker.on("error", function (err) { + serverconsole.locwarnmessage("There was a problem when handling SVR.JS worker! (from master process side) Reason: " + err.message); + }); + newWorker.on("exit", function () { + if (!exiting && Object.keys(cluster.workers).length == 0) { + crashed = true; + SVRJSFork(); + } + }); + newWorker.on("message", bruteForceListenerWrapper(newWorker)); + newWorker.on("message", listenConnListener); +} +var http = require("http"); +http.STATUS_CODES[497] = "HTTP Request Sent to HTTPS Port"; +http.STATUS_CODES[598] = "Network Read Timeout Error"; +http.STATUS_CODES[599] = "Network Connect Timeout Error"; +var url = require("url"); +if (url.URL && typeof URL == "undefined") URL = url.URL; +try { + var gracefulFs = require("graceful-fs"); + if (!process.isBun) gracefulFs.gracefulify(fs); //Bun + graceful-fs + SVR.JS + requests about static content = 500 Internal Server Error! +} catch (ex) { + //Don't use graceful-fs +} +var path = require("path"); +var hexstrbase64 = undefined; +try { + hexstrbase64 = require("./hexstrbase64/index.js"); +} catch (ex) { + //Don't use hexstrbase64 +} +var svrmodpack = undefined; +try { + svrmodpack = require("svrmodpack"); +} catch (ex) { + svrmodpack = { + _errored: ex + }; +} +var zlib = require("zlib"); +var tar = undefined; +try { + tar = require("tar"); +} catch (ex) { + tar = { + _errored: ex + }; +} +var formidable = undefined; +try { + formidable = require("formidable"); +} catch (ex) { + formidable = { + _errored: ex + }; +} +var ocsp = undefined; +var ocspCache = undefined; +try { + ocsp = require("ocsp"); + ocspCache = new ocsp.Cache(); +} catch (ex) { + ocsp = { + _errored: ex + }; +} +var prettyBytes = undefined; +try { + prettyBytes = require("pretty-bytes"); +} catch (ex) { + prettyBytes = { + _errored: ex + }; +} +var http2 = {}; +try { + http2 = require("http2"); + if (process.isBun) { + try { + http2.Http2ServerRequest(); + } catch (ex) { + if (ex.name == "NotImplementedError" || ex.code == "ERR_NOT_IMPLEMENTED") throw ex; + } + } +} catch (ex) { + http2.__disabled__ = null; + http2.createServer = function () { + throw new Error("HTTP/2 support not present"); + }; + http2.createSecureServer = function () { + throw new Error("HTTP/2 support not present"); + }; + http2.connect = function () { + throw new Error("HTTP/2 support not present"); + }; + http2.get = function () { + throw new Error("HTTP/2 support not present"); + }; +} +var crypto = {}; +var https = {}; +try { + crypto = require("crypto"); + https = require("https"); +} catch (ex) { + crypto = {}; + https = {}; + crypto.__disabled__ = null; + https.createServer = function () { + throw new Error("Crypto support not present"); + }; + http2.createSecureServer = function () { + throw new Error("Crypto support not present"); + }; + https.connect = function () { + throw new Error("Crypto support not present"); + }; + https.get = function () { + throw new Error("Crypto support not present"); + }; +} +var mime = require("mime-types"); +var pubip = ""; +var pubport = 80; +var port = 80; +var domain = ""; +var spubport = 443; +var sport = 443; +var mods = []; + +if (!fs.existsSync(__dirname + "/log")) fs.mkdirSync(__dirname + "/log"); +if (!fs.existsSync(__dirname + "/mods")) fs.mkdirSync(__dirname + "/mods"); +if (!fs.existsSync(__dirname + "/temp")) fs.mkdirSync(__dirname + "/temp"); + +var modFiles = fs.readdirSync(__dirname + "/mods").sort(); +var modInfos = []; + +function sizify(x) { + try { + if (prettyBytes._errored) throw prettyBytes._errored; + return prettyBytes(parseInt(x), { + minimumFractionDigits: 0, + maximumFractionDigits: 2 + }).replace(/ /g, "").replace(/B/ig, "").replace(/k/g, "K"); + } catch (ex) { + if (x < 1000) return x.toString(); + if (x < 10000) return (Math.round(x / 10) / 100).toString() + "K"; + if (x < 100000) return (Math.round(x / 100) / 10).toString() + "K"; + if (x < 1000000) return (Math.round(x / 1000)).toString() + "K"; + if (x < 10000000) return (Math.round(x / 10000) / 100).toString() + "M"; + if (x < 100000000) return (Math.round(x / 100000) / 10).toString() + "M"; + if (x < 1000000000) return (Math.round(x / 1000000)).toString() + "M"; + if (x < 10000000000) return (Math.round(x / 10000000) / 100).toString() + "G"; + if (x < 100000000000) return (Math.round(x / 100000000) / 10).toString() + "G"; + if (x < 1000000000000) return (Math.round(x / 1000000000)).toString() + "G"; + if (x < 10000000000000) return (Math.round(x / 10000000000) / 100).toString() + "T"; + if (x < 100000000000000) return (Math.round(x / 100000000000) / 10).toString() + "T"; + if (x < 1000000000000000) return (Math.round(x / 1000000000000)).toString() + "T"; + if (x < 10000000000000000) return (Math.round(x / 10000000000000) / 100).toString() + "P"; + if (x < 100000000000000000) return (Math.round(x / 100000000000000) / 10).toString() + "P"; + return (Math.round(x / 1000000000000000)).toString() + "P"; + } +} + +function getOS() { + var osType = os.type(); + var platform = os.platform(); + if (platform == "android") { + return "Android"; + } else if (osType == "Windows_NT" || osType == "WindowsNT") { + var arch = os.arch(); + if (arch == "ia32") { + return "Win32"; + } else if (arch == "x64") { + return "Win64"; + } else { + return "Win" + arch.toUpperCase(); + } + } else if (osType.indexOf("CYGWIN") == 0) { + return "Cygwin"; + } else if (osType.indexOf("MINGW") == 0) { + return "MinGW"; + } else if (osType.indexOf("MSYS") == 0) { + return "MSYS"; + } else if (osType.indexOf("UWIN") == 0) { + return "UWIN"; + } else if (osType == "GNU") { + return "GNU Hurd"; + } else { + return osType; + } +} + +function createRegex(regex) { + var regexObj = regex.split("/"); + if (regexObj.length == 0) throw new Error("Invalid regex!"); + var modifiers = regexObj.pop(); + regexObj.shift(); + var searchString = regexObj.join("/"); + return new RegExp(searchString, modifiers); +} + +//IP Block list object +function ipBlockList(rawBlockList) { + function normalizeIPv4Address(address) { + return address.replace(/(^|\.)(?:0(?!\.|$))+/g, ""); + } + + function expandIPv6Address(address) { + var fullAddress = ""; + var expandedAddress = ""; + var validGroupCount = 8; + var validGroupSize = 4; + + var ipv4 = ""; + var extractIpv4 = /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/; + var validateIpv4 = /((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})/; + + if (validateIpv4.test(address)) { + groups = address.match(extractIpv4); + for (var i = 1; i < groups.length; i++) { + ipv4 += ("00" + (parseInt(groups[i], 10).toString(16))).slice(-2) + (i == 2 ? ":" : ""); + } + address = address.replace(extractIpv4, ipv4); + } + + if (address.indexOf("::") == -1) { + fullAddress = address; + } else { + var sides = address.split("::"); + var groupsPresent = 0; + for (var i = 0; i < sides.length; i++) { + groupsPresent += sides[i].split(":").length; + } + fullAddress += sides[0] + ":"; + for (var i = 0; i < validGroupCount - groupsPresent; i++) { + fullAddress += "0000:"; + } + fullAddress += sides[1]; + } + var groups = fullAddress.split(":"); + for (var i = 0; i < validGroupCount; i++) { + while (groups[i].length < validGroupSize) { + groups[i] = "0" + groups[i]; + } + expandedAddress += (i != validGroupCount - 1) ? groups[i] + ":" : groups[i]; + } + return expandedAddress; + } + + function ipv4ToInt(ip) { + var ips = ip.split("."); + return parseInt(ips[0]) * 16777216 + parseInt(ips[1]) * 65536 + parseInt(ips[2]) * 256 + parseInt(ips[3]); + } + + function getIPv4CIDRLimits(ip, cidrMask) { + var ipInt = ipv4ToInt(ip); + var exp = Math.pow(2, 32 - cidrMask); + var ipMin = Math.floor(ipInt / exp) * exp; + var ipMax = ipMin + exp - 1; + return { + min: ipMin, + max: ipMax + }; + } + + function ipv6ToBlocks(ip) { + var ips = ip.split(":"); + var ip2s = []; + for (var i = 0; i < ips.length; i++) { + ip2s.push(parseInt(ips[i])); + } + return ip2s; + } + + function getIPv6CIDRLimits(ip, cidrMask) { + var ipBlocks = ipv6ToBlocks(ip); + var fieldsToDelete = Math.floor((128 - cidrMask) / 16); + var fieldMaskModify = (128 - cidrMask) % 16; + var ipBlockMin = []; + var ipBlockMax = []; + for (var i = 0; i < 8; i++) { + ipBlockMin.push((i < 8 - fieldsToDelete) ? ((i < 7 - fieldsToDelete) ? ipBlocks[i] : (ipBlocks[i] >> fieldMaskModify << fieldMaskModify)) : 0); + } + for (var i = 0; i < 8; i++) { + ipBlockMax.push((i < 8 - fieldsToDelete) ? ((i < 7 - fieldsToDelete) ? ipBlocks[i] : ((ipBlocks[i] >> fieldMaskModify << fieldMaskModify) + Math.pow(2, fieldMaskModify) - 1)) : 65535); + } + return { + min: ipBlockMin, + max: ipBlockMax + }; + } + + function checkIfIPv4CIDRMatches(ipInt, cidrObject) { + if (cidrObject.v6) return false; + return ipInt >= cidrObject.min && ipInt <= cidrObject.max; + } + + function checkIfIPv6CIDRMatches(ipBlock, cidrObject) { + if (!cidrObject.v6) return false; + for (var i = 0; i < 8; i++) { + if (ipBlock[i] < cidrObject.min[i] || ipBlock[i] > cidrObject.max[i]) return true; + } + return false; + } + if (rawBlockList === undefined) rawBlockList = []; + var instance = {}; + instance.raw = []; + instance.rawtoPreparedMap = []; + instance.prepared = []; + instance.cidrs = []; + instance.add = function (rawValue) { + instance.raw.push(rawValue); + var beginIndex = instance.prepared.length; + var cidrIndex = instance.cidrs.length; + var cidrMask = null; + var isIPv6 = false; + if (rawValue.indexOf("/") > -1) { + var rwArray = rawValue.split("/"); + cidrMask = rwArray.pop(); + rawValue = rwArray.join("/"); + } + rawValue = rawValue.toLowerCase(); + if (rawValue.indexOf("::ffff:") == 0) rawValue = rawValue.substr(7); + if (rawValue.indexOf(":") > -1) { + isIPv6 = true; + rawValue = expandIPv6Address(rawValue); + } else { + rawValue = normalizeIPv4Address(rawValue); + } + if (cidrMask) { + var cidrLimits = {}; + if (isIPv6) { + cidrLimits = getIPv6CIDRLimits(rawValue, cidrMask); + cidrLimits.v6 = true; + } else { + cidrLimits = getIPv4CIDRLimits(rawValue, cidrMask); + cidrLimits.v6 = false; + } + instance.cidrs.push(cidrLimits); + instance.rawtoPreparedMap.push({ + cidr: true, + index: cidrIndex + }); + } else { + instance.prepared.push(rawValue); + instance.rawtoPreparedMap.push({ + cidr: false, + index: beginIndex + }); + } + }; + instance.remove = function (ip) { + var index = instance.raw.indexOf(ip); + if (index == -1) return false; + var map = instance.rawtoPreparedMap[index]; + instance.raw.splice(index, 1); + instance.rawtoPreparedMap.splice(index, 1); + if (map.cidr) { + instance.cidrs.splice(map.index, 1); + } else { + instance.prepared.splice(map.index, 1); + } + return true; + }; + instance.check = function (rawValue) { + if (instance.raw.length == 0) return false; + var isIPv6 = false; + rawValue = rawValue.toLowerCase(); + if (rawValue == "localhost") rawValue = "127.0.0.1"; + if (rawValue.indexOf("::ffff:") == 0) rawValue = rawValue.substr(7); + if (rawValue.indexOf(":") > -1) { + isIPv6 = true; + rawValue = expandIPv6Address(rawValue); + } else { + rawValue = normalizeIPv4Address(rawValue); + } + if (instance.prepared.indexOf(rawValue) > -1) return true; + if (instance.cidrs.length == 0) return false; + var ipParsedObject = (!isIPv6 ? ipv4ToInt : ipv6ToBlocks)(rawValue); + var checkMethod = (!isIPv6 ? checkIfIPv4CIDRMatches : checkIfIPv6CIDRMatches); + for (var i = 0; i < instance.cidrs.length; i++) { + if (checkMethod(ipParsedObject, instance.cidrs[i])) return true; + } + return false; + }; + for (var i = 0; i < rawBlockList.length; i++) { + instance.add(rawBlockList[i]); + } + return instance; +} + +//Error stack generator from Error objects. +function generateErrorStack(ex) { + var errStack = ex.stack ? ex.stack.split("\n") : []; + for (var i = 0; i < errStack.length; i++) { + if (errStack[i].indexOf(ex.name) == 0) return ex.stack; + } + var nErrStack = [ex.name + (ex.code ? ": " + ex.code : "") + (ex.message == "" ? "" : ": " + ex.message)]; + for (var i = 0; i < errStack.length; i++) { + if (errStack[i] != "") { + var ef = errStack[i].split("@"); + var location = ""; + if (ef.length > 1) location = ef.pop(); + var func = ef.join("@"); + nErrStack.push(" at " + (func == "" ? (!location || location == "" ? "" : location) : (func + (!location || location == "" ? "" : " (" + location + ")")))); + } + } + return nErrStack.join("\n"); +} + +var ifaces = {}; +var ifaceEx = null; +try { + ifaces = os.networkInterfaces(); +} catch (ex) { + ifaceEx = ex; +} +var ips = []; +var attmts = 5; +var attmtsRedir = 5; +var errors = os.constants.errno; +var timestamp = new Date().getTime(); +var wwwredirect = false; +Object.keys(ifaces).forEach(function (ifname) { + var alias = 0; + ifaces[ifname].forEach(function (iface) { + if (iface.family !== "IPv4" || iface.internal !== false) { + return; + } + if (alias >= 1) { + ips.push(ifname + ":" + alias, iface.address); + } else { + ips.push(ifname, iface.address); + } + ++alias; + }); +}); +if (ips.length == 0) { + Object.keys(ifaces).forEach(function (ifname) { + var alias = 0; + ifaces[ifname].forEach(function (iface) { + if (iface.family !== "IPv6" || iface.internal !== false) { + return; + } + if (alias >= 1) { + ips.push(ifname + ":" + alias, iface.address); + } else { + ips.push(ifname, iface.address); + } + ++alias; + }); + }); +} +var host = ips[(ips.length) - 1]; +if (!host) host = "[offline]"; +var hp = host + ":" + port.toString(); + +var ipRequestCompleted = false; +var ipRequestGotError = false; +if (host != "[offline]" || ifaceEx) { + var ipRequest = (crypto.__disabled__ !== undefined ? http : https).get({ + host: "api64.ipify.org", + port: (crypto.__disabled__ !== undefined ? 80 : 443), + path: "/", + headers: { + "User-Agent": (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + }, + timeout: 5000 + }, function (res) { + ipRequest.removeAllListeners("timeout"); + res.on("data", function (d) { + if (res.statusCode != 200) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + return; + } + pubip = d.toString(); + if (!domain) { + if (pubip.indexOf(":") == -1) { + var parts = pubip.split("."); + var p1 = parseInt(parts[0]).toString(16); + var p2 = parseInt(parts[1]).toString(16); + var p3 = parseInt(parts[2]).toString(16); + var p4 = parseInt(parts[3]).toString(16); + var pp = parseInt(pubport).toString(16); + domain = p1 + p2 + p3 + p4 + pp + ".nodesvr.doriantech.com"; + } else { + domain = pubip.replace(/[^0-9a-zA-Z]/gi, "").toLowerCase() + ".nodesvrip6.doriantech.com"; + } + } + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + }); + }); + ipRequest.on("error", function () { + if (crypto.__disabled__ || ipRequestGotError) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + } else { + ipRequestGotError = true; + } + }); + ipRequest.on("timeout", function () { + if (crypto.__disabled__ || ipRequestGotError) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + } else { + ipRequestGotError = true; + } + }); + + if (!crypto.__disabled) { + var ipRequest2 = https.get({ + host: "api.seeip.org", + port: 443, + path: "/", + headers: { + "User-Agent": (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + }, + timeout: 5000 + }, function (res) { + ipRequest2.removeAllListeners("timeout"); + res.on("data", function (d) { + if (res.statusCode != 200) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + return; + } + pubip = d.toString(); + if (!domain) { + if (pubip.indexOf(":") == -1) { + var parts = pubip.split("."); + var p1 = parseInt(parts[0]).toString(16); + var p2 = parseInt(parts[1]).toString(16); + var p3 = parseInt(parts[2]).toString(16); + var p4 = parseInt(parts[3]).toString(16); + var pp = parseInt(pubport).toString(16); + domain = p1 + p2 + p3 + p4 + pp + ".nodesvr.doriantech.com"; + } else { + domain = pubip.replace(/[^0-9a-zA-Z]/gi, "").toLowerCase() + ".nodesvrip6.doriantech.com"; + } + } + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + }); + }); + ipRequest2.on("error", function () { + if (crypto.__disabled__ || ipRequestGotError) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + } else { + ipRequestGotError = true; + } + }); + ipRequest2.on("timeout", function () { + if (crypto.__disabled__ || ipRequestGotError) { + ipRequestCompleted = true; + process.emit("ipRequestCompleted"); + } else { + ipRequestGotError = true; + } + }); + } +} else { + ipRequestCompleted = true; +} + +function ipStatusCallback(callback) { + if (ipRequestCompleted) { + callback(); + } else { + process.once("ipRequestCompleted", callback); + } +} + +var configJSON = {}; +if (fs.existsSync(__dirname + "/config.json")) { + var configJSONf = ""; + try { + configJSONf = fs.readFileSync(__dirname + "/config.json"); //Read JSON File + } catch (ex) { + throw new Error("Cannot read JSON file."); + } + try { + configJSON = JSON.parse(configJSONf); //Parse JSON + } catch (ex) { + throw new Error("JSON Parse error."); + } +} + +var rawBlackList = []; +var users = []; +var page404 = "404.html"; +var serverAdmin = "[no contact information]"; +var stackHidden = false; +var exposeServerVersion = true; +var rewriteMap = []; +var allowStatus = true; +var dontCompress = []; +var enableIPSpoofing = false; +var sni = {}; +var disableNonEncryptedServer = false; +var disableToHTTPSRedirect = false; +var nonStandardCodesRaw = []; +if (configJSON.blacklist != undefined) rawBlackList = configJSON.blacklist; +if (configJSON.wwwredirect != undefined) wwwredirect = configJSON.wwwredirect; +if (configJSON.port != undefined) port = configJSON.port; +if (configJSON.pubport != undefined) pubport = configJSON.pubport; +if (configJSON.domian != undefined) domain = configJSON.domian; +if (configJSON.domain != undefined) domain = configJSON.domain; +if (configJSON.sport != undefined) sport = configJSON.sport; +if (configJSON.spubport != undefined) spubport = configJSON.spubport; +if (configJSON.page404 != undefined) page404 = configJSON.page404; +if (configJSON.serverAdministratorEmail != undefined) serverAdmin = configJSON.serverAdministratorEmail; +if (configJSON.nonStandardCodes != undefined) nonStandardCodesRaw = configJSON.nonStandardCodes; +if (configJSON.stackHidden != undefined) stackHidden = configJSON.stackHidden; +if (configJSON.users != undefined) users = configJSON.users; +if (configJSON.exposeServerVersion != undefined) exposeServerVersion = configJSON.exposeServerVersion; +if (configJSON.rewriteMap != undefined) rewriteMap = configJSON.rewriteMap; +if (configJSON.allowStatus != undefined) allowStatus = configJSON.allowStatus; +if (configJSON.dontCompress != undefined) dontCompress = configJSON.dontCompress; +if (configJSON.enableIPSpoofing != undefined) enableIPSpoofing = configJSON.enableIPSpoofing; +if (configJSON.secure != undefined) secure = secure || configJSON.secure; +if (configJSON.sni != undefined) sni = configJSON.sni; +if (configJSON.disableNonEncryptedServer != undefined) disableNonEncryptedServer = configJSON.disableNonEncryptedServer; +if (configJSON.disableToHTTPSRedirect != undefined) disableToHTTPSRedirect = configJSON.disableToHTTPSRedirect; +if (configJSON.wwwroot != undefined) { + var wwwroot = configJSON.wwwroot; + if (cluster.isMaster || cluster.isMaster === undefined) process.chdir(wwwroot); +} else { + if (cluster.isMaster || cluster.isMaster === undefined) process.chdir(__dirname); +} + +//Compability for older mods +configJSON.version = version; +configJSON.productName = "SVR.JS"; + +var blacklist = ipBlockList(rawBlackList); + +var nonStandardCodes = []; +for (var i = 0; i < nonStandardCodesRaw.length; i++) { + var nO = {}; + var nsKeys = Object.keys(nonStandardCodesRaw[i]); + for (var j = 0; j < nsKeys.length; j++) { + if (nsKeys[j] != "users") { + nO[nsKeys[j]] = nonStandardCodesRaw[i][nsKeys[j]]; + } else { + nO["users"] = ipBlockList(nonStandardCodesRaw[i].users); + } + } + nonStandardCodes.push(nO); +} + +var customHeaders = (configJSON.customHeaders == undefined ? {} : JSON.parse(JSON.stringify(configJSON.customHeaders))); +if (exposeServerVersion) { + customHeaders["Server"] = "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")"; +} else { + customHeaders["Server"] = "SVR.JS"; +} + +function getCustomHeaders() { + return JSON.parse(JSON.stringify(customHeaders)); +} + +var vnum = 0; +try { + vnum = process.config.variables.node_module_version; +} catch (ex) { + //Version number not retrieved +} +if (vnum === undefined) vnum = 0; +if (process.isBun) vnum = 59; +// NOTE: One of regexes used here is reported as vulnerable according to Devina ReDOS checker, but it's actually just FALSE POSITIVE. + +function sanitizeURL(resource) { + if (resource == "*") return "*"; + if (resource == "") return ""; + // Remove null characters + resource = resource.replace(/%00/ig, "").replace(/\0/g,""); + // Check if URL is malformed (e.g. %c0%af or %u002f or simply %as) + if (resource.match(/%(?:c[01]|f[ef]|(?![0-9a-f]{2}).{2}|.{0,1}$)/gi)) throw new URIError("URI malformed"); + // Decode URL-encoded characters while preserving certain characters + resource = resource.replace(/%([0-9a-f]{2})/gi, function (match, hex) { + var decodedChar = String.fromCharCode(parseInt(hex, 16)); + return /(?![;?:@&=+$,#%])[!-~]/.test(decodedChar) ? decodedChar : "%" + hex; + }); + var sanitizedResource = resource; + // Ensure the resource starts with a slash + if (resource[0] != "/") sanitizedResource = "/" + sanitizedResource; + // Convert backslashes to slashes and remove duplicate slashes + sanitizedResource = sanitizedResource.replace(/\\/g, "/").replace(/\/+/g, "/"); + // Handle relative navigation (e.g., "/./", "/../", "../", "./"), also remove trailing dots in paths + sanitizedResource = sanitizedResource.replace(/\/\.(?:\.{2,})?(?=($|\/))/g, "$1").replace(/([^.\/])\.+(?=($|\/))/g, "$1$2").replace(/\/+/g, "/"); + while (sanitizedResource.match(/\/(?!\.\.\/)[^\/]+\/\.\.(?=(\/|$))/g)) { + sanitizedResource = sanitizedResource.replace(/\/(?!\.\.\/)[^\/]+\/\.\.(?=(\/|$))/g, "$1").replace(/\/+/g, "/"); + } + sanitizedResource = sanitizedResource.replace(/\/\.\.(?=(\/|$))/g, "$1").replace(/\/+/g, "/"); + if (sanitizedResource.length == 0) return "/"; + else return sanitizedResource; +} + +var key = ""; +var cert = ""; + +if (secure) { + if (!configJSON.key) configJSON.key = "cert/key.key"; + if (!configJSON.cert) configJSON.cert = "cert/cert.crt"; +} else { + key = "SSL DISABLED"; + cert = "SSL DISABLED"; + configJSON.cert = "SSL DISABLED"; + configJSON.key = "SSL DISABLED"; +} + +if (!fs.existsSync(__dirname + "/config.json")) { + saveConfig(); +} + +if (secure) { + key = fs.readFileSync((configJSON.key[0] != "/" && !configJSON.key.match(/^[A-Z0-9]:\\/)) ? __dirname + "/" + configJSON.key : configJSON.key).toString(); + cert = fs.readFileSync((configJSON.cert[0] != "/" && !configJSON.cert.match(/^[A-Z0-9]:\\/)) ? __dirname + "/" + configJSON.cert : configJSON.cert).toString(); + var sniNames = Object.keys(sni); + var sniCredentials = []; + for (var i = 0; i < sniNames.length; i++) { + sniCredentials.push({ + name: sniNames[i], + cert: fs.readFileSync((sni[sniNames[i]].cert[0] != "/" && !sni[sniNames[i]].cert.match(/^[A-Z0-9]:\\/)) ? __dirname + "/" + sni[sniNames[i]].cert : sni[sniNames[i]].cert).toString(), + key: fs.readFileSync((sni[sniNames[i]].key[0] != "/" && !sni[sniNames[i]].key.match(/^[A-Z0-9]:\\/)) ? __dirname + "/" + sni[sniNames[i]].key : sni[sniNames[i]].key).toString() + }); + } +} + +var logFile = undefined; +var logSync = false; + +function LOG(s) { + try { + if (configJSON.enableLogging || configJSON.enableLogging == undefined) { + if (logSync) { + fs.appendFileSync(__dirname + "/log/" + (cluster.isMaster ? "master" : (cluster.isMaster === undefined ? "singlethread" : "worker")) + "-" + timestamp + ".log", "[" + new Date().toISOString() + "] " + s + "\r\n"); + } else { + if (!logFile) { + logFile = fs.createWriteStream(__dirname + "/log/" + (cluster.isMaster ? "master" : (cluster.isMaster === undefined ? "singlethread" : "worker")) + "-" + timestamp + ".log", { + flags: "a", + autoClose: false + }); + } + if (logFile.writable) { + logFile.write("[" + new Date().toISOString() + "] " + s + "\r\n"); + } else { + throw new Error("Log file stream is closed."); + } + } + } + } catch (ex) { + if (!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: /)) serverconsole.locwarnmessage("There was a problem while saving logs! Logs will not be kept in log file. Reason: " + ex.message); + } +} + +var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE: " + msg); + LOG("SERVER CLI MESSAGE: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE: " + msg); + LOG("SERVER MESSAGE: " + msg); + return; + } +}; + +//Wrap around process.exit, so log contents can flush. +process.unsafeExit = process.exit; +process.exit = function (code) { + if (logFile && logFile.writable && !logFile.pending) { + try { + logFile.close(function () { + logFile = undefined; + logSync = true; + process.unsafeExit(code); + if (process.isBun) { + setInterval(function () { + if (!logFile.writable) { + logFile = undefined + logSync = true; + process.unsafeExit(code); + } + }, 50); //Interval + } + }); + setTimeout(function () { + logFile = undefined; + logSync = true; + process.unsafeExit(code); + }, 10000); //timeout + } catch (ex) { + logFile = undefined; + logSync = true; + process.unsafeExit(code); + } + } else { + logSync = true; + process.unsafeExit(code); + } +}; + +if (!disableMods) { + var modloaderFolderName = "modloader"; + if (cluster.isMaster === false) { + modloaderFolderName = ".modloader_w" + Math.floor(Math.random() * 65536); + } + for (var i = 0; i < modFiles.length; i++) { + var modFile = __dirname + "/mods/" + modFiles[i]; + try { + try { + fs.mkdirSync(__dirname + "/temp/" + modloaderFolderName); + } catch (ex) { + if (ex.code != "EEXIST") { + fs.mkdirSync(__dirname + "/temp"); + try { + fs.mkdirSync(__dirname + "/temp/" + modloaderFolderName); + } catch (ex) { + if (ex.code != "EEXIST") throw ex; + } + } + } + fs.mkdirSync(__dirname + "/temp/" + modloaderFolderName + "/" + modFiles[i]); + } catch (ex) { + if (ex.code != "EEXIST" && ex.code != "ENOENT") throw ex; + //Some other SVR.JS process may have create files. + } + if (fs.statSync(modFile).isFile()) { + try { + function extract() { + if (modFile.indexOf(".tar.gz") == modFile.length - 7) { + if (tar._errored) throw tar._errored; + tar.x({ + file: modFile, + sync: true, + C: __dirname + "/temp/" + modloaderFolderName + "/" + modFiles[i] + }); + } else { + if (svrmodpack._errored) throw svrmodpack._errored; + svrmodpack.unpack(modFile, __dirname + "/temp/" + modloaderFolderName + "/" + modFiles[i]); + } + } + extract(); + var Mod = undefined; + var mod = undefined; + var modSloaded = false; + for (var j = 0; j < 3; j++) { + try { + Mod = require("./temp/" + modloaderFolderName + "/" + modFiles[i] + "/index.js"); + mod = new Mod(); + break; + } catch (ex) { + if (j >= 2 || ex.name == "SyntaxError") throw ex; + var now = Date.now(); + while (Date.now() - now < 2); + //Try reloading mod + } + } + mods.push(mod); + for (var j = 0; j < 3; j++) { + try { + modInfos.push(JSON.parse(fs.readFileSync(__dirname + "/temp/" + modloaderFolderName + "/" + modFiles[i] + "/mod.info"))); + break; + } catch (ex) { + if (j >= 2) { + modInfos.push({ + name: "Unknown mod (" + modFiles[i] + ";" + ex.message + ")", + version: "ERROR" + }); + } + //Try reloading mod info + } + } + } catch (ex) { + if (cluster.isMaster || cluster.isMaster === undefined) { + serverconsole.locwarnmessage("There was a problem while loading a \"" + modFiles[i] + "\" mod."); + serverconsole.locwarnmessage("Stack:"); + serverconsole.locwarnmessage(generateErrorStack(ex)); + } + } + } + } + if (fs.existsSync("./serverSideScript.js") && fs.statSync("./serverSideScript.js").isFile()) { + try { + var modhead = "var readline = require('readline');\r\nvar os = require('os');\r\nvar http = require('http');\r\nvar url = require('url');\r\nvar fs = require('fs');\r\nvar path = require('path');\r\n" + (hexstrbase64 === undefined ? "" : "var hexstrbase64 = require('../hexstrbase64/index.js');\r\n") + (crypto.__disabled__ === undefined ? "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) {\r\nreturn function () {\r\nvar disableEndElseCallbackExecute = false;\r\nfunction filterHeaders(headers){for(var jsn=JSON.stringify(headers,null,2).split('\\n'),njsn=[\"{\"],i=1;i= 7 || ex.name == "SyntaxError") throw ex; + var now = Date.now(); + while (Date.now() - now < 2); + //Try reloading mod + } + } + mods.push(amod); + } catch (ex) { + if (cluster.isMaster || cluster.isMaster === undefined) { + serverconsole.locwarnmessage("There was a problem while loading server side JavaScript."); + serverconsole.locwarnmessage("Stack:"); + serverconsole.locwarnmessage(generateErrorStack(ex)); + } + } + } +} + +function sha256(s) { + if (crypto.__disabled__ === undefined) { + var hash = crypto.createHash("SHA256"); + hash.update(s); + return hash.digest("hex"); + } else { + + var chrsz = 8; + var hexcase = 0; + + function safeAdd(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + } + + function S(X, n) { + return (X >>> n) | (X << (32 - n)); + } + + function R(X, n) { + return (X >>> n); + } + + function Ch(x, y, z) { + return ((x & y) ^ ((~x) & z)); + } + + function Maj(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); + } + + function Sigma0256(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); + } + + function Sigma1256(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); + } + + function Gamma0256(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); + } + + function Gamma1256(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); + } + + function coreSha256(m, l) { + var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + a = HASH[0]; + b = HASH[1]; + c = HASH[2]; + d = HASH[3]; + e = HASH[4]; + f = HASH[5]; + g = HASH[6]; + h = HASH[7]; + + for (var j = 0; j < 64; j++) { + if (j < 16) W[j] = m[j + i]; + else W[j] = safeAdd(safeAdd(safeAdd(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + + T1 = safeAdd(safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); + T2 = safeAdd(Sigma0256(a), Maj(a, b, c)); + + h = g; + g = f; + f = e; + e = safeAdd(d, T1); + d = c; + c = b; + b = a; + a = safeAdd(T1, T2); + } + + HASH[0] = safeAdd(a, HASH[0]); + HASH[1] = safeAdd(b, HASH[1]); + HASH[2] = safeAdd(c, HASH[2]); + HASH[3] = safeAdd(d, HASH[3]); + HASH[4] = safeAdd(e, HASH[4]); + HASH[5] = safeAdd(f, HASH[5]); + HASH[6] = safeAdd(g, HASH[6]); + HASH[7] = safeAdd(h, HASH[7]); + } + return HASH; + } + + function str2binb(str) { + var bin = Array(); + var mask = (1 << chrsz) - 1; + for (var i = 0; i < str.length * chrsz; i += chrsz) { + bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32); + } + return bin; + } + + function Utf8Encode(string) { + string = string.replace(/\r\n/g, "\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; + } + + function binb2hex(binarray) { + var hexTab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for (var i = 0; i < binarray.length * 4; i++) { + str += hexTab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + + hexTab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF); + } + return str; + } + + s = Utf8Encode(s); + return binb2hex(coreSha256(str2binb(s), s.length * chrsz)); + } +} + +function getInitializePath(to) { + var cwd = process.cwd(); + if (os.platform() == "win32") { + to = to.replace(/\//g, "\\"); + if (to[0] == "\\") to = cwd.split("\\")[0] + to; + } + var absoluteTo = path.isAbsolute(to) ? to : (__dirname + (os.platform() == "win32" ? "\\" : "/") + to); + if (os.platform() == "win32" && cwd[0] != absoluteTo[0]) return ""; + var relative = path.relative(cwd, absoluteTo); + if (os.platform() == "win32") { + return "/" + relative.replace(/\\/g, "/"); + } else { + return "/" + relative; + } +} + +function checkIfForbiddenPath(decodedHref, match) { + var mo = forbiddenPaths[match]; + if (!mo) return false; + if (typeof mo == "string") return decodedHref == mo || (os.platform() == "win32" && decodedHref.toLowerCase() == mo.toLowerCase()); + if (typeof mo == "object") { + for (var i = 0; i < mo.length; i++) { + if (decodedHref == mo[i] || (os.platform() == "win32" && decodedHref.toLowerCase() == mo[i].toLowerCase())) return true; + } + } + return false; +} + +function checkIfIndexOfForbiddenPath(decodedHref, match) { + var mo = forbiddenPaths[match]; + if (!mo) return false; + if (typeof mo == "string") return decodedHref == mo || decodedHref.indexOf(mo + "/") == 0 || (os.platform() == "win32" && (decodedHref.toLowerCase() == mo.toLowerCase() || decodedHref.toLowerCase().indexOf(mo.toLowerCase()) == 0)); + if (typeof mo == "object") { + for (var i = 0; i < mo.length; i++) { + if (decodedHref == mo || decodedHref.indexOf(mo[i] + "/") == 0 || (os.platform() == "win32" && (decodedHref.toLowerCase() == mo[i].toLowerCase() || decodedHref.toLowerCase().indexOf(mo[i].toLowerCase()) == 0))) return true; + } + } + return false; +} + +var forbiddenPaths = {}; + +forbiddenPaths.config = getInitializePath("./config.json"); +forbiddenPaths.certificates = []; +if (secure) { + forbiddenPaths.certificates.push(getInitializePath(configJSON.cert)); + forbiddenPaths.certificates.push(getInitializePath(configJSON.key)); + for (var i = 0; i < Object.keys(sni).length; i++) { + forbiddenPaths.certificates.push(getInitializePath(sni[Object.keys(sni)[i]].cert)); + forbiddenPaths.certificates.push(getInitializePath(sni[Object.keys(sni)[i]].key)); + } +} +forbiddenPaths.svrjs = getInitializePath("./" + ((__dirname[__dirname.length - 1] != "/") ? __filename.replace(__dirname + "/", "") : __filename.replace(__dirname, ""))); +forbiddenPaths.serverSideScripts = []; +forbiddenPaths.serverSideScripts.push("/serverSideScript.js"); +forbiddenPaths.serverSideScripts.push(getInitializePath("./temp/serverSideScript.js")); +forbiddenPaths.serverSideScriptDirectories = []; +forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./temp/modloader")); +forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./node_modules")); +forbiddenPaths.serverSideScriptDirectories.push(getInitializePath("./mods")); +forbiddenPaths.log = getInitializePath("./log"); + +//Create server +if (!cluster.isMaster) { + var reqcounter = 0; + var server = {}; + var server2 = {}; + try { + server2 = http.createServer({ + requireHostHeader: false + }); + } catch (ex) { + server2 = http.createServer(); + } + if (!disableToHTTPSRedirect) { + server2.on("request", redirhandler); + server2.on("connect", function (request, socket) { + var reqIdInt = Math.round(Math.random() * 16777216); + var reqId = "0".repeat(6 - reqIdInt.toString(16).length) + reqIdInt.toString(16); + var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + } + }; + socket.on("close", function (hasError) { + if (!hasError) serverconsole.locmessage("Client disconnected."); + else serverconsole.locmessage("Client disconnected due to error."); + }); + socket.on("error", function () {}); + var reqip = socket.remoteAddress; + var reqport = socket.remotePort; + serverconsole.locmessage("Somebody connected to port " + port + "..."); + serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants to proxy " + request.url + " through this server"); + if (request.headers["user-agent"] != undefined) serverconsole.reqmessage("Client uses " + request.headers["user-agent"]); + serverconsole.errmessage("This server will never be a proxy."); + if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n"); + }); + server2.on("clientError", function (err, socket) { + reqerrhandler(err, socket, false); + }); + server2.on("checkExpectation", redirhandler); + } else { + server2.on("request", function (req, res) { + reqhandler(req, res, false); + }); + server2.on("checkExpectation", reqhandler); + server2.on("connect", connhandler); + server2.on("clientError", function (err, socket) { + reqerrhandler(err, socket, false); + }); + + } + server2.on("error", function (err) { + if (err.code == "EADDRINUSE" || err.code == "EADDRNOTAVAIL" || err.code == "EACCES") { + attmtsRedir--; + if (cluster.isMaster === undefined) { + if (err.code == "EADDRINUSE") { + serverconsole.locerrmessage("Address in use by another process."); + } else if (err.code == "EADDRNOTAVAIL") { + serverconsole.locerrmessage("Address not available."); + } else if (err.code == "EACCES") { + serverconsole.locerrmessage("Access denied."); + } + serverconsole.locmessage(attmtsRedir + " attempts left."); + } else { + process.send("\x12ERRLIST" + attmtsRedir + err.code); + } + if (attmtsRedir > 0) { + server2.close(); + setTimeout(start, 900); + } else { + if (cluster.isMaster !== undefined) process.send("\x12" + err.code); + process.exit(errors[err.code]); + } + } else { + serverconsole.locerrmessage("There was a problem starting SVR.JS!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(generateErrorStack(err)); + if (cluster.isMaster !== undefined) process.send("\x12CRASH"); + process.exit(err.code ? errors[err.code] : 1); + } + }); + + server2.once("listening", function () { + listeningMessage(); + }); + + if (configJSON.enableHTTP2 == true) { + if (secure) { + server = http2.createSecureServer({ + allowHTTP1: true, + requireHostHeader: false, + key: key, + cert: cert + }); + } else { + server = http2.createServer({ + allowHTTP1: true, + requireHostHeader: false + }); + } + } else { + if (secure) { + server = https.createServer({ + key: key, + cert: cert, + requireHostHeader: false + }); + } else { + try { + server = http.createServer({ + requireHostHeader: false + }); + } catch (ex) { + server = http.createServer(); + } + } + } + if (secure) { + for (var i = 0; i < sniCredentials.length; i++) { + server.addContext(sniCredentials[i].name, { + cert: sniCredentials[i].cert, + key: sniCredentials[i].key + }); + } + } + server.on("request", reqhandler); + server.on("checkExpectation", reqhandler); + server.on("connect", connhandler); + server.on("clientError", reqerrhandler); + + if (secure) { + server.prependListener("connection", function (sock) { + sock.reallyDestroy = sock.destroy; + sock.destroy = function () { + sock.toDestroy = true; + }; + }); + + server.prependListener("tlsClientError", function (err, sock) { + if (err.code == "ERR_SSL_HTTP_REQUEST" || err.message.indexOf("http request") != -1) { + sock._parent.destroy = sock._parent.reallyDestroy; + sock._readableState = sock._parent._readableState; + sock._writableState = sock._parent._writableState; + sock._parent.toDestroy = false; + sock.pipe = function (a, b, c) { + sock._parent.pipe(a, b, c); + }; + sock.write = function (a, b, c) { + sock._parent.write(a, b, c); + }; + sock.end = function (a, b, c) { + sock._parent.end(a, b, c); + }; + sock.destroyed = sock._parent.destroyed; + sock.readable = sock._parent.readable; + sock.writable = sock._parent.writable; + sock.remoteAddress = sock._parent.remoteAddress; + sock.remotePort = sock._parent.remoteAddress; + sock.destroy = function (a, b, c) { + try { + sock._parent.destroy(a, b, c); + sock.destroyed = sock._parent.destroyed; + } catch (ex) { + //Socket is probably already destroyed. + } + }; + } else { + sock._parent.destroy = sock._parent.reallyDestroy; + try { + if (sock._parent.toDestroy) sock._parent.destroy(); + } catch (ex) { + //Socket is probably already destroyed. + } + } + }); + + server.prependListener("secureConnection", function (sock) { + sock._parent.destroy = sock._parent.reallyDestroy; + delete sock._parent.reallyDestroy; + }); + + if (configJSON.enableOCSPStapling && !ocsp._errored) { + server.on("OCSPRequest", function (cert, issuer, callback) { + ocsp.getOCSPURI(cert, function (err, uri) { + if (err) return callback(err); + + var req = ocsp.request.generate(cert, issuer); + var options = { + url: uri, + ocsp: req.data + }; + + ocspCache.request(req.id, options, callback); + }); + }); + } + } + + //Patches from Node.JS v18.0.0 + if (server.requestTimeout !== undefined && server.requestTimeout === 0) server.requestTimeout = 300000; + if (server2.requestTimeout !== undefined && server2.requestTimeout === 0) server2.requestTimeout = 300000; + + function redirhandler(req, res) { + if (req.headers["force-insecure"] == "true" || req.headers["x-force-insecure"] == "true" || req.headers["x-svr-js-force-insecure"] == "true") { + reqhandler(req, res, false); + } else { + var reqIdInt = Math.round(Math.random() * 16777216); + var reqId = "0".repeat(6 - reqIdInt.toString(16).length) + reqIdInt.toString(16); + var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + } + }; + + function getCustomHeaders() { + var ph = JSON.parse(JSON.stringify(customHeaders)); + var phk = Object.keys(ph); + for (var i = 0; i < phk.length; i++) { + if (typeof ph[phk[i]] == "string") ph[phk[i]] = ph[phk[i]].replace(/\{path\}/g, req.url); + } + return ph; + } + if (req.headers["x-svr-js-from-main-thread"] == "true") { + res.writeHead(204, "No Content", getCustomHeaders()); + res.end(); + return; + } + try { + req.url = encodeURI(Buffer.from(req.url, "latin1").toString("utf8")).replace(/%25/gi, "%"); + } catch (ex) { + //URL not converted... + } + res.writeHeadNative = res.writeHead; + res.writeHead = function (a, b, c) { + if (parseInt(a) >= 400 && parseInt(a) <= 599) { + serverconsole.errmessage("Server responded with " + a.toString() + " code."); + } else { + serverconsole.resmessage("Server responded with " + a.toString() + " code."); + } + res.writeHeadNative(a, b, c); + }; + var finished = false; + res.on("finish", function () { + if (!finished) { + finished = true; + serverconsole.locmessage("Client disconnected."); + } + }); + res.on("close", function () { + if (!finished) { + finished = true; + serverconsole.locmessage("Client disconnected."); + } + }); + + serverconsole.locmessage("Somebody connected to port " + port + "..."); + + if (req.socket == null) { + serverconsole.errmessage("Client socket is null!!!"); + return; + } + + var isProxy = false; + if (req.url.indexOf("/") != 0 && req.url != "*") isProxy = true; + + var head = fs.existsSync("./.head") ? fs.readFileSync("./.head").toString() : (fs.existsSync("./head.html") ? fs.readFileSync("./head.html").toString() : ""); // header + var foot = fs.existsSync("./.foot") ? fs.readFileSync("./.foot").toString() : (fs.existsSync("./foot.html") ? fs.readFileSync("./foot.html").toString() : ""); // footer + var fd = ""; + + function responseEnd(d) { + if (d === undefined) d = fd; + res.write(head + d + foot); + res.end(); + } + + //Error descriptions + var serverErrorDescs = { + 400: "The request you made is invalid.", + 417: "Expectation in Expect property couldn't be satisfied.", + 500: "The server had an unexpected error. Below, the error stack is shown:

{stack}

Please contact with developer/administrator at {contact}.", + 501: "The request requires use of a function, which isn't implemented (yet) by the server." + }; + + //Server error calling method + function callServerError(errorCode, extName, stack, ch) { + var errorFile = errorCode.toString() + ".html"; + var errorFile2 = "." + errorCode.toString(); + if (fs.existsSync(errorFile2)) errorFile = errorFile2; + if (errorCode == 404 && fs.existsSync(page404)) errorFile = page404; + if (Object.prototype.toString.call(stack) === "[object Error]") stack = generateErrorStack(stack); + if (stack === undefined) stack = generateErrorStack(new Error("Unknown error")); + if (errorCode == 500 || errorCode == 502) { + serverconsole.errmessage("There was an error while processing the request!"); + serverconsole.errmessage("Stack:"); + serverconsole.errmessage(stack); + } + if (stackHidden) stack = "[error stack hidden]"; + if (serverErrorDescs[errorCode] === undefined) { + callServerError(501, extName, stack); + } else { + var cheaders = getCustomHeaders(); + if (ch) { + var chon = Object.keys(cheaders); + var chn = Object.keys(ch); + for (var i = 0; i < chn.length; i++) { + var nhn = chn[i]; + for (var j = 0; j < chon.length; j++) { + if (chon[j].toLowerCase() == chn[i].toLowerCase()) { + nhn = chon[j]; + break; + } + } + if (ch[chn[i]]) cheaders[nhn] = ch[chn[i]]; + } + } + cheaders["Content-Type"] = "text/html; charset=utf-8"; + if (errorCode == 405 && !cheaders["Allow"]) cheaders["Allow"] = "GET, POST, HEAD, OPTIONS"; + fs.readFile(errorFile, function (err, data) { + try { + if (err) throw err; + res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + fd += data.toString().replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{path}/g, req.url.replace(/&/g, "&").replace(//g, ">")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName) + ((req.headers.host == undefined || isProxy) ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">"))).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")); + responseEnd(); + } catch (ex) { + var additionalError = 500; + if (ex.code == "ENOENT") { + additionalError = 404; + } else if (ex.code == "EACCES") { + additionalError = 403; + } else if (ex.code == "EMFILE") { + additionalError = 429; + } else if (ex.code == "ELOOP") { + additionalError = 508; + } + res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + res.write(("{errorMessage}

{errorMessage}

{errorDesc}

" + ((additionalError == 404) ? "" : "

Additionally, a {additionalError} error occurred while loading an error page.

") + "

{server}

").replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{path}/g, req.url.replace(/&/g, "&").replace(//g, ">")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName) + ((req.headers.host == undefined || isProxy) ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">"))).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")).replace(/{additionalError}/g, additionalError.toString())); + res.end(); + } + }); + + } + } + + var reqport = ""; + var reqip = ""; + var oldport = ""; + var oldip = ""; + if (req.headers["x-svr-js-client"] != undefined && enableIPSpoofing) { + var kl = req.headers["x-svr-js-client"].split(":"); + reqport = kl.pop(); + reqip = kl.join(":"); + try { + oldport = req.socket.remotePort; + oldip = req.socket.remoteAddress; + req.socket.realRemotePort = reqport; + req.socket.realRemoteAddress = reqip; + req.socket.originalRemotePort = oldport; + req.socket.originalRemoteAddress = oldip; + res.socket.realRemotePort = reqport; + res.socket.realRemoteAddress = reqip; + res.socket.originalRemotePort = oldport; + res.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Nevermind... + } + } else if (req.headers["x-forwarded-for"] != undefined && enableIPSpoofing) { + reqport = null; + reqip = req.headers["x-forwarded-for"].split(",")[0].replace(/ /g, ""); + if (reqip.indexOf(":") == -1) reqip = "::ffff:" + reqip; + try { + oldport = req.socket.remotePort; + oldip = req.socket.remoteAddress; + req.socket.realRemotePort = reqport; + req.socket.realRemoteAddress = reqip; + req.socket.originalRemotePort = oldport; + req.socket.originalRemoteAddress = oldip; + res.socket.realRemotePort = reqport; + res.socket.realRemoteAddress = reqip; + res.socket.originalRemotePort = oldport; + res.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Nevermind... + } + } else { + reqip = req.socket.remoteAddress; + reqport = req.socket.remotePort; + } + + if (!isProxy) serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants " + (req.method == "GET" ? "content in " : (req.method == "POST" ? "to post content in " : (req.method == "PUT" ? "to add content in " : (req.method == "DELETE" ? "to delete content in " : (req.method == "PATCH" ? "to patch content in " : "to access content using " + req.method + " method in "))))) + (req.headers.host == undefined ? "" : req.headers.host) + req.url); + else serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants " + (req.method == "GET" ? "content in " : (req.method == "POST" ? "to post content in " : (req.method == "PUT" ? "to add content in " : (req.method == "DELETE" ? "to delete content in " : (req.method == "PATCH" ? "to patch content in " : "to access content using " + req.method + " method in "))))) + req.url); + if (req.headers["user-agent"] != undefined) serverconsole.reqmessage("Client uses " + req.headers["user-agent"]); + + try { + if (req.headers["expect"] && req.headers["expect"] != "100-continue") { + serverconsole.errmessage("Expectation not satified!"); + callServerError(417); + return; + } + var hostx = req.headers.host; + if (hostx === undefined) { + serverconsole.errmessage("Bad request!"); + callServerError(400); + return; + } + + if (req.method == "CONNECT") { + callServerError(501); + serverconsole.errmessage("CONNECT requests aren't supported. Your JS runtime probably doesn't support 'connect' handler for HTTP library."); + return; + } + + if (isProxy) { + callServerError(501); + serverconsole.errmessage("This server will never be a proxy."); + return; + } + + function urlParse(uri) { + if (typeof URL != "undefined" && url.Url) { + try { + var uobject = new URL(uri, "http" + (req.socket.encrypted ? "s" : "") + "://" + (req.headers.host ? req.headers.host : (domain ? domain : "unknown.invalid"))); + var nuobject = new url.Url(); + if (uri.indexOf("/") != -1) nuobject.slashes = true; + if (uobject.protocol != "") nuobject.protocol = uobject.protocol; + if (uobject.username != "" && uobject.password != "") nuobject.auth = uobject.username + ":" + uobject.password; + if (uobject.host != "") nuobject.host = uobject.host; + if (uobject.hostname != "") nuobject.hostname = uobject.hostname; + if (uobject.port != "") nuobject.port = uobject.port; + if (uobject.pathname != "") nuobject.pathname = uobject.pathname; + if (uobject.search != "") nuobject.search = uobject.search; + if (uobject.hash != "") nuobject.hash = uobject.hash; + if (uobject.href != "") nuobject.href = uobject.href; + if (uri.indexOf("/") != 0) { + if (nuobject.pathname) { + nuobject.pathname = nuobject.pathname.substr(1); + nuobject.href = nuobject.pathname + (nuobject.search ? nuobject.search : ""); + } + } + if (nuobject.pathname) { + nuobject.path = nuobject.pathname + (nuobject.search ? nuobject.search : ""); + } + //if(nuobject.path != "" && uobject.password != "") nuobject.path = nuobject.pathname + nuobject.href; + nuobject.query = {}; + uobject.searchParams.forEach(function (value, key) { + nuobject.query[key] = value; + }); + return nuobject; + } catch (ex) { + return url.parse(uri, true); + } + } else { + return url.parse(uri, true); + } + } + var urlp = urlParse("http://" + hostx); + try { + if (urlp.path.indexOf("//") == 0) { + urlp = urlParse("http:" + url.path); + } + } catch (ex) { + //URL parse error... + } + if (urlp.host == "localhost" || urlp.host == "localhost:" + port.toString() || urlp.host == "127.0.0.1" || urlp.host == "127.0.0.1:" + port.toString() || urlp.host == "::1" || urlp.host == "::1:" + port.toString()) { + urlp.protocol = "https:"; + if (sport == 443) { + urlp.host = urlp.hostname; + } else { + urlp.host = urlp.hostname + ":" + sport.toString(); + urlp.port = sport.toString(); + } + } else if (urlp.host == host || urlp.host == host + ":" + port.toString()) { + urlp.protocol = "https:"; + if (sport == 443) { + urlp.host = urlp.hostname; + } else { + urlp.host = urlp.hostname + ":" + sport.toString(); + urlp.port = sport.toString(); + } + } else if (urlp.host == pubip || urlp.host == pubip + ":" + pubport.toString()) { + urlp.protocol = "https:"; + if (spubport == 443) { + urlp.host = urlp.hostname; + } else { + urlp.host = urlp.hostname + ":" + spubport.toString(); + urlp.port = spubport.toString(); + } + } else if (urlp.hostname == domain || urlp.hostname.indexOf(domain) != -1) { + urlp.protocol = "https:"; + if (spubport == 443) { + urlp.host = urlp.hostname; + } else { + urlp.host = urlp.hostname + ":" + spubport.toString(); + urlp.port = spubport.toString(); + } + } else { + urlp.protocol = "https:"; + } + urlp.path = null; + urlp.pathname = null; + var lloc = url.format(urlp); + var requestURL = req.url; + try { + if (requestURL.split("/")[1].indexOf(".onion") != -1) { + requestURL = requestURL.split("/"); + requestURL.shift(); + requestURL.shift(); + requestURL.unshift(""); + requestURL = requestURL.join("/"); + } + } catch (ex) { + //Leave URL as it is... + } + var rheaders = getCustomHeaders(); + rheaders["Location"] = lloc + requestURL; + res.writeHead(301, "Redirect to HTTPS", rheaders); + res.end(); + } catch (ex) { + serverconsole.errmessage("There was an error while processing the request!"); + serverconsole.errmessage("Stack:"); + serverconsole.errmessage(generateErrorStack(ex)); + callServerError(500, undefined, generateErrorStack(ex)); + } + + } + } + + function reqerrhandler(err, socket, fromMain) { + if (fromMain === undefined) fromMain = true; + //Define response object similar to Node.JS native one + var res = {}; + res.socket = socket; + res.write = function (x) { + if (err.code === "ECONNRESET" || !socket.writable) { + return; + } + socket.write(x); + }; + res.end = function (x) { + if (err.code === "ECONNRESET" || !socket.writable) { + return; + } + socket.end(x, function () { + try { + socket.destroy(); + } catch (ex) { + //Socket is probably already destroyed + } + }); + }; + res.writeHead = function (code, name, headers) { + var head = ("HTTP/1.1 " + code.toString() + " " + name + "\r\n"); + var headers = JSON.parse(JSON.stringify(headers)); + headers["Date"] = (new Date()).toGMTString(); + headers["Connection"] = "close"; + var headernames = Object.keys(headers); + for (var i = 0; i < headernames.length; i++) { + if (headernames[i].toLowerCase() == "set-cookie") { + for (var j = 0; j < headers[headernames[i]]; j++) { + if (headernames[i].match(/[^\x09\x20-\x7e\x80-\xff]|.:/) || headers[headernames[i]][j].match(/[^\x09\x20-\x7e\x80-\xff]/)) throw new Error("Invalid header!!! (" + headernames[i] + ")"); + head += (headernames[i] + ": " + headers[headernames[i]][j]); + } + } else { + if (headernames[i].match(/[^\x09\x20-\x7e\x80-\xff]|.:/) || headers[headernames[i]].match(/[^\x09\x20-\x7e\x80-\xff]/)) throw new Error("Invalid header!!! (" + headernames[i] + ")"); + head += (headernames[i] + ": " + headers[headernames[i]]); + } + head += "\r\n"; + } + head += ("\r\n"); + res.write(head); + }; + + var reqIdInt = Math.round(Math.random() * 16777216); + var reqId = "0".repeat(6 - reqIdInt.toString(16).length) + reqIdInt.toString(16); + var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + } + }; + socket.on("close", function (hasError) { + if (!hasError || err.code == "ERR_SSL_HTTP_REQUEST" || err.message.indexOf("http request") != -1) serverconsole.locmessage("Client disconnected."); + else serverconsole.locmessage("Client disconnected due to error."); + }); + socket.on("error", function () {}); + + var head = fs.existsSync("./.head") ? fs.readFileSync("./.head").toString() : (fs.existsSync("./head.html") ? fs.readFileSync("./head.html").toString() : ""); // header + var foot = fs.existsSync("./.foot") ? fs.readFileSync("./.foot").toString() : (fs.existsSync("./foot.html") ? fs.readFileSync("./foot.html").toString() : ""); // footer + + var fd = ""; + + function responseEnd(d) { + if (d === undefined) d = fd; + res.write(head + d + foot); + res.end(); + } + + var serverErrorDescs = { + 400: "The request you made is invalid.", + 405: "Method used to access the requested file isn't allowed.", + 408: "You have timed out.", + 414: "URL you sent is too long.", + 431: "The request you sent contains headers, that are too large.", + 451: "The requested file isn't accessible for legal reasons.", + 497: "You sent non-TLS request to the HTTPS server." + }; + + //Server error calling method + function callServerError(errorCode, extName, stack, ch) { + var errorFile = errorCode.toString() + ".html"; + var errorFile2 = "." + errorCode.toString(); + if (fs.existsSync(errorFile2)) errorFile = errorFile2; + if (errorCode == 404 && fs.existsSync(page404)) errorFile = page404; + if (Object.prototype.toString.call(stack) === "[object Error]") stack = generateErrorStack(stack); + if (stack === undefined) stack = generateErrorStack(new Error("Unknown error")); + if (errorCode == 500 || errorCode == 502) { + serverconsole.errmessage("There was an error while processing the request!"); + serverconsole.errmessage("Stack:"); + serverconsole.errmessage(stack); + } + if (stackHidden) stack = "[error stack hidden]"; + if (serverErrorDescs[errorCode] === undefined) { + callServerError(501, extName, stack); + } else { + var cheaders = getCustomHeaders(); + if (ch) { + var chon = Object.keys(cheaders); + var chn = Object.keys(ch); + for (var i = 0; i < chn.length; i++) { + var nhn = chn[i]; + for (var j = 0; j < chon.length; j++) { + if (chon[j].toLowerCase() == chn[i].toLowerCase()) { + nhn = chon[j]; + break; + } + } + if (ch[chn[i]]) cheaders[nhn] = ch[chn[i]]; + } + } + cheaders["Content-Type"] = "text/html; charset=utf-8"; + if (errorCode == 405 && !cheaders["Allow"]) cheaders["Allow"] = "GET, POST, HEAD, OPTIONS"; + fs.readFile(errorFile, function (err, data) { + try { + if (err) throw err; + res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + fd += data.toString().replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName)).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")); + responseEnd(); + } catch (ex) { + var additionalError = 500; + if (ex.code == "ENOENT") { + additionalError = 404; + } else if (ex.code == "EACCES") { + additionalError = 403; + } else if (ex.code == "EMFILE") { + additionalError = 429; + } else if (ex.code == "ELOOP") { + additionalError = 508; + } + res.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + res.write(("{errorMessage}

{errorMessage}

{errorDesc}

" + ((additionalError == 404) ? "" : "

Additionally, a {additionalError} error occurred while loading an error page.

") + "

{server}

").replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName)).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")).replace(/{additionalError}/g, additionalError.toString())); + res.end(); + } + }); + + } + } + var reqip = socket.remoteAddress; + var reqport = socket.remotePort; + serverconsole.locmessage("Somebody connected to port " + (secure && fromMain ? sport : port) + "..."); + serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " sent invalid request."); + try { + if ((err.code && (err.code.indexOf("ERR_SSL_") == 0 || err.code.indexOf("ERR_TLS_") == 0)) || (!err.code && err.message.indexOf("SSL routines") != -1)) { + if (err.code == "ERR_SSL_HTTP_REQUEST" || err.message.indexOf("http request") != -1) { + serverconsole.errmessage("Client sent HTTP request to HTTPS port."); + callServerError(497); + return; + } else { + serverconsole.errmessage("An SSL error occured: " + (err.code ? err.code : err.message)); + callServerError(400); + return; + } + } + + if (err.code && err.code == "ERR_HTTP_REQUEST_TIMEOUT") { + serverconsole.errmessage("Client timed out."); + callServerError(408); + return; + } + + if (!err.rawPacket) { + serverconsole.errmessage("Connection ended prematurely."); + callServerError(400); + return; + } + + var packetLines = err.rawPacket.toString().split("\r\n"); + if (packetLines.length == 0) { + serverconsole.errmessage("Invalid request."); + callServerError(400); + return; + } + + function checkHeaders(beginsFromFirst) { + for (var i = (beginsFromFirst ? 0 : 1); i < packetLines.length; i++) { + var header = packetLines[i]; + if (header == "") return false; //Beginning of body + else if (header.indexOf(":") < 1) { + serverconsole.errmessage("Invalid header."); + callServerError(400); + return true; + } else if (header.length > 8192) { + serverconsole.errmessage("Header too large."); + callServerError(431); //Headers too large + return true; + } + } + return false; + } + var packetLine1 = packetLines[0].split(" "); + var method = "GET"; + var httpVersion = "HTTP/1.1"; + if (String(packetLine1[0]).indexOf(":") > 0) { + if (!checkHeaders(true)) { + serverconsole.errmessage("The request is invalid."); + callServerError(400); //Also malformed Packet + return; + } + } + if (String(packetLine1[0]).length < 50) method = packetLine1.shift(); + if (String(packetLine1[packetLine1.length - 1]).length < 50) httpVersion = packetLine1.pop(); + if (packetLine1.length != 1) { + serverconsole.errmessage("The head of request is invalid."); + callServerError(400); //Malformed Packet + } else if (!httpVersion.toString().match(/^HTTP[\/]/i)) { + serverconsole.errmessage("Invalid protocol."); + callServerError(400); //bad protocol version + } else if (http.METHODS.indexOf(method) == -1) { + serverconsole.errmessage("Invalid method."); + callServerError(405); //Also malformed Packet + } else { + if (checkHeaders(false)) return; + if (packetLine1[0].length > 255) { + serverconsole.errmessage("URI too long."); + callServerError(414); //Also malformed Packet + } else { + serverconsole.errmessage("Bad request."); + callServerError(400); //Also malformed Packet + } + } + } catch (ex) { + serverconsole.errmessage("There was an error while determining type of malformed request."); + callServerError(400); + } + } + + function connhandler(request, socket, head) { + var reqIdInt = Math.round(Math.random() * 16777216); + var reqId = "0".repeat(6 - reqIdInt.toString(16).length) + reqIdInt.toString(16); + var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + } + }; + var req = request; + socket.on("close", function (hasError) { + if (!hasError) serverconsole.locmessage("Client disconnected."); + else serverconsole.locmessage("Client disconnected due to error."); + }); + socket.on("error", function () {}); + + var reqip = socket.remoteAddress; + var reqport = socket.remotePort; + serverconsole.locmessage("Somebody connected to port " + (secure ? sport : port) + "..."); + serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants to proxy " + request.url + " through this server"); + if (request.headers["user-agent"] != undefined) serverconsole.reqmessage("Client uses " + request.headers["user-agent"]); + + function modExecute(mods, ffinals) { + var proxyMods = []; + for (var i = 0; i < mods.length; i++) { + if (mods[i].proxyCallback !== undefined) proxyMods.push(mods[i]); + } + + var modFunction = ffinals; + for (var i = proxyMods.length - 1; i >= 0; i--) { + modFunction = proxyMods[i].callback(req, socket, head, configJSON, serverconsole, modFunction); + } + modFunction(); + } + + function vres(req, socket, head, serverconsole) { + return function () { + serverconsole.errmessage("SVR.JS doesn't support proxy without proxy mod."); + if (!socket.destroyed) socket.end("HTTP/1.1 501 Not Implemented\n\n"); + }; + } + modExecute(mods, vres(req, socket, head, serverconsole)); + } + + function reqhandler(request, response, fromMain) { + if (fromMain === undefined) fromMain = true; + var reqIdInt = Math.round(Math.random() * 16777216); + var reqId = "0".repeat(6 - reqIdInt.toString(16).length) + reqIdInt.toString(16); + var serverconsole = { + climessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.climessage(nmsg[i]); + } + return; + } + console.log("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER CLI MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + reqmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.reqmessage(nmsg[i]); + } + return; + } + console.log("\x1b[34mSERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER REQUEST MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + resmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.resmessage(nmsg[i]); + } + return; + } + console.log("\x1b[32mSERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + errmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.errmessage(nmsg[i]); + } + return; + } + console.log("\x1b[31mSERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[37m\x1b[0m"); + LOG("SERVER RESPONSE ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locerrmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locerrmessage(nmsg[i]); + } + return; + } + console.log("\x1b[41mSERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER ERROR MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locwarnmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locwarnmessage(nmsg[i]); + } + return; + } + console.log("\x1b[43mSERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg + "\x1b[40m\x1b[0m"); + LOG("SERVER WARNING MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + }, + locmessage: function (msg) { + if (msg.indexOf("\n") != -1) { + var nmsg = msg.split("\n"); + for (var i = 0; i < nmsg.length; i++) { + serverconsole.locmessage(nmsg[i]); + } + return; + } + console.log("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + LOG("SERVER MESSAGE [Request Id: " + reqId + "]: " + msg); + return; + } + }; + + function getCustomHeaders() { + var ph = JSON.parse(JSON.stringify(customHeaders)); + var phk = Object.keys(ph); + for (var i = 0; i < phk.length; i++) { + if (typeof ph[phk[i]] == "string") ph[phk[i]] = ph[phk[i]].replace(/\{path\}/g, request.url); + } + return ph; + } + + //Make HTTP/1.x API-based scripts compatible with HTTP/2.0 API + if (configJSON.enableHTTP2 == true && request.httpVersion == "2.0") { + try { + //Set HTTP/1.x methods (to prevent process warnings) + response.writeHeadNodeApi = response.writeHead; + response.setHeaderNodeApi = response.setHeader; + response.writeHead = function (a, b, c) { + var table = c; + if (typeof (b) == "object") table = b; + if (table == undefined) table = this.tHeaders; + table = JSON.parse(JSON.stringify(table)); + if (table["content-type"] != undefined && table["Content-Type"] != undefined) { + delete table["content-type"]; + } + delete table["transfer-encoding"]; + delete table["connection"]; + delete table["keep-alive"]; + delete table["upgrade"]; + return response.writeHeadNodeApi(a, table); + }; + + response.setHeader = function (a, b) { + if (a != "transfer-encoding" && a != "connection" && a != "keep-alive" && a != "upgrade") return response.setHeaderNodeApi(a, b); + return false; + }; + //Set HTTP/1.x headers + if (!request.headers.host) request.headers.host = request.headers[":authority"]; + (request.headers[":path"] == undefined ? (function () {})() : request.url = request.headers[":path"]); + request.protocol = request.headers[":scheme"]; + var headers = [":path" || ":method"]; + for (var i = 0; i < headers.length; i++) { + if (request.headers[headers[i]] == undefined) { + var cheaders = getCustomHeaders(); + cheaders["Content-Type"] = "text/html; charset=utf-8"; + response.writeHead(400, "Bad Request", cheaders); + response.write("400 Bad Request

400 Bad Request

The request you sent is invalid.

" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (request.headers[":authority"] == undefined ? "" : " on " + request.headers[":authority"]) + "

"); + response.end(); + return; + } + } + } catch (ex) { + var cheaders = getCustomHeaders(); + cheaders["Content-Type"] = "text/html; charset=utf-8"; + cheaders[":status"] = "500"; + response.stream.respond(cheaders); + response.stream.write("500 Internal Server Error

500 Internal Server Error

The server had an unexpected error. Below, error stack is shown:

" + (stackHidden ? "[error stack hidden]" : generateErrorStack(ex)).replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ") + "

Please contact with developer/administrator of the website.

" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (request.headers[":authority"] == undefined ? "" : " on " + request.headers[":authority"]) + "

"); + response.stream.end(); + return; + } + } + + if (request.headers["x-svr-js-from-main-thread"] == "true") { + response.writeHead(204, "No Content", getCustomHeaders()); + var lastStatusCode = null; + response.end(); + return; + } + + try { + request.url = encodeURI(Buffer.from(request.url, "latin1").toString("utf8")).replace(/%25/gi, "%"); + } catch (ex) { + //Request URL not modified... + } + + var headWritten = false; + response.writeHeadNative = response.writeHead; + response.writeHead = function (a, b, c) { + if (!(headWritten && process.isBun && a === lastStatusCode && b === undefined && c === undefined)) { + if (headWritten) { + process.emitWarning("res.writeHead called multiple times.", { + code: "WARN_SVRJS_MULTIPLE_WRITEHEAD" + }); + return response; + } else { + headWritten = true; + } + if (parseInt(a) >= 400 && parseInt(a) <= 599) { + serverconsole.errmessage("Server responded with " + a.toString() + " code."); + } else { + serverconsole.resmessage("Server responded with " + a.toString() + " code."); + } + lastStatusCode = a; + } + response.writeHeadNative(a, b, c); + }; + if (wwwredirect) { + var hostname = request.headers.host.split[":"]; + var hostport = null; + if (hostname.length > 1 && (hostname[0] != "[" || hostname[hostname.length - 1] != "]")) hostport = hostname.pop(); + hostname = hostname.join(":"); + } + if (wwwredirect && hostname == domain && hostname.indexOf("www.") != 0) { + var lloc = (request.socket.encrypted ? "https" : "http") + "://" + hostname + (hostport ? ":" + hostport : ""); + try { + var rheaders = getCustomHeaders(); + rheaders["Location"] = lloc + (request.url.replace(/\/+/g, "/")); + response.writeHead(301, "Redirect to WWW", rheaders); + response.end(); + } catch (ex) { + var cheaders = getCustomHeaders(); + cheaders["Content-Type"] = "text/html; charset=utf-8"; + res.writeHead(500, "Internal Server Error", cheaders); + res.write("500 Internal Server Error

500 Internal Server Error

The server had an unexpected error. Below, error stack is shown:

" + (stackHidden ? "[error stack hidden]" : generateErrorStack(ex)).replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ") + "

Please contact with developer/administrator of the website.

" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (req.headers.host == undefined ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">")) + "

"); + response.end(); + } + } else { + var finished = false; + response.on("finish", function () { + if (!finished) { + finished = true; + serverconsole.locmessage("Client disconnected."); + } + }); + response.on("close", function () { + if (!finished) { + finished = true; + serverconsole.locmessage("Client disconnected."); + } + }); + var isProxy = false; + if (request.url.indexOf("/") != 0 && request.url != "*") isProxy = true; + serverconsole.locmessage("Somebody connected to port " + (secure && fromMain ? sport : port) + "..."); + + if (request.socket == null) { + serverconsole.errmessage("Client socket is null!!!"); + return; + } + + var reqport = ""; + var reqip = ""; + var oldport = ""; + var oldip = ""; + if (request.headers["x-svr-js-client"] != undefined && enableIPSpoofing) { + var kl = request.headers["x-svr-js-client"].split(":"); + reqport = kl.pop(); + reqip = kl.join(":"); + try { + oldport = request.socket.remotePort; + oldip = request.socket.remoteAddress; + request.socket.realRemotePort = reqport; + request.socket.realRemoteAddress = reqip; + request.socket.originalRemotePort = oldport; + request.socket.originalRemoteAddress = oldip; + response.socket.realRemotePort = reqport; + response.socket.realRemoteAddress = reqip; + response.socket.originalRemotePort = oldport; + response.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Address setting failed + } + } else if (request.headers["x-forwarded-for"] != undefined && enableIPSpoofing) { + reqport = null; + reqip = request.headers["x-forwarded-for"].split(",")[0].replace(/ /g, ""); + if (reqip.indexOf(":") == -1) reqip = "::ffff:" + reqip; + try { + oldport = request.socket.remotePort; + oldip = request.socket.remoteAddress; + request.socket.realRemotePort = reqport; + request.socket.realRemoteAddress = reqip; + request.socket.originalRemotePort = oldport; + request.socket.originalRemoteAddress = oldip; + response.socket.realRemotePort = reqport; + response.socket.realRemoteAddress = reqip; + response.socket.originalRemotePort = oldport; + response.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Address setting failed + } + } else { + reqip = request.socket.remoteAddress; + reqport = request.socket.remotePort; + } + + if (!isProxy) serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants " + (request.method == "GET" ? "content in " : (request.method == "POST" ? "to post content in " : (request.method == "PUT" ? "to add content in " : (request.method == "DELETE" ? "to delete content in " : (request.method == "PATCH" ? "to patch content in " : "to access content using " + request.method + " method in "))))) + (request.headers.host == undefined ? "" : request.headers.host) + request.url); + else serverconsole.reqmessage("Client " + ((!reqip || reqip == "") ? "[unknown client]" : (reqip + ((reqport && reqport !== 0) && reqport != "" ? ":" + reqport : ""))) + " wants " + (request.method == "GET" ? "content in " : (request.method == "POST" ? "to post content in " : (request.method == "PUT" ? "to add content in " : (request.method == "DELETE" ? "to delete content in " : (request.method == "PATCH" ? "to patch content in " : "to access content using " + request.method + " method in "))))) + request.url); + if (request.headers["user-agent"] != undefined) serverconsole.reqmessage("Client uses " + request.headers["user-agent"]); + + var acceptEncoding = request.headers["accept-encoding"]; + if (!acceptEncoding) acceptEncoding = ""; + + var head = fs.existsSync("./.head") ? fs.readFileSync("./.head").toString() : (fs.existsSync("./head.html") ? fs.readFileSync("./head.html").toString() : ""); // header + var foot = fs.existsSync("./.foot") ? fs.readFileSync("./.foot").toString() : (fs.existsSync("./foot.html") ? fs.readFileSync("./foot.html").toString() : ""); // footer + + var fd = ""; + + function responseEnd(d) { + if (d === undefined) d = fd; + res.write(head + d + foot); + res.end(); + } + + // function responseEndGzip(d) { + // if (d === undefined) d = fd; + // zlib.gzip(head + d + foot, function (err, buff) { + // if (err) { + // throw err; + // } else { + // res.write(buff); + // res.end(); + // } + // }); + // } + // + // function responseEndDeflate(d) { + // if (d === undefined) d = fd; + // zlib.deflateRaw(head + d + foot, function (err, buff) { + // if (err) { + // throw err; + // } else { + // res.write(buff); + // res.end(); + // } + // }); + // } + + var req = request; // request var is req = request + var res = response; // response var is res = response + + //Error descriptions + var serverErrorDescs = { + 200: "The request succeeded! :)", + 201: "New resource has been created.", + 202: "The request has been accepted for processing, but the processing has not been completed.", + 400: "The request you made is invalid.", + 401: "You need to authenticate yourself in order to access the requested file.", + 402: "You need to pay in order to access the requested file.", + 403: "You don't have access to the requested file.", + 404: "The requested file doesn't exist. If you have typed URL manually, then please check the spelling.", + 405: "Method used to access the requested file isn't allowed.", + 406: "The request is capable of generating only not acceptable content.", + 407: "You need to authenticate yourself in order to use the proxy.", + 408: "You have timed out.", + 409: "The request you sent conflicts with the current state of the server.", + 410: "The requested file is permanently deleted.", + 411: "Content-Length property is required.", + 412: "The server doesn't meet preconditions you put in the request.", + 413: "The request you sent is too large.", + 414: "URL you sent is too long.", + 415: "The media type of request you sent isn't supported by the server.", + 416: "Content-Range you sent is unsatisfiable.", + 417: "Expectation in Expect property couldn't be satisfied.", + 418: "The server (teapot) can't brew any coffee! ;)", + 421: "The request you made isn't intended for this server.", + 422: "The server couldn't process content sent by you.", + 423: "The requested file is locked.", + 424: "The request depends on another failed request.", + 425: "The server is unwilling to risk processing a request that might be replayed.", + 426: "You need to upgrade protocols you use to request a file.", + 428: "The request you sent needs to be conditional, but it isn't.", + 429: "You sent too much requests to the server.", + 431: "The request you sent contains headers, that are too large.", + 451: "The requested file isn't accessible for legal reasons.", + 500: "The server had an unexpected error. Below, the error stack is shown:

{stack}

Please contact with developer/administrator at {contact}.", + 501: "The request requires use of a function, which isn't implemented (yet) by the server.", + 502: "The server had an error, while it was acting as a gateway.

Please contact with developer/administrator at {contact}.", + 503: "Service provided by the server isn't available (yet).

Please contact with developer/administrator at {contact}.", + 504: "The server couldn't get response in time, while it was acting as a gateway.

Please contact with developer/administrator at {contact}.", + 505: "The server doesn't support HTTP version used in the request.", + 506: "Variant header is configured to be engaged in content negotiation.

Please contact with developer/administrator at {contact}.", + 507: "The server ran out of disk space neccessary to complete the request.", + 508: "The server detected an infinite loop while processing the request.", + 509: "The server has it's bandwidth limit exceeded.

Please contact with developer/administrator at {contact}.", + 510: "The server requires an extended HTTP request. The request you made isn't an extended HTTP request.", + 511: "You need to authenticate yourself in order to get network access.", + 598: "The server couldn't get response in time, while it was acting as a proxy.", + 599: "The server couldn't connect in time, while it was acting as a proxy." + }; + + //Server error calling method + // Server error calling method + function callServerError(errorCode, extName, stack, ch) { + if (typeof errorCode !== "number") { + throw new TypeError("HTTP error code parameter needs to be an integer."); + } + + // Handle optional parameters + if (extName && typeof extName === "object") { + ch = stack; + stack = extName; + extName = undefined; + } else if (typeof extName !== "string" && extName !== null && extName !== undefined) { + throw new TypeError("Extension name parameter needs to be a string."); + } + + if (stack && typeof stack === "object" && Object.prototype.toString.call(stack) !== "[object Error]") { + ch = stack; + stack = undefined; + } else if (typeof stack !== "object" && typeof stack !== "string" && stack) { + throw new TypeError("Error stack parameter needs to be either a string or an instance of Error object."); + } + + var errorFile = errorCode.toString() + ".html"; + var errorFile2 = "." + errorCode.toString(); + if (fs.existsSync(errorFile2)) errorFile = errorFile2; + if (errorCode == 404 && fs.existsSync(page404)) errorFile = page404; + + // Generate error stack if not provided + if (Object.prototype.toString.call(stack) === "[object Error]") stack = generateErrorStack(stack); + if (stack === undefined) stack = generateErrorStack(new Error("Unknown error")); + + if (errorCode == 500 || errorCode == 502) { + serverconsole.errmessage("There was an error while processing the request!"); + serverconsole.errmessage("Stack:"); + serverconsole.errmessage(stack); + } + + // Hide the error stack if specified + if (stackHidden) stack = "[error stack hidden]"; + + // Validate the error code and handle unknown codes + if (serverErrorDescs[errorCode] === undefined) { + callServerError(501, extName, stack); + } else { + var cheaders = getCustomHeaders(); + + // Process custom headers if provided + if (ch) { + var chon = Object.keys(cheaders); + var chn = Object.keys(ch); + for (var i = 0; i < chn.length; i++) { + var nhn = chn[i]; + for (var j = 0; j < chon.length; j++) { + if (chon[j].toLowerCase() == chn[i].toLowerCase()) { + nhn = chon[j]; + break; + } + } + if (ch[chn[i]]) cheaders[nhn] = ch[chn[i]]; + } + } + + cheaders["Content-Type"] = "text/html; charset=utf-8"; + + // Set default Allow header for 405 error if not provided + if (errorCode == 405 && !cheaders["Allow"]) cheaders["Allow"] = "GET, POST, HEAD, OPTIONS"; + + // Read the error file and replace placeholders with error information + fs.readFile(errorFile, function (err, data) { + try { + if (err) throw err; + response.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + fd += data.toString().replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{path}/g, request.url.replace(/&/g, "&").replace(//g, ">")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName) + ((req.headers.host == undefined || isProxy) ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">"))).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")); // Replace placeholders in error response + responseEnd(); + } catch (ex) { + var additionalError = 500; + // Handle additional error cases + if (ex.code == "ENOENT") { + additionalError = 404; + } else if (ex.code == "EACCES") { + additionalError = 403; + } else if (ex.code == "EMFILE") { + additionalError = 429; + } else if (ex.code == "ELOOP") { + additionalError = 508; + } + + response.writeHead(errorCode, http.STATUS_CODES[errorCode], cheaders); + response.write(("{errorMessage}

{errorMessage}

{errorDesc}

" + ((additionalError == 404) ? "" : "

Additionally, a {additionalError} error occurred while loading an error page.

") + "

{server}

").replace(/{errorMessage}/g, errorCode.toString() + " " + http.STATUS_CODES[errorCode]).replace(/{errorDesc}/g, serverErrorDescs[errorCode]).replace(/{stack}/g, stack.replace(/&/g, "&").replace(//g, ">").replace(/\r\n/g, "
").replace(/\n/g, "
").replace(/\r/g, "
").replace(/ {2}/g, "  ")).replace(/{path}/g, request.url.replace(/&/g, "&").replace(//g, ">")).replace(/{server}/g, "" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (extName == undefined ? "" : " " + extName) + ((req.headers.host == undefined || isProxy) ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">"))).replace(/{contact}/g, serverAdmin.replace(/\./g, "[dot]").replace(/@/g, "[at]")).replace(/{additionalError}/g, additionalError.toString())); // Replace placeholders in error response + response.end(); + } + }); + } + } + + + function redirect(dest, isTemporary, headers) { + if (headers === undefined) headers = getCustomHeaders(); + headers["Location"] = dest; + var scode = isTemporary ? 302 : 301; + res.writeHead(scode, http.STATUS_CODES[scode], headers); + serverconsole.resmessage("Client redirected to " + dest); + res.end(); + return; + } + + function parsePostData(options, callback) { + if (req.method != "POST") { + var h = getCustomHeaders(); + h["Allow"] = "POST"; + callServerError(405, undefined, undefined, h); + return; + } + var formidableOptions = options; + if (!callback) { + callback = options; + formidableOptions = {}; + } + if (formidable._errored) callServerError(500, undefined, generateErrorStack(formidable._errored)); + var form = formidable(formidableOptions); + form.parse(req, function (err, fields, files) { + if (err) { + if(err.httpCode) callServerError(err.httpCode); + else callServerError(400); + return; + } + callback(fields, files); + }); + } + + function urlParse(uri) { + if (typeof URL != "undefined" && url.Url) { + try { + var uobject = new URL(uri, "http" + (req.socket.encrypted ? "s" : "") + "://" + (req.headers.host ? req.headers.host : (domain ? domain : "unknown.invalid"))); + var nuobject = new url.Url(); + if (uri.indexOf("/") != -1) nuobject.slashes = true; + if (uobject.protocol != "") nuobject.protocol = uobject.protocol; + if (uobject.username != "" && uobject.password != "") nuobject.auth = uobject.username + ":" + uobject.password; + if (uobject.host != "") nuobject.host = uobject.host; + if (uobject.hostname != "") nuobject.hostname = uobject.hostname; + if (uobject.port != "") nuobject.port = uobject.port; + if (uobject.pathname != "") nuobject.pathname = uobject.pathname; + if (uobject.search != "") nuobject.search = uobject.search; + if (uobject.hash != "") nuobject.hash = uobject.hash; + if (uobject.href != "") nuobject.href = uobject.href; + if (uri.indexOf("/") != 0) { + if (nuobject.pathname) { + nuobject.pathname = nuobject.pathname.substr(1); + nuobject.href = nuobject.pathname + (nuobject.search ? nuobject.search : ""); + } + } + if (nuobject.pathname) { + nuobject.path = nuobject.pathname + (nuobject.search ? nuobject.search : ""); + } + nuobject.query = {}; + uobject.searchParams.forEach(function (value, key) { + nuobject.query[key] = value; + }); + return nuobject; + } catch (ex) { + return url.parse(uri, true); + } + } else { + return url.parse(uri, true); + } + } + + var uobject = urlParse(req.url); + var search = uobject.search; + var href = uobject.pathname; + var ext = path.extname(href).toLowerCase(); + ext = ext.substr(1, ext.length); + var decodedHref = ""; + try { + decodedHref = decodeURIComponent(href); + } catch (ex) { + //Return 400 error + callServerError(400); + serverconsole.errmessage("Bad request!"); + return; + } + + if (req.headers["expect"] && req.headers["expect"] != "100-continue") { + callServerError(417); + return; + } + + //MOD EXCECUTION FUNCTION + function modExecute(mods, ffinals) { + var modFunction = ffinals; + for (var i = mods.length - 1; i >= 0; i--) { + modFunction = mods[i].callback(req, res, serverconsole, responseEnd, href, ext, uobject, search, "index.html", users, page404, head, foot, fd, modFunction, configJSON, callServerError, getCustomHeaders, origHref, redirect, parsePostData); + } + modFunction(); + } + + var vresCalled = false; + + function vres(req, res, serverconsole, responseEnd, href, ext, uobject, search, defaultpage, users, page404, head, foot, fd, callServerError, getCustomHeaders, origHref, redirect, parsePostData) { + return function () { + if (vresCalled) { + process.emitWarning("elseCallback() invoked multiple times.", { + code: "WARN_SVRJS_MULTIPLE_ELSECALLBACK" + }); + return; + } else { + vresCalled = true; + } + // function responseEndGzip(d) { + // if (d === undefined) d = fd; + // zlib.gzip(head + d + foot, function (err, buff) { + // if (err) { + // throw err; + // } else { + // res.write(buff); + // res.end(); + // } + // }); + // } + // + // function responseEndDeflate(d) { + // if (d === undefined) d = fd; + // zlib.deflateRaw(head + d + foot, function (err, buff) { + // if (err) { + // throw err; + // } else { + // res.write(buff); + // res.end(); + // } + // }); + // } + + function responseEnd(d) { + if (d === undefined) d = fd; + res.write(head + d + foot); + res.end(); + } + + if (req.socket == null) { + serverconsole.errmessage("Client socket is null!!!"); + return; + } + + var reqport = ""; + var reqip = ""; + var oldport = ""; + var oldip = ""; + if (req.headers["x-svr-js-client"] != undefined && enableIPSpoofing) { + var kl = req.headers["x-svr-js-client"].split(":"); + reqport = kl.pop(); + reqip = kl.join(":"); + try { + oldport = req.socket.remotePort; + oldip = req.socket.remoteAddress; + req.socket.realRemotePort = reqport; + req.socket.realRemoteAddress = reqip; + req.socket.originalRemotePort = oldport; + req.socket.originalRemoteAddress = oldip; + res.socket.realRemotePort = reqport; + res.socket.realRemoteAddress = reqip; + res.socket.originalRemotePort = oldport; + res.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Nevermind... + } + } else if (req.headers["x-forwarded-for"] != undefined && enableIPSpoofing) { + reqport = null; + reqip = req.headers["x-forwarded-for"].split(",")[0].replace(/ /g, ""); + if (reqip.indexOf(":") == -1) reqip = "::ffff:" + reqip; + try { + oldport = req.socket.remotePort; + oldip = req.socket.remoteAddress; + req.socket.realRemotePort = reqport; + req.socket.realRemoteAddress = reqip; + req.socket.originalRemotePort = oldport; + req.socket.originalRemoteAddress = oldip; + res.socket.realRemotePort = reqport; + res.socket.realRemoteAddress = reqip; + res.socket.originalRemotePort = oldport; + res.socket.originalRemoteAddress = oldip; + } catch (ex) { + //Nevermind... + } + } else { + reqip = req.socket.remoteAddress; + reqport = req.socket.remotePort; + } + + function checkLevel(e) { + for (var n = e.split("/"), r = 0, t = 0; t < n.length; t += 1) ".." == n[t] ? r -= 1 : "." !== n[t] && "" !== n[t] && (r += 1); + return r; + } + + if (isProxy) { + var eheaders = getCustomHeaders(); + eheaders["Content-Type"] = "text/html; charset=utf-8"; + res.writeHead(501, "Not implemented", eheaders); + res.write("Proxy not implemented

Proxy not implemented

SVR.JS doesn't support proxy without proxy mod. If you're administator of this server, then install this mod in order to use SVR.JS as a proxy.

" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + "

"); + res.end(); + serverconsole.errmessage("SVR.JS doesn't support proxy without proxy mod."); + return; + } + + if (req.method == "OPTIONS") { + var hdss = getCustomHeaders(); + hdss["Allow"] = "GET, POST, HEAD, OPTIONS"; + res.writeHead(204, "No Content", hdss); + res.end(); + return; + } else if (req.method != "GET" && req.method != "POST" && req.method != "HEAD") { + callServerError(405); + serverconsole.errmessage("Invaild method: " + req.method); + return; + } + + if (href == "/invoke500.svr" || (os.platform() == "win32" && href.toLowerCase() == "/invoke500.svr")) { + if (version.indexOf("Nightly-") === 0 && uobject.query.crash !== undefined) throw new Error("Intentionally crashed"); + try { + if (uobject.query.aprilfools === undefined) throw new Error("This page is intended to return 500 code."); + var hdhds = getCustomHeaders(); + hdhds["Content-Type"] = "text/html; charset=utf-8"; + if (uobject.query.activate === undefined) { + res.writeHead(599, "You may be a victim of software counterfeiting.", hdhds); + res.end("Directory traversal prevention is not working.
  X  
Directory traversal prevention is not working.
You may be a victim of software
counterfeiting.


To use all DorianTech SVR.JS features, such as all
directory traversal protections; use server-side JS;
and recieve product support, your copy of DorianTech
SVR.JS must be validated as genuine.

Go online and resolve now

This copy of SVR.JS is not genuine."); + serverconsole.resmessage("You may be a victim of software counterfeiting."); + } else { + res.writeHead(200, "OK", hdhds); + res.end("\n\n\n\nSVR.JS Genuine Advantage\n\n\n

Activate SVR.JS

\nYou will then be able to use all of SVR.JS features through SVR.JS Genuine Advantage!\n\n

Wait...

\n\n\n\nThis copy of SVR.JS is not genuine."); + } + return; + } catch (ex) { + callServerError(500, undefined, generateErrorStack(ex)); + return; + } + } else if (allowStatus && (href == "/svrjsstatus.svr" || (os.platform() == "win32" && href.toLowerCase() == "/svrjsstatus.svr"))) { + function formatRelativeTime(relativeTime) { + var days = Math.floor(relativeTime / 60 / (60 * 24)); + var dateDiff = new Date(relativeTime * 1000); + return days + " days, " + dateDiff.getUTCHours() + " hours, " + dateDiff.getUTCMinutes() + " minutes, " + dateDiff.getUTCSeconds() + " seconds"; + } + var hdhds = getCustomHeaders(); + hdhds["Content-Type"] = "text/html; charset=utf-8"; + res.writeHead(200, "OK", hdhds); + res.end((head == "" ? "SVR.JS status" + (request.headers.host == undefined ? "" : " for " + String(req.headers.host).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")) + "" : head.replace(//i, "SVR.JS status" + (request.headers.host == undefined ? "" : " for " + String(req.headers.host).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")) + "")) + "

SVR.JS status" + (request.headers.host == undefined ? "" : " for " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">")) + "

Server version: " + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + "

Current time: " + new Date().toString() + "
Thread start time: " + new Date(new Date() - (process.uptime() * 1000)).toString() + "
Thread uptime: " + formatRelativeTime(Math.floor(process.uptime())) + "
OS uptime: " + formatRelativeTime(os.uptime()) + "
Total request count: " + reqcounter + "
Average request rate: " + (Math.round((reqcounter / process.uptime()) * 100) / 100) + " requests/s" + (process.memoryUsage ? ("
Memory usage of thread: " + sizify(process.memoryUsage().rss) + "B") : "") + (process.cpuUsage ? ("
Total CPU usage by thread: u" + (process.cpuUsage().user / 1000) + "ms s" + (process.cpuUsage().system / 1000) + "ms - " + (Math.round((((process.cpuUsage().user + process.cpuUsage().system) / 1000000) / process.uptime()) * 1000) / 1000) + "%") : "") + "
Thread PID: " + process.pid + "
" + (foot == "" ? "" : foot)); + return; + } else if (href == "/zsoiebook.svr" || (os.platform() == "win32" && href.toLowerCase() == "/zsoiebook.svr")) { + var hdhds = getCustomHeaders(); + hdhds["Content-Type"] = "text/html; charset=utf-8"; + res.writeHead(200, "OK", hdhds); + if (typeof uobject.query.summary !== "undefined") { + res.end("\n\n \n The Summary of Book of ZSOiE\n \n \n \n \n \n
\n

And Satan created Mammon. His work won people from all over the school. When people abandoned them through the Piracy Window, so Satan went back in time and created the Server to continue to wreak havoc all over the school.

\n

from The Summary of Book of ZSOiE

\n
\n \n"); + return; + } + var randomValue = Math.random(); + if (randomValue > 0.85714) { + res.end("\n\n\n\n \n The Book of ZSOiE, 7:28\n \n \n \n \n \n
\n

The Server continues to cultivate it's Dafa. The Author found the Robot and asked him for help. Then the Robot started to help the Author to improve his Server. And the Author tries to create yet another server without using the main node...

\n

from The Book of ZSOiE, 7:28

\n
\n \n"); + } else if (randomValue > 0.71429) { + res.end("\n\n\n\n \n The Book of ZSOiE, 7:16\n \n \n \n \n \n
\n

The Server is still going. But the Author commanded to the Server: \"thou shalt you split to two branches.\". And the Server did split it's Dafa. One of two branches stopped serving on old and rusty node. Other one is still serving on that, but it will later vanish... \"Mammon will get confused\" - said the Author.

\n

from The Book of ZSOiE, 7:16

\n
\n \n"); + } else if (randomValue > 0.57143) { + res.end("\n\n\n\n \n The Book of ZSOiE, 7:2\n \n \n \n \n \n
\n

The old Server forces died. The all-powerful new Server rosen from ashes of old Server like phoenix followed the ways of Durability-Ease-Reliability and cultivated his Dafa. Then, the Author and Whyvn appeared on best former Mammon's disciples paper.

\n

from The Book of ZSOiE, 7:2

\n
\n \n"); + } else if (randomValue > 0.42857) { + res.end("\n\n\n\n \n The Book of ZSOiE, 6:24\n \n \n \n \n \n
\n

Mammon had enough karmic retribution. The Author tried it's Server on main node's substitute. Then, the Author saw, that Server's Dafa is good, and that main node, it's substitute, and older Mammon are good. Meanwhile the Author, Whyvn, and Snovbyn rejoiced even more from their success over older Mammon.

\n

from The Book of ZSOiE, 6:24

\n
\n \n"); + } else if (randomValue > 0.32143) { + res.end("\n\n\n\n \n The Book of ZSOiE, 6:6\n \n \n \n \n \n
\n

And the Server is about to come. The Author along with Whyvn and Snovbyn passing the Mammon's test rejoiced their success over older Mammon.

\n

from The Book of ZSOiE, 6:6

\n
\n \n"); + } else if (randomValue > 0.14286) { + res.end("\n\n\n\n \n The Book of ZSOiE, 5:25\n \n \n \n \n \n
\n

The twins of Mammon quarrelled. The Author with it's Server and it's main node plunged the Mammon's servers into darkness. Meanwhile Whyvn and Snovbyn helped him to break Mammon's servers.

\n

from The Book of ZSOiE, 5:25

\n
\n \n"); + } else { + res.end("\n\n\n\n \n The Book of ZSOiE, 3:16\n \n \n \n \n \n
\n

Mammon slept. Meanwhile, the Author, Whyvn and Snovbyn being in very skill-requiring challenge casted tcpdump and mongodb on him.

\n

from The Book of ZSOiE, 3:16

\n
\n \n"); + } + return; + } else if (version.indexOf("Nightly-") === 0 && (href == "/crash.svr" || (os.platform() == "win32" && href.toLowerCase() == "/crash.svr"))) { + throw new Error("Intentionally crashed"); + } + + var pth = decodeURIComponent(href).replace(/\/+/g, "/").substr(1); + fs.stat("./" + pth, function (err, stats) { + if (err) { + if (err.code == "ENOENT") { + callServerError(404); + serverconsole.errmessage("Resource not found."); + } else if (err.code == "EACCES") { + callServerError(403); + serverconsole.errmessage("Access denied."); + } else if (err.code == "EMFILE") { + callServerError(429); + } else if (err.code == "ELOOP") { + callServerError(508); + } else { + callServerError(500, undefined, generateErrorStack(err)); + } + return; + } + //Check if index file exists + if (req.url == "/" || stats.isDirectory()) { + fs.stat("./" + pth + "/.notindex".replace(/\/+/g, "/"), function (e) { + if (e) { + fs.stat(("./" + pth + "/index.html").replace(/\/+/g, "/"), function (e, s) { + if (e || !s.isFile()) { + fs.stat(("./" + pth + "/index.htm").replace(/\/+/g, "/"), function (e, s) { + if (e || !s.isFile()) { + fs.stat(("./" + pth + "/index.xhtml").replace(/\/+/g, "/"), function (e, s) { + if (e || !s.isFile()) { + properServe() + } else { + stats = s; + pth = (pth + "/index.xhtml").replace(/\/+/g, "/"); + ext = "xhtml"; + properServe(); + } + }); + } else { + stats = s; + pth = (pth + "/index.htm").replace(/\/+/g, "/"); + ext = "htm"; + properServe(); + } + }); + } else { + stats = s; + pth = (pth + "/index.html").replace(/\/+/g, "/"); + ext = "html"; + properServe(); + } + }); + } + }); + } else { + properServe(); + } + + function properServe() { + if (stats.isDirectory()) { + if (configJSON.enableDirectoryListing || configJSON.enableDirectoryListing === undefined) { + var dheaders = getCustomHeaders(); + dheaders["Content-Type"] = "text/html; charset=utf-8"; + res.writeHead(200, http.STATUS_CODES[200], dheaders); + var heada = fs.existsSync(("." + decodeURIComponent(href) + "/.dirhead").replace(/\/+/g, "/")) ? fs.readFileSync(("." + decodeURIComponent(href) + "/.dirhead").replace(/\/+/g, "/")).toString() : ((fs.existsSync(("." + decodeURIComponent(href) + "/HEAD.html").replace(/\/+/g, "/")) && (os.platform != "win32" || href != "/")) ? fs.readFileSync(("." + decodeURIComponent(href) + "/HEAD.html").replace(/\/+/g, "/")).toString() : ""); // header + var foota = fs.existsSync(("." + decodeURIComponent(href) + "/.dirfoot").replace(/\/+/g, "/")) ? fs.readFileSync(("." + decodeURIComponent(href) + "/.dirfoot").replace(/\/+/g, "/")).toString() : ((fs.existsSync(("." + decodeURIComponent(href) + "/FOOT.html").replace(/\/+/g, "/")) && (os.platform != "win32" || href != "/")) ? fs.readFileSync(("." + decodeURIComponent(href) + "/FOOT.html").replace(/\/+/g, "/")).toString() : ""); // footer + var htmlHead = (configJSON.enableDirectoryListingWithDefaultHead == undefined || configJSON.enableDirectoryListingWithDefaultHead == false || (fs.existsSync("./head.html") == false && fs.existsSync("./.head") == false) || head == "" || head == " " || head == "\r\n" || head == "\n" ? (heada.indexOf("") == -1 ? "Directory: " + decodeURIComponent(origHref).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "" : heada.replace("", "Directory: " + decodeURIComponent(origHref).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "")) : head.replace("", "Directory: " + decodeURIComponent(origHref).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + "")) + (heada.indexOf("") == -1 ? heada : "") + "

Directory: " + decodeURIComponent(origHref).replace(/&/g, "&").replace(//g, ">") + "

" + (checkLevel(decodeURIComponent(origHref)) < 1 ? "" : ""); + var htmlFoot = "
Filename Size Date
\"[RET]\"Return

" + (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + (req.headers.host == undefined ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">")) + "

" + foota + (configJSON.enableDirectoryListingWithDefaultHead == undefined || configJSON.enableDirectoryListingWithDefaultHead == false || (fs.existsSync("./foot.html") == false && fs.existsSync("./.foot") == false) || foot == "" || foot == " " || foot == "\r\n" || foot == "\n" ? "" : foot); + if (fs.existsSync(("." + req.url.split("?")[0] + "/.maindesc").replace(/\/+/g, "/"))) { + htmlFoot = "
" + fs.readFileSync(("." + req.url.split("?")[0] + "/.maindesc").replace(/\/+/g, "/")) + htmlFoot; + } + fs.readdir("." + decodeURIComponent(href), function (err, list) { + try { + if (err) throw err; + list = list.sort(); + + function getStatsForAllFilesI(fileList, callback, prefix, pushArray, index) { + if (fileList.length == 0) { + callback(pushArray); + return; + } + fs.stat((prefix + "/" + fileList[index]).replace(/\/+/g, "/"), function (err, stats) { + if (err) { + fs.lstat((prefix + "/" + fileList[index]).replace(/\/+/g, "/"), function (err, stats) { + if (err) { + pushArray.push({ + name: fileList[index], + stats: null, + errored: true + }); + if (index < fileList.length - 1) { + getStatsForAllFilesI(fileList, callback, prefix, pushArray, index + 1); + } else { + callback(pushArray); + } + } else { + pushArray.push({ + name: fileList[index], + stats: stats, + errored: true + }); + if (index < fileList.length - 1) { + getStatsForAllFilesI(fileList, callback, prefix, pushArray, index + 1); + } else { + callback(pushArray); + } + } + }); + } else { + pushArray.push({ + name: fileList[index], + stats: stats, + errored: false + }); + if (index < fileList.length - 1) { + getStatsForAllFilesI(fileList, callback, prefix, pushArray, index + 1); + } else { + callback(pushArray); + } + } + }); + } + + function getStatsForAllFiles(fileList, prefix, callback) { + if (!prefix) prefix = ""; + getStatsForAllFilesI(fileList, callback, prefix, [], 0); + } + + getStatsForAllFiles(list, "." + decodeURIComponent(href), function (filelist) { + function checkEXT(filename, ext) { + if (filename.length < ext.length) return false; + return (filename.toLowerCase().indexOf(ext) == (filename.length - ext.length)); + } + var statsa = []; + for (var i = 0; i < filelist.length; i++) { + if (filelist[i].name[0] !== ".") { + var estats = filelist[i].stats; + var ename = filelist[i].name; + if (filelist[i].errored) { + if (estats) { + statsa.push("[BAD]" + ename.replace(/&/g, "&").replace(//g, ">") + "-" + estats.mtime.toDateString() + "\r\n"); + } else { + statsa.push("[BAD]" + ename.replace(/&/g, "&").replace(//g, ">") + "--\r\n"); + } + + } else { + var entry = "\"[alt]\"" + ename.replace(/&/g, "&").replace(//g, ">") + "" + (estats.isDirectory() ? "-" : sizify(estats.size.toString())) + "" + estats.mtime.toDateString() + "\r\n"; + if (estats.isDirectory()) { + entry = entry.replace("[img]", "/.dirimages/directory.png").replace("[alt]", "[DIR]"); + } else if (!estats.isFile()) { + entry = "\"[alt]\"" + ename.replace(/&/g, "&").replace(//g, ">") + "-" + estats.mtime.toDateString() + "\r\n"; + if (estats.isBlockDevice()) { + entry = entry.replace("[img]", "/.dirimages/hwdevice.png").replace("[alt]", "[BLK]"); + } else if (estats.isCharacterDevice()) { + entry = entry.replace("[img]", "/.dirimages/hwdevice.png").replace("[alt]", "[CHR]"); + } else if (estats.isFIFO()) { + entry = entry.replace("[img]", "/.dirimages/fifo.png").replace("[alt]", "[FIF]"); + } else if (estats.isSocket()) { + entry = entry.replace("[img]", "/.dirimages/socket.png").replace("[alt]", "[SCK]"); + } + } else if ((/README/ig).test(ename) || (/LICEN[SC]E/ig).test(ename)) { + entry = entry.replace("[img]", "/.dirimages/important.png").replace("[alt]", "[IMP]"); + } else if (checkEXT(ename, ".html") || checkEXT(ename, ".htm") || checkEXT(ename, ".xml") || checkEXT(ename, ".xhtml") || checkEXT(ename, ".shtml")) { + entry = entry.replace("[img]", "/.dirimages/html.png").replace("[alt]", (checkEXT(ename, ".xml") ? "[XML]" : "[HTM]")); + } else if (checkEXT(ename, ".js")) { + entry = entry.replace("[img]", "/.dirimages/javascript.png").replace("[alt]", "[JS ]"); + } else if (checkEXT(ename, ".php")) { + entry = entry.replace("[img]", "/.dirimages/php.png").replace("[alt]", "[PHP]"); + } else if (checkEXT(ename, ".css")) { + entry = entry.replace("[img]", "/.dirimages/css.png").replace("[alt]", "[CSS]"); + } else if (checkEXT(ename, ".png") || checkEXT(ename, ".jpg") || checkEXT(ename, ".gif") || checkEXT(ename, ".bmp") || checkEXT(ename, ".webm") || checkEXT(ename, ".jpeg") || checkEXT(ename, ".svg") || checkEXT(ename, ".jfif") || checkEXT(ename, ".webp")) { + entry = entry.replace("[img]", "/.dirimages/image.png").replace("[alt]", "[IMG]"); + } else if (checkEXT(ename, ".ico") || checkEXT(ename, ".icn")) { + entry = entry.replace("[img]", "/.dirimages/image.png").replace("[alt]", "[ICO]"); + } else if (checkEXT(ename, ".ttf") || checkEXT(ename, ".otf") || checkEXT(ename, ".fon")) { + entry = entry.replace("[img]", "/.dirimages/font.png").replace("[alt]", "[FON]"); + } else if (checkEXT(ename, ".mp3") || checkEXT(ename, ".ogg") || checkEXT(ename, ".aac") || checkEXT(ename, ".wav") || checkEXT(ename, ".mid") || checkEXT(ename, ".midi") || checkEXT(ename, ".mka")) { + entry = entry.replace("[img]", "/.dirimages/audio.png").replace("[alt]", "[AUD]"); + } else if (checkEXT(ename, ".txt") || checkEXT(ename, ".log") || checkEXT(ename, ".json")) { + entry = entry.replace("[img]", "/.dirimages/text.png").replace("[alt]", (checkEXT(ename, ".json") ? "[JSO]" : "[TXT]")); + } else if (checkEXT(ename, ".mp5") || checkEXT(ename, ".avi") || checkEXT(ename, ".mkv") || checkEXT(ename, ".mov") || checkEXT(ename, ".mp2") || checkEXT(ename, ".mp4") || checkEXT(ename, ".ogv")) { + entry = entry.replace("[img]", "/.dirimages/video.png").replace("[alt]", "[VID]"); + } else if (checkEXT(ename, ".zip") || checkEXT(ename, ".rar") || checkEXT(ename, ".bz2") || checkEXT(ename, ".gz") || checkEXT(ename, ".bz") || checkEXT(ename, ".7z") || checkEXT(ename, ".xz") || checkEXT(ename, ".lzma") || checkEXT(ename, ".tar")) { + entry = entry.replace("[img]", "/.dirimages/archive.png").replace("[alt]", "[ARC]"); + } else if (checkEXT(ename, ".img") || checkEXT(ename, ".dmg") || checkEXT(ename, ".iso") || checkEXT(ename, ".flp")) { + entry = entry.replace("[img]", "/.dirimages/diskimage.png").replace("[alt]", "[DSK]"); + } else { + entry = entry.replace("[img]", "/.dirimages/other.png").replace("[alt]", "[OTH]"); + } + statsa.push(entry); + } + } + } + if (statsa.length == 0) { + statsa.push("No files found"); + } + res.end(htmlHead + statsa.join("") + htmlFoot); + serverconsole.resmessage("Client successfully recieved content."); + }); + } catch (ex) { + if (ex.code == "ENOENT") { + callServerError(404); + serverconsole.errmessage("Resource not found."); + } else if (ex.code == "EACCES") { + callServerError(403); + serverconsole.errmessage("Access denied."); + } else if (ex.code == "EMFILE") { + callServerError(429); + } else if (ex.code == "ELOOP") { + callServerError(508); + } else { + callServerError(500, undefined, generateErrorStack(ex)); + } + } + }); + } else { + callServerError(403); + serverconsole.errmessage("Directory listing disabled."); + return; + } + } else { + var acceptEncoding = req.headers["accept-encoding"]; + if (!acceptEncoding) acceptEncoding = ""; + + // Check if the requested file exists and handle errors + fs.stat("./" + pth, function (err, stats) { + if (err) { + if (err.code == "ENOENT") { + callServerError(404); + serverconsole.errmessage("Resource not found."); + } else if (err.code == "EACCES") { + callServerError(403); + serverconsole.errmessage("Access denied."); + } else if (err.code == "EMFILE") { + callServerError(429); + } else if (err.code == "ELOOP") { + callServerError(508); + } else { + callServerError(500, undefined, generateErrorStack(err)); + } + return; + } + + // Check if the requested resource is a directory + if (stats.isDirectory()) { + callServerError(501); + serverconsole.errmessage("SVR.JS expected file but got directory instead."); + return; + } else if (!stats.isFile()) { + callServerError(501); + serverconsole.errmessage("SVR.JS doesn't support block devices, character devices, FIFOs nor sockets."); + return; + } + + var filelen = stats.size; + + // Helper function to check if compression is allowed for the file + function canCompress(path, list) { + var canCompress = true; + for (var i = 0; i < list.length; i++) { + if (createRegex(list[i]).test(path)) { + canCompress = false; + break; + } + } + return canCompress; + } + + var isCompressable = canCompress(href, dontCompress); + + // Check for browser quirks and adjust compression accordingly + if (ext != "html" && ext != "htm" && ext != "xhtml" && ext != "xht" && ext != "shtml" && /^Mozilla\/4\.[0-9]+(( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test(req.headers["user-agent"]) && !(/https?:\/\/|[bB][oO][tT]|[sS][pP][iI][dD][eE][rR]|[sS][uU][rR][vV][eE][yY]|MSI[E]/.test(req.headers["user-agent"]))) { + isCompressable = false; //Netscape 4.x doesn't handle compressed data properly outside of HTML documents. + } else if (/^Mozilla\/4\.0[6-8](( *\[[^)]*\] *| *)\([^)\]]*\))? *$/.test(req.headers["user-agent"]) && !(/https?:\/\/|[bB][oO][tT]|[sS][pP][iI][dD][eE][rR]|[sS][uU][rR][vV][eE][yY]|MSI[E]/.test(req.headers["user-agent"]))) { + isCompressable = false; //Netscape 4.06-4.08 doesn't handle compressed data properly. + } else if (ext != "html" && ext != "htm" && ext != "xhtml" && ext != "xht" && ext != "shtml" && /^w3m\/[^ ]*$/.test(req.headers["user-agent"])) { + isCompressable = false; //w3m doesn't handle compressed data properly outside of HTML documents. + } + + // Handle partial content request + if (ext != "html" && req.headers["range"]) { + try { + if (err) throw err; + var rhd = getCustomHeaders(); + rhd["Accept-Ranges"] = "bytes"; + rhd["Content-Range"] = "bytes */" + filelen; + var regexmatch = req.headers["range"].match(/bytes=([0-9]*)-([0-9]*)/); + if (!regexmatch) { + callServerError(416, undefined, undefined, rhd); + } else { + // Process the partial content request + var beginOrig = regexmatch[1]; + var endOrig = regexmatch[2]; + var begin = 0; + var end = filelen - 1; + if (beginOrig == "" && endOrig == "") { + callServerError(416, undefined, undefined, rhd); + return; + } else if (beginOrig == "") { + begin = end - parseInt(endOrig) + 1; + } else { + begin = parseInt(beginOrig); + if (endOrig != "") end = parseInt(endOrig); + } + if (begin > end || begin < 0 || begin > filelen - 1) { + callServerError(416, undefined, undefined, rhd); + return; + } + if (end > filelen - 1) end = filelen - 1; + rhd["Content-Range"] = "bytes " + begin + "-" + end + "/" + filelen; + rhd["Content-Length"] = end - begin + 1; + if (!(mime.contentType(ext) == false) && ext != "") rhd["Content-Type"] = mime.contentType(ext); + + if (req.method != "HEAD") { + var readStream = fs.createReadStream("./" + pth, { + start: begin, + end: end + }); + readStream.on("error", function (err) { + if (err.code == "ENOENT") { + callServerError(404); + serverconsole.errmessage("Resource not found."); + } else if (err.code == "EACCES") { + callServerError(403); + serverconsole.errmessage("Access denied."); + } else if (err.code == "EMFILE") { + callServerError(429); + } else if (err.code == "ELOOP") { + callServerError(508); + } else { + callServerError(500, undefined, generateErrorStack(err)); + } + }).on("open", function () { + try { + res.writeHead(206, http.STATUS_CODES[206], rhd); + readStream.pipe(res); + serverconsole.resmessage("Client successfully received content."); + } catch (ex) { + callServerError(500, undefined, generateErrorStack(ex)); + } + }); + } else { + res.writeHead(206, http.STATUS_CODES[206], rhd); + res.end(); + } + } + } catch (ex) { + callServerError(500, undefined, generateErrorStack(ex)); + } + } else { + try { + if (err) throw err; + var hdhds = getCustomHeaders(); + if (configJSON.enableCompression === true && ext != "br" && filelen > 256 && isCompressable && zlib.createBrotliCompress && acceptEncoding.match(/\bbr\b/)) { + hdhds["Content-Encoding"] = "br"; + } else if (configJSON.enableCompression === true && ext != "zip" && filelen > 256 && isCompressable && acceptEncoding.match(/\bdeflate\b/)) { + hdhds["Content-Encoding"] = "deflate"; + } else if (configJSON.enableCompression === true && ext != "gz" && filelen > 256 && isCompressable && acceptEncoding.match(/\bgzip\b/)) { + hdhds["Content-Encoding"] = "gzip"; + } else { + if (ext == "html") { + hdhds["Content-Length"] = head.length + filelen + foot.length; + } else { + hdhds["Content-Length"] = filelen; + } + } + if (ext != "html") hdhds["Accept-Ranges"] = "bytes"; + delete hdhds["Content-Type"]; + if (!(mime.contentType(ext) == false) && ext != "") hdhds["Content-Type"] = mime.contentType(ext); + + if (req.method != "HEAD") { + var readStream = fs.createReadStream("./" + pth); + readStream.on("error", function (ex) { + if (ex.code == "ENOENT") { + callServerError(404); + serverconsole.errmessage("Resource not found."); + } else if (ex.code == "EACCES") { + callServerError(403); + serverconsole.errmessage("Access denied."); + } else if (ex.code == "EMFILE") { + callServerError(429); + } else if (ex.code == "ELOOP") { + callServerError(508); + } else { + callServerError(500, undefined, generateErrorStack(ex)); + } + }).on("open", function () { + try { + res.writeHead(200, http.STATUS_CODES[200], hdhds); + var resStream = {}; + if (configJSON.enableCompression === true && ext != "br" && filelen > 256 && isCompressable && zlib.createBrotliCompress && acceptEncoding.match(/\bbr\b/)) { + resStream = zlib.createBrotliCompress(); + resStream.pipe(res); + } else if (configJSON.enableCompression === true && ext != "zip" && filelen > 256 && isCompressable && acceptEncoding.match(/\bdeflate\b/)) { + resStream = zlib.createDeflateRaw(); + resStream.pipe(res); + } else if (configJSON.enableCompression === true && ext != "gz" && filelen > 256 && isCompressable && acceptEncoding.match(/\bgzip\b/)) { + resStream = zlib.createGzip(); + resStream.pipe(res); + } else { + resStream = res; + } + if (ext == "html") { + function afterWriteCallback() { + readStream.on("end", function () { + resStream.end(foot); + }); + readStream.pipe(resStream, { + end: false + }); + } + if (!resStream.write(head)) { + resStream.on("drain", afterWriteCallback); + } else { + process.nextTick(afterWriteCallback); + } + } else { + readStream.pipe(resStream); + } + serverconsole.resmessage("Client successfully received content."); + } catch (ex) { + callServerError(500, undefined, generateErrorStack(ex)); + } + }); + } else { + res.writeHead(200, http.STATUS_CODES[200], hdhds); + res.end(); + serverconsole.resmessage("Client successfully received content."); + } + } catch (ex) { + callServerError(500, undefined, generateErrorStack(ex)); + } + } + }); + } + } + }); + }; + } + // } + + try { + + //scan blacklist + if (blacklist.check(reqip) && href != "/favicon.ico") { + var bheaders = getCustomHeaders(); + bheaders["Content-Type"] = "text/html; charset=utf8"; + response.writeHead(403, "Client blocked", bheaders); + response.write("Access denied - SVR.JS

ACCESS DENIED

Request from " + reqip + " is denied. The client is now in the blacklist.

SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" + (req.headers.host == undefined ? "" : " on " + String(req.headers.host).replace(/&/g, "&").replace(//g, ">")) + "

"); + serverconsole.errmessage("Client blocked"); + response.end(); + return; + } + + if (req.url == "*") { + if (req.method == "OPTIONS") { + var hdss = getCustomHeaders(); + hdss["Allow"] = "GET, POST, HEAD, OPTIONS"; + res.writeHead(204, "No Content", hdss); + res.end(); + return; + } else { + callServerError(400); + return; + } + } + + if (req.method == "CONNECT") { + callServerError(501); + serverconsole.errmessage("CONNECT requests aren't supported. Your JS runtime probably doesn't support 'connect' handler for HTTP library."); + return; + } + + //SANITIZE URL + var sanitizedHref = sanitizeURL(href); + + if (href.toLowerCase() != sanitizedHref.toLowerCase() && !isProxy) { + var sanitizedURL = uobject; + sanitizedURL.path = null; + sanitizedURL.href = null; + sanitizedURL.pathname = sanitizedHref; + sanitizedURL.hostname = null; + sanitizedURL.host = null; + sanitizedURL.port = null; + sanitizedURL.protocol = null; + sanitizedURL.slashes = null; + sanitizedURL = url.format(sanitizedURL); + serverconsole.resmessage("URL sanitized: " + req.url + " => " + sanitizedURL); + redirect(sanitizedURL, false); + return; + } + //URL REWRITING + + function rewriteURL(address, map) { + var rewrittenAddress = address; + for (var i = 0; i < map.length; i++) { + if (createRegex(map[i].definingRegex).test(address)) { + for (var j = 0; j < map[i].replacements.length; j++) { + rewrittenAddress = rewrittenAddress.replace(createRegex(map[i].replacements[j].regex), map[i].replacements[j].replacement); + } + if (map[i].append) rewrittenAddress += map[i].append; + break; + } + } + return rewrittenAddress; + } + var origHref = href; + if (!isProxy) { + var rewrittenURL = rewriteURL(req.url, rewriteMap); + if (rewrittenURL != req.url) { + serverconsole.resmessage("URL rewritten: " + req.url + " => " + rewrittenURL); + req.url = rewrittenURL; + uobject = urlParse(req.url); + search = uobject.search; + href = uobject.pathname; + ext = path.extname(href).toLowerCase(); + ext = ext.substr(1, ext.length); + + try { + decodedHref = decodeURIComponent(href); + } catch (ex) { + //Return 400 error + callServerError(400); + serverconsole.errmessage("Bad request!"); + return; + } + + var sHref = sanitizeURL(href); + if (sHref != href.replace(/\/\.(?=\/|$)/g, "/").replace(/\/+/g, "/")) { + callServerError(403); + serverconsole.errmessage("Content blocked."); + return; + } else if (sHref != href) { + var rewrittenAgainURL = uobject; + rewrittenAgainURL.path = null; + rewrittenAgainURL.href = null; + rewrittenAgainURL.pathname = sHref; + rewrittenAgainURL = url.format(rewrittenAgainURL); + serverconsole.resmessage("URL sanitized: " + req.url + " => " + rewrittenAgainURL); + req.url = rewrittenAgainURL; + uobject = urlParse(req.url); + search = uobject.search; + href = uobject.pathname; + ext = path.extname(href).toLowerCase(); + ext = ext.substr(1, ext.length); + try { + decodedHref = decodeURIComponent(href); + } catch (ex) { + //Return 400 error + callServerError(400); + serverconsole.errmessage("Bad request!"); + return; + } + } + } + } + if (!isProxy) { + reqcounter++; + var hkh = getCustomHeaders(); + var hk = Object.keys(hkh); + for (var i = 0; i < hk.length; i++) { + try { + response.setHeader(hk[i], hkh[hk[i]]); + } catch (ex) { + //Headers will not be set. + } + } + } + if ((checkIfForbiddenPath(decodedHref, "config") || checkIfForbiddenPath(decodedHref, "certificates")) && !isProxy) { + callServerError(403); + serverconsole.errmessage("Access to configuration file/certificates is denied."); + return; + } else if (checkIfIndexOfForbiddenPath(decodedHref, "log") && !isProxy && (configJSON.enableLogging || configJSON.enableLogging == undefined) && !(configJSON.enableRemoteLogBrowsing || configJSON.enableRemoteLogBrowsing == undefined)) { + callServerError(403); + serverconsole.errmessage("Access to log files is denied."); + return; + } else if (checkIfForbiddenPath(decodedHref, "svrjs") && !isProxy && !exposeServerVersion && process.cwd() == __dirname) { + callServerError(403); + serverconsole.errmessage("Access to SVR.JS script is denied."); + return; + } else if ((checkIfForbiddenPath(decodedHref, "svrjs") || checkIfForbiddenPath(decodedHref, "serverSideScripts") || checkIfIndexOfForbiddenPath(decodedHref, "serverSideScriptDirectories")) && !isProxy && (configJSON.disableServerSideScriptExpose && configJSON.disableServerSideScriptExpose != undefined)) { + callServerError(403); + serverconsole.errmessage("Access to sources is denied."); + return; + } else { + var nonscodeIndex = -1; + var authIndex = -1; + var regexI = []; + if (!isProxy && nonStandardCodes != undefined) { + for (var i = 0; i < nonStandardCodes.length; i++) { + var mth = false; + if (nonStandardCodes[i].regex) { + var regexObj = nonStandardCodes[i].regex.split("/"); + if (regexObj.length == 0) throw new Error("Invalid regex!"); + var modifiers = regexObj.pop(); + if (!modifiers.match(/i/i) && os.platform() == "win32") modifiers += "i"; + regexObj.shift(); + var searchString = regexObj.join("/"); + var rx = RegExp(searchString, modifiers); + mth = req.url.match(rx) || href.match(rx); + regexI.push(rx); + } else { + mth = nonStandardCodes[i].url == href || (os.platform() == "win32" && nonStandardCodes[i].url.toLowerCase() == href.toLowerCase()); + } + if (mth) { + if (nonStandardCodes[i].scode == 401) { + if (authIndex == -1) { + authIndex = i; + } + } else { + if (nonscodeIndex == -1) { + if ((nonStandardCodes[i].scode == 403 || nonStandardCodes[i].scode == 451) && nonStandardCodes[i].users !== undefined) { + var lpk = false; + if (nonStandardCodes[i].users.check(reqip)) { + nonscodeIndex = i; + lpk = true; + } + if (lpk) break; + } else { + nonscodeIndex = i; + } + } + } + } + } + } + + if (nonscodeIndex > -1) { + var nonscode = nonStandardCodes[nonscodeIndex]; + if (nonscode.scode == 301 || nonscode.scode == 302) { + var location = ""; + if (regexI[nonscodeIndex]) { + location = req.url.replace(regexI[nonscodeIndex], nonscode.location); + } else if (req.url.split("?")[1] == undefined || req.url.split("?")[1] == null || req.url.split("?")[1] == "" || req.url.split("?")[1] == " ") { + location = nonscode.location; + } else { + location = nonscode.location + "?" + req.url.split("?")[1]; + } + redirect(location, nonscode.scode == 302); + return; + } else if (nonscode.scode == 403) { + callServerError(403); + serverconsole.errmessage("Content blocked."); + return; + } else if (nonscode.scode == 410) { + callServerError(410); + serverconsole.errmessage("Content is gone."); + return; + } else if (nonscode.scode == 418) { + callServerError(418); + serverconsole.errmessage("SVR.JS is always a teapot ;)"); + return; + } else { + callServerError(nonscode.scode); + serverconsole.errmessage("Client fails recieving content."); + return; + } + } + if (authIndex > -1) { + var authcode = nonStandardCodes[authIndex]; + + function authorizedCallback(bruteProtection) { + var ha = getCustomHeaders(); + ha["WWW-Authenticate"] = "Basic realm=\"" + (authcode.realm ? authcode.realm.replace(/(\\|")/g, "\\$1") : "SVR.JS HTTP Basic Authorization") + "\", charset=\"UTF-8\""; + var credentials = req.headers["authorization"]; + if (!credentials) { + callServerError(401, undefined, undefined, ha); + serverconsole.errmessage("Content needs authorization."); + return; + } + var cmatch = credentials.match(/^Basic (.+)$/); + if (!cmatch) { + callServerError(401, undefined, undefined, ha); + serverconsole.errmessage("Malformed credentials."); + return; + } + var c2 = Buffer.from(cmatch[1], "base64").toString("utf8"); + var c2match = c2.match(/^([^:]*):(.*)$/); + if (!c2match) { + callServerError(401, undefined, undefined, ha); + serverconsole.errmessage("Malformed credentials."); + return; + } + var username = c2match[1]; + var password = c2match[2]; + var authorized = false; + for (var i = 0; i < users.length; i++) { + var hash = sha256(password + users[i].salt); + if (users[i].name == username && users[i].pass == hash) { + authorized = true; + break; + } + } + if (!authorized) { + if (bruteProtection) { + if (process.send) { + process.send("\x12AUTHW" + reqip); + } else { + if (!bruteForceDb[reqip]) bruteForceDb[reqip] = { + invalidAttempts: 0 + }; + bruteForceDb[reqip].invalidAttempts++; + if (bruteForceDb[reqip].invalidAttempts >= 10) { + bruteForceDb[reqip].lastAttemptDate = new Date(); + } + } + } + callServerError(401, undefined, undefined, ha); + serverconsole.errmessage("User " + username + " failed to log in."); + } else { + if (bruteProtection) { + if (process.send) { + process.send("\x12AUTHR" + reqip); + } else { + if (bruteForceDb[reqip]) bruteForceDb[reqip] = { + invalidAttempts: 0 + }; + } + } + modExecute(mods, vres(req, res, serverconsole, responseEnd, href, ext, uobject, search, "index.html", users, page404, head, foot, fd, callServerError, getCustomHeaders, origHref, redirect, parsePostData)); + } + } + if (authcode.disableBruteProtection) { + authorizedCallback(false); + } else if (!process.send) { + if (!bruteForceDb[reqip] || !bruteForceDb[reqip].lastAttemptDate || (new Date() - 300000 >= bruteForceDb[reqip].lastAttemptDate)) { + if (bruteForceDb[reqip] && bruteForceDb[reqip].invalidAttempts >= 10) bruteForceDb[reqip] = { + invalidAttempts: 5 + }; + authorizedCallback(true); + } else { + callServerError(429); + serverconsole.errmessage("Brute force limit reached!"); + } + } else { + var listenerEmitted = false; + + function authMessageListener(message) { + if (listenerEmitted) return; + if (message == "\x14AUTHA" + reqip || message == "\x14AUTHD" + reqip) { + process.removeListener("message", authMessageListener); + listenerEmitted = true; + } + if (message == "\x14AUTHD" + reqip) { + callServerError(429); + serverconsole.errmessage("Brute force limit reached!"); + } else if (message == "\x14AUTHA" + reqip) { + authorizedCallback(true); + } + } + process.on("message", authMessageListener); + process.send("\x12AUTHQ" + reqip); + } + } else { + modExecute(mods, vres(req, res, serverconsole, responseEnd, href, ext, uobject, search, "index.html", users, page404, head, foot, fd, callServerError, getCustomHeaders, origHref, redirect, parsePostData)); + } + } + } catch (ex) { + //CRASH HANDLER + if (ex.message == "Intentionally crashed") throw ex; //If intentionally crashed, then crash SVR.JS + callServerError(500, undefined, generateErrorStack(ex)); //Else just return 500 error + } + } + + } + //Listen port to server + server.on("error", function (err) { + if (err.code == "EADDRINUSE" || err.code == "EADDRNOTAVAIL" || err.code == "EACCES") { + attmts--; + if (cluster.isMaster === undefined) { + if (err.code == "EADDRINUSE") { + serverconsole.locerrmessage("Address in use by another process."); + } else if (err.code == "EADDRNOTAVAIL") { + serverconsole.locerrmessage("Address not available."); + } else if (err.code == "EACCES") { + serverconsole.locerrmessage("Access denied."); + } + serverconsole.locmessage(attmts + " attempts left."); + } else { + process.send("\x12ERRLIST" + attmts + err.code); + } + if (attmts > 0) { + server2.close(); + setTimeout(start, 900); + } else { + if (cluster.isMaster !== undefined) process.send("\x12" + err.code); + process.exit(errors[err.code]); + } + } else { + serverconsole.locerrmessage("There was a problem starting SVR.JS!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(generateErrorStack(err)); + if (cluster.isMaster !== undefined) process.send("\x12CRASH"); + process.exit(err.code ? errors[err.code] : 1); + } + }); + + server.once("listening", function () { + listeningMessage(); + }); +} + +function listenConnListener(msg) { + if (msg == "\x12LISTEN") { + listeningMessage(); + } +} + +function bruteForceListenerWrapper(worker) { + return function bruteForceListener(message) { + var ip = ""; + if (message.substr(0, 6) == "\x12AUTHQ") { + ip = message.substr(6); + if (!bruteForceDb[ip] || !bruteForceDb[ip].lastAttemptDate || (new Date() - 300000 >= bruteForceDb[ip].lastAttemptDate)) { + if (bruteForceDb[ip] && bruteForceDb[ip].invalidAttempts >= 10) bruteForceDb[ip] = { + invalidAttempts: 5 + }; + worker.send("\x14AUTHA" + ip); + } else { + worker.send("\x14AUTHD" + ip); + } + } else if (message.substr(0, 6) == "\x12AUTHR") { + ip = message.substr(6); + if (bruteForceDb[ip]) bruteForceDb[ip] = { + invalidAttempts: 0 + }; + } else if (message.substr(0, 6) == "\x12AUTHW") { + ip = message.substr(6); + if (!bruteForceDb[ip]) bruteForceDb[ip] = { + invalidAttempts: 0 + }; + bruteForceDb[ip].invalidAttempts++; + if (bruteForceDb[ip].invalidAttempts >= 10) { + bruteForceDb[ip].lastAttemptDate = new Date(); + } + } + }; +} + +function msgListener(msg) { + for (var i = 0; i < Object.keys(cluster.workers).length; i++) { + if (msg == "\x12END") { + cluster.workers[Object.keys(cluster.workers)[i]].removeAllListeners("message"); + cluster.workers[Object.keys(cluster.workers)[i]].on("message", bruteForceListenerWrapper(cluster.workers[Object.keys(cluster.workers)[i]])); + cluster.workers[Object.keys(cluster.workers)[i]].on("message", listenConnListener); + } + } + if (msg == "\x12CLOSE") { + closedMaster = true; + } else if (msg == "\x12LISTEN" || msg.substr(0, 4) == "\x12AUTH") { + //Do nothing! + } else if (msg == "\x12SAVEGOOD") { + serverconsole.locmessage("Configuration saved."); + } else if (msg.indexOf("\x12SAVEERR") == 0) { + serverconsole.locwarnmessage("There was a problem, while saving configuration file. Reason: " + msg.substr(8)); + } else if (msg == "\x12OPEN") { + closedMaster = false; + } else if (msg == "\x12END") { + cluster.workers[Object.keys(cluster.workers)[0]].on("message", function (msg) { + if (msg.length > 9 && msg.indexOf("\x12ERRLIST") == 0) { + var tries = parseInt(msg.substr(8, 1)); + var errCode = msg.substr(9); + if (errCode == "EADDRINUSE") { + serverconsole.locerrmessage("Address in use by another process."); + } else if (errCode == "EADDRNOTAVAIL") { + serverconsole.locerrmessage("Address not available."); + } else if (errCode == "EACCES") { + serverconsole.locerrmessage("Access denied."); + } + serverconsole.locmessage(tries + " attempts left."); + } + if (msg == "\x12CRASH") process.exit(1); + if (msg == "\x12EADDRINUSE" || msg == "\x12EADDRNOTAVAIL" || msg == "\x12EACCES") process.exit(errors[msg.substr(1)]); + }); + } else { + serverconsole.climessage(msg); + } +} + +var messageTransmitted = false; + +function listeningMessage() { + if (messageTransmitted) return; + messageTransmitted = true; + if (!cluster.isMaster && cluster.isMaster !== undefined) { + process.send("\x12LISTEN"); + return; + } + serverconsole.locmessage("Started server at: "); + if (secure) serverconsole.locmessage("* https://localhost" + (sport == 443 ? "" : (":" + sport))); + if (!(secure && disableNonEncryptedServer)) serverconsole.locmessage("* http://localhost" + (port == 80 ? "" : (":" + port))); + if (host != "" && host != "[offline]") { + if (secure) serverconsole.locmessage("* https://" + (host.indexOf(":") > -1 ? "[" + host + "]" : host) + (sport == 443 ? "" : (":" + sport))); + if (!(secure && disableNonEncryptedServer)) serverconsole.locmessage("* http://" + (host.indexOf(":") > -1 ? "[" + host + "]" : host) + (port == 80 ? "" : (":" + port))); + } + ipStatusCallback(function () { + if (pubip != "") { + if (secure) serverconsole.locmessage("* https://" + (pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip) + (spubport == 443 ? "" : (":" + spubport))); + if (!(secure && disableNonEncryptedServer)) serverconsole.locmessage("* http://" + (pubip.indexOf(":") > -1 ? "[" + pubip + "]" : pubip) + (pubport == 80 ? "" : (":" + pubport))); + } + if (domain != "") { + if (secure) serverconsole.locmessage("* https://" + domain + (spubport == 443 ? "" : (":" + spubport))); + if (!(secure && disableNonEncryptedServer)) serverconsole.locmessage("* http://" + domain + (pubport == 80 ? "" : (":" + pubport))); + } + serverconsole.locmessage("For CLI help type \"help\""); + }); +} + +var closedMaster = false; + +function start(init) { + init = Boolean(init); + if (cluster.isMaster || cluster.isMaster === undefined) { + if (init) { + for (i = 0; i < logo.length; i++) console.log(logo[i]); //Print logo + console.log(); + console.log("Welcome to DorianTech SVR.JS server."); + if (version.indexOf("Nightly-") === 0) serverconsole.locwarnmessage("This version is only for test purposes and may be unstable."); + if (vnum <= 57 && JSON.stringify(rewriteMap) != "[]") serverconsole.locwarnmessage("Some URL rewriting regexes will not work in Node.JS 8.x and earlier."); + if (http2.__disabled__ !== undefined) serverconsole.locwarnmessage("HTTP/2 isn't supported by your Node.JS version!"); + if (process.isBun) serverconsole.locwarnmessage("Bun support is experimental."); + if (cluster.isMaster === undefined) serverconsole.locwarnmessage("You're running SVR.JS on single thread. Reliability may suffer."); + if (crypto.__disabled__ !== undefined) serverconsole.locwarnmessage("Your Node.JS version doesn't have crypto support!"); + if (!process.isBun && process.version == "v8.5.0") serverconsole.locwarnmessage("Your Node.JS version is vulnerable to path validation vulnerability (CVE-2017-14849)."); + if (process.getuid && process.getuid() == 0) serverconsole.locwarnmessage("You're running SVR.JS as root. It's recommended to run SVR.JS as an non-root user."); + if (secure && process.versions && process.versions.openssl && process.versions.openssl.substr(0, 2) == "1.") { + if (new Date() > new Date("11 September 2023")) { + serverconsole.locwarnmessage("OpenSSL 1.x is no longer recieving security updates after 11th September 2023. Your HTTPS communication might be vulnerable."); + } else { + serverconsole.locwarnmessage("OpenSSL 1.x will no longer recieve security updates after 11th September 2023. Your HTTPS communication might be vulnerable in future."); + } + } + if (secure && configJSON.enableOCSPStapling && ocsp._errored) serverconsole.locwarnmessage("Can't load OCSP module. OCSP stapling will be disabled"); + if (vnum < 64) serverconsole.locwarnmessage("SVR.JS 3.5.0 and newer are no longer supported on Node.JS 8.x and 9.x"); + if (disableMods) serverconsole.locwarnmessage("SVR.JS is running without mods and server-side JavaScript enabled."); + console.log(); + serverconsole.locmessage("Server version: " + version); + if (process.isBun) serverconsole.locmessage("Bun version: v" + process.versions.bun); + else serverconsole.locmessage("Node.JS version: " + process.version); + var CPUs = os.cpus(); + if (CPUs.length > 0) serverconsole.locmessage("CPU: " + (CPUs.length > 1 ? CPUs.length + "x " : "") + CPUs[0].model); + if (vnum < 57) { + throw new Error("SVR.JS requires Node.JS 8.4.0 and newer, but your Node.JS version isn't supported by SVR.JS."); + } + } + if (!(secure && disableNonEncryptedServer)) serverconsole.locmessage("Starting HTTP server at localhost:" + port.toString() + "..."); + if (secure) serverconsole.locmessage("Starting HTTPS server at localhost:" + sport.toString() + "..."); + } + + + if (!cluster.isMaster) { + if (secure) { + server.listen(sport); + if (!disableNonEncryptedServer) server2.listen(port); + } else { + server.listen(port); + } + } + + + var commands = { + close: function () { + try { + server.close(); + if (secure && !disableNonEncryptedServer) { + server2.close(); + } + if (cluster.isMaster === undefined) serverconsole.climessage("Server closed."); + else { + process.send("Server closed."); + process.send("\x12CLOSE"); + } + } catch (ex) { + if (cluster.isMaster === undefined) serverconsole.climessage("Cannot close server! Reason: " + ex.message); + else process.send("Cannot close server! Reason: " + ex.message); + } + }, + open: function () { + try { + if (secure) { + server.listen(sport); + if (!disableNonEncryptedServer) server2.listen(port); + } else { + server.listen(port); // ReOpen Server + } + if (cluster.isMaster === undefined) serverconsole.climessage("Server opened."); + else { + process.send("Server opened."); + process.send("\x12OPEN"); + } + } catch (ex) { + if (cluster.isMaster === undefined) serverconsole.climessage("Cannot open server! Reason: " + ex.message); + else process.send("Cannot open server! Reason: " + ex.message); + } + }, + help: function () { + if (cluster.isMaster === undefined) serverconsole.climessage("Server commands:\n" + Object.keys(commands).join(" ")); + else process.send("Server commands:\n" + Object.keys(commands).join(" ")); + }, + mods: function () { + if (cluster.isMaster === undefined) serverconsole.climessage("Mods:"); + else process.send("Mods:"); + for (var i = 0; i < modInfos.length; i++) { + if (cluster.isMaster === undefined) serverconsole.climessage((i + 1).toString() + ". " + modInfos[i].name + " " + modInfos[i].version); + else process.send((i + 1).toString() + ". " + modInfos[i].name + " " + modInfos[i].version); + } + if (modInfos.length == 0) { + if (cluster.isMaster === undefined) serverconsole.climessage("No mods installed."); + else process.send("No mods installed."); + } + }, + stop: function (retcode) { + if (typeof retcode == "number") { + process.exit(retcode); + } else { + process.exit(0); + } + }, + clear: function () { + console.clear(); + }, + block: function (ip) { + if (ip == undefined || JSON.stringify(ip) == "[]") { + if (cluster.isMaster === undefined) serverconsole.climessage("Cannot block non-existent IP."); + else if (!cluster.isMaster) process.send("Cannot block non-existent IP."); + } else { + for (var i = 0; i < ip.length; i++) { + if (ip[i].indexOf(":") == -1) { + ip[i] = "::ffff:" + ip[i]; + } + if (!blacklist.check(ip[i])) { + blacklist.add(ip[i]); + } + } + if (cluster.isMaster === undefined) serverconsole.climessage("IPs successfully blocked."); + else if (!cluster.isMaster) process.send("IPs successfully blocked."); + } + }, + unblock: function (ip) { + if (ip == undefined || JSON.stringify(ip) == "[]") { + if (cluster.isMaster === undefined) serverconsole.climessage("Cannot unblock non-existent IP."); + else if (!cluster.isMaster) process.send("Cannot unblock non-existent IP."); + } else { + for (var i = 0; i < ip.length; i++) { + if (ip[i].indexOf(":") == -1) { + ip[i] = "::ffff:" + ip[i]; + } + blacklist.remove(ip[i]); + } + if (cluster.isMaster === undefined) serverconsole.climessage("IPs successfully unblocked."); + else if (!cluster.isMaster) process.send("IPs successfully unblocked."); + } + }, + restart: function () { + if (cluster.isMaster === undefined) serverconsole.climessage("This command is not supported on single-threaded SVR.JS."); + else process.send("This command need to be run in SVR.JS master."); + } + }; + + + if (init) { + if (cluster.isMaster === undefined) { + setInterval(function () { + try { + saveConfig(); + serverconsole.locmessage("Configuration saved."); + } catch (ex) { + throw new Error(ex); + } + }, 300000); + } else if (cluster.isMaster) { + setInterval(function () { + var allClusters = Object.keys(cluster.workers); + for (var i = 0; i < allClusters.length; i++) { + try { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].on("message", msgListener); + cluster.workers[allClusters[i]].send("\x14SAVECONF"); + } + } catch (ex) { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].removeAllListeners("message"); + cluster.workers[allClusters[i]].on("message", bruteForceListenerWrapper(cluster.workers[allClusters[i]])); + cluster.workers[allClusters[i]].on("message", listenConnListener); + } + serverconsole.locwarnmessage("There was a problem, while saving configuration file. Reason: " + ex.message); + } + } + }, 300000); + } + if (!cluster.isMaster && cluster.isMaster !== undefined) { + process.on("message", function (line) { + try { + if (line == "") { + //Does Nothing + process.send("\x12END"); + } else if (line == "\x14SAVECONF") { + //Save configuration file + try { + saveConfig(); + process.send("\x12SAVEGOOD"); + } catch (ex) { + process.send("\x12SAVEERR" + ex.message); + } + process.send("\x12END"); + } else if (commands[line.split(" ")[0]] !== undefined && commands[line.split(" ")[0]] !== null) { + var argss = line.split(" "); + var command = argss.shift(); + commands[command](argss); + process.send("\x12END"); + } else { + process.send("Unrecognized command \"" + line.split(" ")[0] + "\"."); + process.send("\x12END"); + } + } catch (ex) { + if (line != "") { + process.send("Can't execute command \"" + line.split(" ")[0] + "\"."); + process.send("\x12END"); + } + } + }); + } else { + var rla = readline.createInterface({ + input: process.stdin, + output: process.stdout, + prompt: "" + }); + rla.prompt(); + rla.on("line", function (line) { + line = line.trim(); + var argss = line.split(" "); + var command = argss.shift(); + if (line != "") { + if (cluster.isMaster !== undefined) { + var allClusters = Object.keys(cluster.workers); + if (command == "block") commands.block(argss); + if (command == "unblock") commands.unblock(argss); + if (command == "restart") { + var stopError = false; + exiting = true; + for (var i = 0; i < allClusters.length; i++) { + try { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].kill(); + } + } catch (ex) { + stopError = true; + } + } + if (stopError) serverconsole.climessage("Some SVR.JS workers might not be stopped."); + SVRJSInitialized = false; + var cpus = os.cpus().length; + if (cpus > 16) cpus = 16; + try { + var useAvailableCores = Math.round((os.freemem()) / 50000000) - 1; //1 core deleted for safety... + if (cpus > useAvailableCores) cpus = useAvailableCores; + } catch (ex) { + //Nevermind... Don't want SVR.JS to fail starting, because os.freemem function is not working. + } + if (cpus < 1) cpus = 1; //If SVR.JS is run on Haiku or if useAvailableCores = 0 + for (var i = 0; i < cpus; i++) { + if (i == 0) { + SVRJSFork(); + } else { + setTimeout((function (i) { + return function () { + SVRJSFork(); + if (i >= cpus - 1) { + SVRJSInitialized = true; + exiting = false; + serverconsole.climessage("SVR.JS workers restarted."); + } + }; + })(i), i * 6.6); + } + } + return; + } + if (command == "stop") { + exiting = true; + allClusters = Object.keys(cluster.workers); + } + for (var i = 0; i < allClusters.length; i++) { + try { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].on("message", msgListener); + cluster.workers[allClusters[i]].send(line); + } + } catch (ex) { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].removeAllListeners("message"); + cluster.workers[allClusters[i]].on("message", bruteForceListenerWrapper(cluster.workers[allClusters[i]])); + cluster.workers[allClusters[i]].on("message", listenConnListener); + } + serverconsole.climessage("Can't run command \"" + command + "\"."); + } + } + if (command == "stop") { + setTimeout(function () { + process.exit(0); + }, 50); + } + } else { + if (command == "stop") process.exit(0); + try { + commands[command](argss); + } catch (ex) { + serverconsole.climessage("Unrecognized command \"" + command + "\"."); + } + } + } + rla.prompt(); + }); + } + + if (cluster.isMaster || cluster.isMaster === undefined) { + //Cluster forking code + if (cluster.isMaster !== undefined && init) { + var cpus = os.cpus().length; + if (cpus > 16) cpus = 16; + try { + var useAvailableCores = Math.round((os.freemem()) / 50000000) - 1; //1 core deleted for safety... + if (cpus > useAvailableCores) cpus = useAvailableCores; + } catch (ex) { + //Nevermind... Don't want SVR.JS to fail starting, because os.freemem function is not working. + } + if (cpus < 1) cpus = 1; //If SVR.JS is run on Haiku or if useAvailableCores = 0 + for (var i = 0; i < cpus; i++) { + if (i == 0) { + SVRJSFork(); + } else { + setTimeout((function (i) { + return function () { + SVRJSFork(); + if (i >= cpus - 1) SVRJSInitialized = true; + }; + })(i), i * 6.6); + } + } + cluster.workers[Object.keys(cluster.workers)[0]].on("message", function (msg) { + if (msg.length > 9 && msg.indexOf("\x12ERRLIST") == 0) { + var tries = parseInt(msg.substr(8, 1)); + var errCode = msg.substr(9); + if (errCode == "EADDRINUSE") { + serverconsole.locerrmessage("Address in use by another process."); + } else if (errCode == "EADDRNOTAVAIL") { + serverconsole.locerrmessage("Address not available."); + } else if (errCode == "EACCES") { + serverconsole.locerrmessage("Access denied."); + } + serverconsole.locmessage(tries + " attempts left."); + } + if (msg == "\x12CRASH") process.exit(1); + if (msg == "\x12EADDRINUSE" || msg == "\x12EADDRNOTAVAIL" || msg == "\x12EACCES") process.exit(errors[msg.substr(1)]); + }); + + setInterval(function () { + if (!closedMaster && !exiting) { + var chksocket = {}; + if (secure && disableNonEncryptedServer) { + chksocket = https.get({ + port: sport, + headers: { + "X-SVR-JS-From-Main-Thread": "true", + "User-Agent": (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + }, + timeout: 2000, + rejectUnauthorized: false + }, function (res) { + chksocket.removeAllListeners("timeout"); + res.destroy(); + res.on("data", function () {}); + res.on("end", function () {}); + crashed = false; + }).on("error", function () { + if (!exiting) { + if (!crashed) SVRJSFork(); + else crashed = false; + } + }).on("timeout", function () { + if (!exiting) SVRJSFork(); + crashed = true; + }); + } else if ((configJSON.enableHTTP2 == undefined ? false : configJSON.enableHTTP2) && !secure) { + var connection = http2.connect("http://localhost:" + port.toString()); + connection.on("error", function () { + if (!exiting) { + if (!crashed) SVRJSFork(); + else crashed = false; + } + }); + connection.setTimeout(2000, function () { + if (!exiting) SVRJSFork(); + crashed = true; + }); + chksocket = connection.request({ + ":path": "/", + "x-svr-js-from-main-thread": "true", + "user-agent": (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + }); + chksocket.on("response", function () { + connection.close(); + crashed = false; + }); + chksocket.on("error", function () { + if (!exiting) { + if (!crashed) SVRJSFork(); + else crashed = false; + } + }); + } else { + chksocket = http.get({ + port: port, + headers: { + "X-SVR-JS-From-Main-Thread": "true", + "User-Agent": (exposeServerVersion ? "SVR.JS/" + version + " (" + getOS() + "; " + (process.isBun ? ("Bun/v" + process.versions.bun + "; like Node.JS/" + process.version) : ("Node.JS/" + process.version)) + ")" : "SVR.JS") + }, + timeout: 2000 + }, function (res) { + chksocket.removeAllListeners("timeout"); + res.destroy(); + res.on("data", function () {}); + res.on("end", function () {}); + crashed = false; + }).on("error", function () { + if (!exiting) { + if (!crashed) SVRJSFork(); + else crashed = false; + } + }).on("timeout", function () { + if (!exiting) SVRJSFork(); + crashed = true; + }); + } + } + }, 5000); + } + } + } +} + +//Save configuration file +function saveConfig() { + for (var i = 0; i < 3; i++) { + try { + var configJSONobj = {}; + if (fs.existsSync(__dirname + "/config.json")) configJSONobj = JSON.parse(fs.readFileSync(__dirname + "/config.json").toString()); + if (configJSONobj.users === undefined) configJSONobj.users = []; + if (secure) { + if (configJSONobj.key === undefined) configJSONobj.key = "cert/key.key"; + if (configJSONobj.cert === undefined) configJSONobj.cert = "cert/cert.crt"; + if (configJSONobj.sport === undefined) configJSONobj.sport = 443; + if (configJSONobj.spubport === undefined) configJSONobj.spubport = 443; + if (configJSONobj.sni === undefined) configJSONobj.sni = {}; + if (configJSONobj.enableOCSPStapling === undefined) configJSONobj.enableOCSPStapling = false; + } + if (configJSONobj.port === undefined) configJSONobj.port = 80; + if (configJSONobj.pubport === undefined) configJSONobj.pubport = 80; + if (configJSONobj.domain === undefined && configJSONobj.domian !== undefined) configJSONobj.domain = configJSONobj.domian; + delete configJSONobj.domian; + if (configJSONobj.page404 === undefined) configJSONobj.page404 = "404.html"; + configJSONobj.timestamp = timestamp; + configJSONobj.blacklist = blacklist.raw; + if (configJSONobj.nonStandardCodes === undefined) configJSONobj.nonStandardCodes = []; + if (configJSONobj.enableCompression === undefined) configJSONobj.enableCompression = true; + if (configJSONobj.customHeaders === undefined) configJSONobj.customHeaders = {}; + if (configJSONobj.enableHTTP2 === undefined) configJSONobj.enableHTTP2 = false; + if (configJSONobj.enableLogging === undefined) configJSONobj.enableLogging = true; + if (configJSONobj.enableDirectoryListing === undefined) configJSONobj.enableDirectoryListing = true; + if (configJSONobj.enableDirectoryListingWithDefaultHead === undefined) configJSONobj.enableDirectoryListingWithDefaultHead = false; + if (configJSONobj.serverAdministratorEmail === undefined) configJSONobj.serverAdministratorEmail = "[no contact information]"; + if (configJSONobj.stackHidden === undefined) configJSONobj.stackHidden = false; + if (configJSONobj.enableRemoteLogBrowsing === undefined) configJSONobj.enableRemoteLogBrowsing = true; + if (configJSONobj.exposeServerVersion === undefined) configJSONobj.exposeServerVersion = true; + if (configJSONobj.disableServerSideScriptExpose === undefined) configJSONobj.disableServerSideScriptExpose = false; + if (configJSONobj.allowStatus === undefined) configJSONobj.allowStatus = true; + if (configJSONobj.rewriteMap === undefined) configJSONobj.rewriteMap = []; + if (configJSONobj.dontCompress === undefined) configJSONobj.dontCompress = []; + if (configJSONobj.enableIPSpoofing === undefined) configJSONobj.enableIPSpoofing = false; + if (configJSONobj.secure === undefined) configJSONobj.secure = false; + if (configJSONobj.disableNonEncryptedServer === undefined) configJSONobj.disableNonEncryptedServer = false; + if (configJSONobj.disableToHTTPSRedirect === undefined) configJSONobj.disableToHTTPSRedirect = false; + //configJSONobj.wwwroot = configJSON.wwwroot; + + var configString = JSON.stringify(configJSONobj, null, 2); + fs.writeFileSync(__dirname + "/config.json", configString); + break; + } catch (ex) { + if (i >= 2) throw ex; + var now = Date.now(); + while (Date.now() - now < 2); + } + } +} + +//Process event listeners +if (cluster.isMaster || cluster.isMaster === undefined) { + process.on("uncaughtException", function (ex) { + //CRASH HANDLER + serverconsole.locerrmessage("SVR.JS master process just crashed!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(generateErrorStack(ex)); + process.exit(ex.errno); + }); + process.on("unhandledRejection", function (ex) { + //CRASH HANDLER + serverconsole.locerrmessage("SVR.JS master process just crashed!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(ex.stack ? generateErrorStack(ex) : String(ex)); + process.exit(ex.errno); + }); + process.on("exit", function (code) { + try { + saveConfig(); + } catch (ex) { + serverconsole.locwarnmessage("There was a problem, while saving configuration file. Reason: " + ex.message); + } + try { + deleteFolderRecursive(__dirname + "/temp"); + } catch (ex) { + //Error! + } + try { + fs.mkdirSync(__dirname + "/temp"); + } catch (ex) { + //Error! + } + serverconsole.locmessage("Server closed with exit code: " + code); + }); + process.on("warning", function (warning) { + serverconsole.locwarnmessage(warning.message); + if (generateErrorStack(warning)) {} + if (process.isBun) { + try { + fs.writeFileSync(__dirname + "/temp/serverSideScript.js", "//Placeholder server-side JavaScript to workaround Bun bug.\r\n"); + } catch (ex) { + //Error! + } + serverconsole.locwarnmessage("Stack:"); + serverconsole.locwarnmessage(generateErrorStack(warning)); + } + }); + process.on("SIGINT", function () { + if (cluster.isMaster !== undefined) { + exiting = true; + var allClusters = Object.keys(cluster.workers); + for (var i = 0; i < allClusters.length; i++) { + try { + if (cluster.workers[allClusters[i]]) { + cluster.workers[allClusters[i]].send("stop"); + } + } catch (ex) { + //Worker will crash with EPIPE anyway. + } + } + } + serverconsole.locmessage("Server terminated using SIGINT"); + process.exit(); + }); +} else { + process.on("uncaughtException", function (ex) { + //CRASH HANDLER + serverconsole.locerrmessage("SVR.JS worker just crashed!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(generateErrorStack(ex)); + process.exit(ex.errno); + }); + process.on("unhandledRejection", function (ex) { + //CRASH HANDLER + serverconsole.locerrmessage("SVR.JS worker just crashed!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(ex.stack ? generateErrorStack(ex) : String(ex)); + process.exit(ex.errno); + }); + process.on("warning", function (warning) { + serverconsole.locwarnmessage(warning.message); + if (warning.stack) { + serverconsole.locwarnmessage("Stack:"); + serverconsole.locwarnmessage(generateErrorStack(warning)); + } + }); +} +//Call start +try { + start(true); +} catch (ex) { + serverconsole.locerrmessage("There was a problem starting SVR.JS!!!"); + serverconsole.locerrmessage("Stack:"); + serverconsole.locerrmessage(generateErrorStack(ex)); + process.exit(ex.errno); +} diff --git a/svr_new.js b/svr_new.js new file mode 100644 index 0000000..89a5ae2 --- /dev/null +++ b/svr_new.js @@ -0,0 +1 @@ +require("./svr.js"); diff --git a/svrpasswd.js b/svrpasswd.js new file mode 100644 index 0000000..0942229 --- /dev/null +++ b/svrpasswd.js @@ -0,0 +1,346 @@ +//SVR.JS USER TOOL +var readline = require("readline"); +var process = require("process"); +var fs = require("fs"); +try { + var crypto = require('crypto'); +} catch (ex) { + var crypto = {}; + crypto.__disabled__ = null; + crypto.createHash = function(type) { + if (type != "SHA256") throw new Error("Hash type not supported!"); + return { + msg: "", + update: function(a) { + this.msg = a; + return this; + }, + digest: function(ty) { + var chrsz = 8; + var hexcase = 0; + + function safe_add(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + } + + function S(X, n) { + return (X >>> n) | (X << (32 - n)); + } + + function R(X, n) { + return (X >>> n); + } + + function Ch(x, y, z) { + return ((x & y) ^ ((~x) & z)); + } + + function Maj(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); + } + + function Sigma0256(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); + } + + function Sigma1256(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); + } + + function Gamma0256(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); + } + + function Gamma1256(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); + } + + function core_sha256(m, l) { + var K = new Array(0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0xFC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x6CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + a = HASH[0]; + b = HASH[1]; + c = HASH[2]; + d = HASH[3]; + e = HASH[4]; + f = HASH[5]; + g = HASH[6]; + h = HASH[7]; + + for (var j = 0; j < 64; j++) { + if (j < 16) W[j] = m[j + i]; + else W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + + T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); + T2 = safe_add(Sigma0256(a), Maj(a, b, c)); + + h = g; + g = f; + f = e; + e = safe_add(d, T1); + d = c; + c = b; + b = a; + a = safe_add(T1, T2); + } + + HASH[0] = safe_add(a, HASH[0]); + HASH[1] = safe_add(b, HASH[1]); + HASH[2] = safe_add(c, HASH[2]); + HASH[3] = safe_add(d, HASH[3]); + HASH[4] = safe_add(e, HASH[4]); + HASH[5] = safe_add(f, HASH[5]); + HASH[6] = safe_add(g, HASH[6]); + HASH[7] = safe_add(h, HASH[7]); + } + return HASH; + } + + function str2binb(str) { + var bin = Array(); + var mask = (1 << chrsz) - 1; + for (var i = 0; i < str.length * chrsz; i += chrsz) { + bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32); + } + return bin; + } + + function Utf8Encode(string) { + string = string.replace(/\r\n/g, '\n'); + var utftext = ''; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; + } + + function binb2hex(binarray) { + var hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; + var str = ''; + for (var i = 0; i < binarray.length * 4; i++) { + str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF); + } + return str; + } + + s = Utf8Encode(this.msg); + var str = binb2hex(core_sha256(str2binb(s), s.length * chrsz)); + if (ty == "hex") return str; + var hx = []; + for (var i = 0; i < str.length; i += 2) { + hx.push(parseInt(str[i] + str[i + 1], 16)); + } + return new Buffer(hx); + } + }; + } +} + +if (!crypto.randomInt) { + crypto.randomInt = function(min, max) { + return Math.round(Math.random() * (max - min)) + min; + } +} +var configJSON = {}; +if (fs.existsSync("config.json")) { + var configJSONf = ""; + try { + configJSONf = fs.readFileSync("config.json"); //Read JSON File + } catch (ex) { + throw new Error("Cannot read JSON file."); + } + try { + configJSON = JSON.parse(configJSONf); //Parse JSON + } catch (ex) { + throw new Error("JSON Parse error."); + } +} + +var users = []; +if (configJSON.users != undefined) users = configJSON.users; + +function saveConfig() { + var configJSONobj = {}; + if (fs.existsSync("./config.json")) configJSONobj = JSON.parse(fs.readFileSync("./config.json").toString()); + configJSONobj.users = users; + var configString = JSON.stringify(configJSONobj, null, 2); + fs.writeFileSync("config.json", configString); +} + +var args = process.argv; +var user = ""; +var action = "change"; +if (process.argv.length <= (process.argv[0].indexOf("node") > -1 || process.argv[0].indexOf("bun") > -1 ? 2 : 1)) args.push("-h"); +for (var i = (process.argv[0].indexOf("node") > -1 || process.argv[0].indexOf("bun") > -1 ? 2 : 1); i < args.length; i++) { + if (args[i] == "-h" || args[i] == "--help" || args[i] == "-?" || args[i] == "/h" || args[i] == "/?") { + console.log("SVR.JS user tool usage:"); + console.log("node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-a|--add|-d|--delete] "); + console.log("-h -? /h /? --help -- Displays help"); + console.log("-a --add -- Add an user"); + console.log("-d --delete -- Deletes an user"); + process.exit(0); + } else if (args[i] == "-a" || args[i] == "--add") { + if (action != "change") { + console.log("Multiple actions specified."); + console.log("node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-a|--add|-d|--delete] "); + console.log("-h -? /h /? --help -- Displays help"); + console.log("-a --add -- Add an user"); + console.log("-d --delete -- Deletes an user"); + process.exit(1); + } + action = "add"; + } else if (args[i] == "-d" || args[i] == "--delete") { + if (action != "change") { + console.log("Multiple actions specified."); + console.log("node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-a|--add|-d|--delete] "); + console.log("-h -? /h /? --help -- Displays help"); + console.log("-a --add -- Add an user"); + console.log("-d --delete -- Deletes an user"); + process.exit(1); + } + action = "delete"; + } else { + if (user != "") { + console.log("Multiple users specified."); + console.log("node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-a|--add|-d|--delete] "); + console.log("-h -? /h /? --help -- Displays help"); + console.log("-a --add -- Add an user"); + console.log("-d --delete -- Deletes an user"); + process.exit(1); + } + user = args[i]; + } +} + +if (user == "") { + console.log("No user specified."); + console.log("node svrpasswd.js [-h] [--help] [-?] [/h] [/?] [-a|--add|-d|--delete] "); + console.log("-h -? /h /? --help -- Displays help"); + console.log("-a --add -- Add an user"); + console.log("-d --delete -- Deletes an user"); + process.exit(1); +} + +function getUserIndex(username) { + var ind = -1 + for (var i = 0; i < users.length; i++) { + if (users[i].name == username) { + ind = i; + break; + } + } + return ind; +} + +function sha256(msg) { + var hash = crypto.createHash("SHA256"); + hash.update(msg); + return hash.digest('hex'); +} + +function generateSalt() { + var token = ""; + var strlist = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + for (var i = 0; i < 63; i++) { + token += strlist[crypto.randomInt(0, strlist.length)]; + } + return token; +} + +function password(callback) { + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + prompt: 'Password: ', + terminal: false + }); + rl.prompt(); + rl.once('line', (line) => { + //rl.close(); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + prompt: 'Confirm password: ', + terminal: false + }); + rl.prompt(); + rl.on('line', (line2) => { + rl.close(); + if (line != line2) callback(false); + else callback(line); + + }); + }); +} + +var userindex = getUserIndex(user); +if (action == "add" && userindex != -1) { + console.log("User alerady exists."); + process.exit(1); +} else if (action != "add" && userindex == -1) { + console.log("User doesn't exist."); + process.exit(1); +} +if (action == "delete") { + users.splice(userindex, 1); + saveConfig(); + console.log("User deleted successfully"); +} else if (action == "add") { + password(function(password) { + if (!password) { + console.log("Passwords don't match!"); + process.exit(1); + } else { + var salt = generateSalt() + users.push({ + name: user, + pass: sha256(password + salt), + salt: salt + }); + saveConfig(); + console.log("User added successfully"); + } + }); +} else { + password(function(password) { + if (!password) { + console.log("Passwords don't match!"); + process.exit(1); + } else { + var salt = generateSalt() + users[userindex] = { + name: user, + pass: sha256(password + salt), + salt: salt + }; + saveConfig(); + console.log("Password changed successfully"); + } + }); +} diff --git a/testdir/.personalized/FOOT.html b/testdir/.personalized/FOOT.html new file mode 100644 index 0000000..dd34732 --- /dev/null +++ b/testdir/.personalized/FOOT.html @@ -0,0 +1,6 @@ + + + + diff --git a/testdir/.personalized/HEAD.html b/testdir/.personalized/HEAD.html new file mode 100644 index 0000000..68f7b83 --- /dev/null +++ b/testdir/.personalized/HEAD.html @@ -0,0 +1,39 @@ + + + + + + +

My Website

+ +
+

Personalized directory listing

+

This is a test of personalized directory listing.

diff --git a/testdir/.personalized/folder/FOOT.html b/testdir/.personalized/folder/FOOT.html new file mode 100644 index 0000000..dd34732 --- /dev/null +++ b/testdir/.personalized/folder/FOOT.html @@ -0,0 +1,6 @@ +
+ + + diff --git a/testdir/.personalized/folder/HEAD.html b/testdir/.personalized/folder/HEAD.html new file mode 100644 index 0000000..68f7b83 --- /dev/null +++ b/testdir/.personalized/folder/HEAD.html @@ -0,0 +1,39 @@ + + + + + + +

My Website

+ +
+

Personalized directory listing

+

This is a test of personalized directory listing.

diff --git a/testdir/.personalized/html.html b/testdir/.personalized/html.html new file mode 100644 index 0000000..e69de29 diff --git a/testdir/.personalized/js.js b/testdir/.personalized/js.js new file mode 100644 index 0000000..e69de29 diff --git a/testdir/.personalized/text.txt b/testdir/.personalized/text.txt new file mode 100644 index 0000000..e69de29 diff --git a/testdir/html.html b/testdir/html.html new file mode 100644 index 0000000..e69de29 diff --git a/testdir/js.js b/testdir/js.js new file mode 100644 index 0000000..e69de29 diff --git a/testdir/text.txt b/testdir/text.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests.html b/tests.html new file mode 100644 index 0000000..6bd8485 --- /dev/null +++ b/tests.html @@ -0,0 +1,41 @@ + + + + SVR.JS 3.4.17 Tests + + + + + +

SVR.JS 3.4.17 Tests

+

Directory

+ +

Directory (with query)

+ +

Directory (personalized)

+ +

404 Error

+ + +

500 Error

+ +

Server Side Javascript

+ +

Proxy test

+ +

URL rewriting test (/invoke500/aprilfools => /invoke500.svr?aprilfools)

+ +
+
+ + + diff --git a/views.txt b/views.txt new file mode 100644 index 0000000..573541a --- /dev/null +++ b/views.txt @@ -0,0 +1 @@ +0