2023-07-29 20:44:13 +02:00
/////////////////////////////////////////
// //
// S V R . J S //
// S O U R C E C O D E //
// //
/////////////////////////////////////////
/////////////////////////////////////////
////// DorianTech SVR.JS //////
//////web server running on Node.JS//////
/////////////////////////////////////////
/////////////////////////////////////////
/ *
* MIT License
2023-08-29 15:03:13 +02:00
*
2023-08-29 14:56:39 +02:00
* Copyright ( c ) 2020 - 2023 DorianTech
2023-08-29 15:03:13 +02:00
*
2023-07-29 20:44:13 +02:00
* 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 :
2023-08-29 15:03:13 +02:00
*
2023-07-29 20:44:13 +02:00
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software .
2023-08-29 15:03:13 +02:00
*
2023-07-29 20:44:13 +02:00
* 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 .
2023-12-03 13:58:35 +01:00
* /
2023-07-29 20:44:13 +02:00
2023-09-03 11:08:16 +02:00
// Check if SVR.JS is running on Node.JS-compatible runtime. If not, just error it out.
2023-07-29 20:32:17 +02:00
if ( typeof require === "undefined" ) {
if ( typeof ActiveXObject !== "undefined" && typeof WScript !== "undefined" ) {
2023-08-09 21:09:23 +02:00
// If it runs on Windows Script Host, display an error message.
2023-07-29 20:32:17 +02:00
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" ) {
2023-08-09 21:09:23 +02:00
// If it runs on web browser, display an alert.
2023-07-29 20:32:17 +02:00
alert ( "SVR.JS doesn't work on web browser. SVR.JS requires use of Node.JS (or compatible JS runtime)." ) ;
}
2023-08-09 21:09:23 +02:00
// If it's not, throw an error.
2023-07-29 20:32:17 +02:00
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)." ) ;
}
}
}
2023-08-09 21:09:23 +02:00
2023-07-29 20:32:17 +02:00
var secure = false ;
var disableMods = false ;
2023-07-29 20:44:13 +02:00
2023-09-03 11:08:16 +02:00
// ASCII art SVR.JS logo ;)
2023-07-29 20:32:17 +02:00
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///////" , " ///////" ,
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" ) ;
2023-08-09 18:01:36 +02:00
var version = "Nightly-GitMain" ;
2023-07-29 20:32:17 +02:00
var singlethreaded = false ;
2023-09-03 11:08:16 +02:00
if ( process . versions ) process . versions . svrjs = version ; // Inject SVR.JS into process.versions
2023-07-29 20:32:17 +02:00
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 cluster = { } ;
if ( ! singlethreaded ) {
try {
// Import cluster module
var cluster = require ( "cluster" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
// Clustering is not supported!
}
// Cluster & IPC shim for Bun
2023-08-12 12:35:46 +02:00
2023-08-10 02:03:23 +02:00
cluster . bunShim = function ( ) {
2023-07-29 20:32:17 +02:00
cluster . isMaster = ! process . env . NODE _UNIQUE _ID ;
2023-08-10 02:03:23 +02:00
cluster . isPrimary = cluster . isMaster ;
2023-07-29 20:32:17 +02:00
cluster . isWorker = ! cluster . isMaster ;
2023-09-10 19:30:29 +02:00
cluster . _ _shimmed _ _ = true ;
2023-07-29 20:32:17 +02:00
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 ) ;
} ) ;
2023-07-29 20:44:13 +02:00
} ) ;
fakeIPCServer . listen ( os . platform ( ) === "win32" ? path . join ( "\\\\?\\pipe" , _ _dirname , "temp/.W" + process . pid + ".ipc" ) : ( _ _dirname + "/temp/.W" + process . pid + ".ipc" ) ) ;
2023-07-29 20:32:17 +02:00
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 ) ;
} ) ;
} ;
2023-08-12 12:35:46 +02:00
2023-08-29 15:03:13 +02:00
process . removeFakeIPC = function ( ) {
2023-08-10 04:01:50 +02:00
// Close IPC server
2023-08-29 15:03:13 +02:00
process . send = function ( ) { } ;
2023-08-10 04:01:50 +02:00
fakeIPCServer . close ( ) ;
2023-08-31 22:47:07 +02:00
} ;
2023-07-29 20:32:17 +02:00
}
}
// 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 ;
2023-09-08 20:08:46 +02:00
if ( ! ( process . versions && process . versions . bun && process . versions . bun [ 0 ] != "0" ) ) {
if ( ! worker . send ) {
sendImplemented = false ;
2023-08-10 03:16:52 +02:00
}
2023-08-12 12:35:46 +02:00
2023-09-08 20:08:46 +02:00
var oldLog = console . log ;
2023-12-03 13:58:35 +01:00
console . log = function ( a , b , c , d , e , f ) {
if ( a == "ChildProcess.prototype.send() - Sorry! Not implemented yet" ) {
2023-09-08 20:08:46 +02:00
throw new Error ( "NOT IMPLEMENTED" ) ;
} else {
2023-12-03 13:58:35 +01:00
oldLog ( a , b , c , d , e , f ) ;
2023-09-08 20:08:46 +02:00
}
} ;
try {
worker . send ( undefined ) ;
} catch ( err ) {
if ( err . message === "NOT IMPLEMENTED" ) {
sendImplemented = false ;
}
console . log ( err ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-12 12:35:46 +02:00
2023-09-08 20:08:46 +02:00
console . log = oldLog ;
}
2023-07-29 20:32:17 +02:00
return sendImplemented ;
}
if ( ! checkSendImplementation ( newWorker ) ) {
2023-08-10 03:16:52 +02:00
var net = require ( "net" ) ;
var os = require ( "os" ) ;
2023-08-12 12:35:46 +02:00
2023-07-29 20:32:17 +02:00
// 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 ) ;
} ) ;
2023-08-10 04:01:50 +02:00
} ) ;
fakeWorkerIPCServer . listen ( os . platform ( ) === "win32" ? path . join ( "\\\\?\\pipe" , _ _dirname , "temp/.P" + newWorker . process . pid + ".ipc" ) : ( _ _dirname + "/temp/.P" + newWorker . process . pid + ".ipc" ) ) ;
2023-07-29 20:32:17 +02:00
// 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 ) ;
} ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-08-10 04:20:30 +02:00
if ( tries > 50 ) throw err ;
newWorker . send ( message , fakeParam2 , fakeParam3 , fakeParam4 , tries + 1 ) ;
2023-07-29 20:32:17 +02:00
}
} ;
2023-09-10 18:58:05 +02:00
} else {
newWorker . on ( "exit" , function ( ) {
delete cluster . workers [ newWorker . id ] ;
} ) ;
2023-07-29 20:32:17 +02:00
}
cluster . workers [ newWorker . id ] = newWorker ;
cluster . _workersCounter ++ ;
return newWorker ;
} ;
2023-08-31 22:47:07 +02:00
} ;
2023-08-09 18:01:36 +02:00
2023-08-10 03:16:52 +02:00
if ( process . isBun && ( cluster . isMaster === undefined || ( cluster . isMaster && process . env . NODE _UNIQUE _ID ) ) ) {
2023-08-10 02:03:23 +02:00
cluster . bunShim ( ) ;
}
2023-08-12 12:35:46 +02:00
2023-08-09 18:01:36 +02:00
// Shim cluster.isPrimary field
if ( cluster . isPrimary === undefined && cluster . isMaster !== undefined ) cluster . isPrimary = cluster . isMaster ;
2023-07-29 20:32:17 +02:00
}
2023-08-09 21:09:23 +02:00
// ETag-related
2023-07-29 20:44:13 +02:00
var ETagDB = { } ;
2023-12-03 13:58:35 +01:00
2023-07-29 20:44:13 +02:00
function generateETag ( filePath , stat ) {
2023-12-03 13:58:35 +01:00
if ( ! ETagDB [ filePath + "-" + stat . size + "-" + stat . mtime ] ) ETagDB [ filePath + "-" + stat . size + "-" + stat . mtime ] = sha256 ( filePath + "-" + stat . size + "-" + stat . mtime ) ;
2023-07-29 20:44:13 +02:00
return ETagDB [ filePath + "-" + stat . size + "-" + stat . mtime ] ;
}
2023-08-09 21:09:23 +02:00
// Brute force-related
var bruteForceDb = { } ;
2023-08-15 19:05:44 +02:00
// PBKDF2 cache
var pbkdf2Cache = [ ] ;
2023-08-18 21:35:09 +02:00
var scryptCache = [ ] ;
2023-08-15 19:05:44 +02:00
var pbkdf2CacheIntervalId = - 1 ;
2023-08-09 21:09:23 +02:00
// SVR.JS worker spawn-related
2023-07-29 20:32:17 +02:00
var SVRJSInitialized = false ;
var exiting = false ;
2023-07-29 20:44:13 +02:00
var reallyExiting = false ;
2023-07-29 20:32:17 +02:00
var crashed = false ;
2023-09-10 19:30:29 +02:00
var threadLimitWarned = false ;
2023-07-29 20:32:17 +02:00
function SVRJSFork ( ) {
2023-09-03 11:08:16 +02:00
// Log
2023-07-29 20:32:17 +02:00
if ( SVRJSInitialized ) serverconsole . locmessage ( "Starting next thread, because previous one hung up/crashed..." ) ;
2023-09-03 11:08:16 +02:00
// Fork new worker
2023-08-10 02:03:23 +02:00
var newWorker = { } ;
try {
2023-09-11 21:50:42 +02:00
if ( ! threadLimitWarned && cluster . _ _shimmed _ _ && process . isBun && process . versions . bun && process . versions . bun [ 0 ] != "0" ) {
2023-09-10 19:30:29 +02:00
threadLimitWarned = true ;
serverconsole . locwarnmessage ( "SVR.JS limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer." ) ;
}
if ( ! ( cluster . _ _shimmed _ _ && process . isBun && process . versions . bun && process . versions . bun [ 0 ] != "0" && Object . keys ( cluster . workers ) > 0 ) ) {
newWorker = cluster . fork ( ) ;
} else {
if ( SVRJSInitialized ) serverconsole . locwarnmessage ( "SVR.JS limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer." ) ;
}
2023-08-10 02:03:23 +02:00
} catch ( err ) {
2023-12-03 13:58:35 +01:00
if ( err . name == "NotImplementedError" ) {
2023-08-10 02:03:23 +02:00
// If cluster.fork throws a NotImplementedError, shim cluster module
cluster . bunShim ( ) ;
2023-09-11 21:50:42 +02:00
if ( ! threadLimitWarned && cluster . _ _shimmed _ _ && process . isBun && process . versions . bun && process . versions . bun [ 0 ] != "0" ) {
2023-09-10 19:30:29 +02:00
threadLimitWarned = true ;
serverconsole . locwarnmessage ( "SVR.JS limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer." ) ;
}
if ( ! ( cluster . _ _shimmed _ _ && process . isBun && process . versions . bun && process . versions . bun [ 0 ] != "0" && Object . keys ( cluster . workers ) > 0 ) ) {
newWorker = cluster . fork ( ) ;
} else {
if ( SVRJSInitialized ) serverconsole . locwarnmessage ( "SVR.JS limited the number of workers to one, because of startup problems in Bun 1.0 and newer with shimmed (not native) clustering module. Reliability may suffer." ) ;
}
2023-08-10 02:03:23 +02:00
} else {
2023-08-12 12:35:46 +02:00
throw err ;
2023-08-10 02:03:23 +02:00
}
}
2023-09-10 19:30:29 +02:00
// Add event listeners
2023-12-03 13:58:35 +01:00
if ( newWorker . on ) {
2023-09-10 19:30:29 +02:00
newWorker . on ( "error" , function ( err ) {
2023-12-03 13:58:35 +01:00
if ( ! reallyExiting ) serverconsole . locwarnmessage ( "There was a problem when handling SVR.JS worker! (from master process side) Reason: " + err . message ) ;
2023-09-10 19:30:29 +02:00
} ) ;
newWorker . on ( "exit" , function ( ) {
if ( ! exiting && Object . keys ( cluster . workers ) . length == 0 ) {
crashed = true ;
SVRJSFork ( ) ;
}
} ) ;
newWorker . on ( "message" , bruteForceListenerWrapper ( newWorker ) ) ;
newWorker . on ( "message" , listenConnListener ) ;
}
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
2023-07-29 20:32:17 +02:00
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" ) ;
2023-08-28 03:44:04 +02:00
var dns = require ( "dns" ) ;
2023-07-29 20:32:17 +02:00
try {
var gracefulFs = require ( "graceful-fs" ) ;
2023-09-03 11:08:16 +02:00
if ( ! process . isBun ) gracefulFs . gracefulify ( fs ) ; // Bun + graceful-fs + SVR.JS + requests about static content = 500 Internal Server Error!
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Don't use graceful-fs
2023-07-29 20:32:17 +02:00
}
var path = require ( "path" ) ;
var hexstrbase64 = undefined ;
try {
hexstrbase64 = require ( "./hexstrbase64/index.js" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Don't use hexstrbase64
2023-07-29 20:32:17 +02:00
}
var svrmodpack = undefined ;
try {
svrmodpack = require ( "svrmodpack" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
svrmodpack = {
2023-08-02 23:54:07 +02:00
_errored : err
2023-07-29 20:32:17 +02:00
} ;
}
var zlib = require ( "zlib" ) ;
var tar = undefined ;
try {
tar = require ( "tar" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
tar = {
2023-08-02 23:54:07 +02:00
_errored : err
2023-07-29 20:32:17 +02:00
} ;
}
var formidable = undefined ;
try {
formidable = require ( "formidable" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
formidable = {
2023-08-02 23:54:07 +02:00
_errored : err
2023-07-29 20:32:17 +02:00
} ;
}
var ocsp = undefined ;
var ocspCache = undefined ;
try {
ocsp = require ( "ocsp" ) ;
ocspCache = new ocsp . Cache ( ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
ocsp = {
2023-08-02 23:54:07 +02:00
_errored : err
2023-07-29 20:32:17 +02:00
} ;
}
var http2 = { } ;
try {
http2 = require ( "http2" ) ;
if ( process . isBun ) {
try {
http2 . Http2ServerRequest ( ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
if ( err . name == "NotImplementedError" || err . code == "ERR_NOT_IMPLEMENTED" ) throw err ;
2023-07-29 20:32:17 +02:00
}
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
http2 . _ _disabled _ _ = null ;
http2 . createServer = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "HTTP/2 support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
http2 . createSecureServer = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "HTTP/2 support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
http2 . connect = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "HTTP/2 support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
http2 . get = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "HTTP/2 support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
}
var crypto = { } ;
var https = { } ;
try {
crypto = require ( "crypto" ) ;
https = require ( "https" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
crypto = { } ;
https = { } ;
crypto . _ _disabled _ _ = null ;
https . createServer = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "Crypto support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
http2 . createSecureServer = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "Crypto support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
https . connect = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "Crypto support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
https . get = function ( ) {
2023-07-29 20:44:13 +02:00
throw new Error ( "Crypto support is not present" ) ;
2023-07-29 20:32:17 +02:00
} ;
}
var mime = require ( "mime-types" ) ;
var pubip = "" ;
2023-09-02 18:15:00 +02:00
var listenAddress = undefined ;
var sListenAddress = undefined ;
2023-07-29 20:32:17 +02:00
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 = [ ] ;
2023-12-03 12:51:05 +01:00
function sizify ( bytes , addI ) {
2023-09-12 19:21:13 +02:00
if ( bytes == 0 ) return "0" ;
if ( bytes < 0 ) bytes = - bytes ;
var prefixes = [ "" , "K" , "M" , "G" , "T" , "P" , "E" , "Z" , "Y" , "R" , "Q" ] ;
2023-12-03 12:51:05 +01:00
var prefixIndex = Math . floor ( Math . log2 ? Math . log2 ( bytes ) / 10 : ( Math . log ( bytes ) / Math . log ( 2 ) * 10 ) ) ;
2023-09-12 19:21:13 +02:00
if ( prefixIndex >= prefixes . length - 1 ) prefixIndex = prefixes . length - 1 ;
2023-12-03 12:51:05 +01:00
var prefixIndexTranslated = Math . pow ( 2 , 10 * prefixIndex ) ;
2023-12-03 13:58:35 +01:00
var decimalPoints = 2 - Math . floor ( Math . log10 ? Math . log10 ( bytes / prefixIndexTranslated ) : ( Math . log ( bytes / prefixIndexTranslated ) / Math . log ( 10 ) ) ) ;
2023-12-03 12:51:05 +01:00
if ( decimalPoints < 0 ) decimalPoints = 0 ;
2023-12-03 13:58:35 +01:00
return ( Math . ceil ( ( bytes / prefixIndexTranslated ) * Math . pow ( 10 , decimalPoints ) ) / Math . pow ( 10 , decimalPoints ) ) + prefixes [ prefixIndex ] + ( ( prefixIndex > 0 && addI ) ? "i" : "" ) ;
2023-07-29 20:32:17 +02:00
}
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 ;
}
}
2023-08-02 23:54:07 +02:00
function createRegex ( regex , isPath ) {
var regexStrMatch = regex . match ( /^\/((?:\\.|[^\/\\])*)\/([a-zA-Z0-9]*)$/ ) ;
2023-12-03 13:07:28 +01:00
if ( ! regexStrMatch ) throw new Error ( "Invalid regular expression: " + regex ) ;
2023-08-02 23:54:07 +02:00
var searchString = regexStrMatch [ 1 ] ;
var modifiers = regexStrMatch [ 2 ] ;
if ( isPath && ! modifiers . match ( /i/i ) && os . platform ( ) == "win32" ) modifiers += "i" ;
2023-07-29 20:32:17 +02:00
return new RegExp ( searchString , modifiers ) ;
}
2023-08-31 22:47:07 +02:00
function checkForEnabledDirectoryListing ( hostname ) {
function matchHostname ( hostnameM ) {
if ( typeof hostnameM == "undefined" || hostnameM == "*" ) {
return true ;
} else if ( hostname && hostnameM . indexOf ( "*." ) == 0 && hostnameM != "*." ) {
var hostnamesRoot = hostnameM . substr ( 2 ) ;
if ( hostname == hostnamesRoot || hostname . indexOf ( "." + hostnamesRoot ) == hostname . length - hostnamesRoot . length - 1 ) {
return true ;
}
} else if ( hostname && hostname == hostnameM ) {
return true ;
}
return false ;
}
2023-09-03 10:27:30 +02:00
2023-08-31 22:47:07 +02:00
var main = ( configJSON . enableDirectoryListing || configJSON . enableDirectoryListing === undefined ) ;
2023-12-03 13:58:35 +01:00
if ( ! configJSON . enableDirectoryListingVHost ) return main ;
2023-08-31 22:47:07 +02:00
var vhostP = null ;
2023-12-03 13:58:35 +01:00
configJSON . enableDirectoryListingVHost . every ( function ( vhost ) {
if ( matchHostname ( vhost . host ) ) {
2023-08-31 22:47:07 +02:00
vhostP = vhost ;
return false ;
} else {
return true ;
}
} ) ;
2023-12-03 13:58:35 +01:00
if ( ! vhostP || vhostP . enabled === undefined ) return main ;
2023-08-31 22:47:07 +02:00
else return vhostP . enabled ;
}
2023-09-03 11:08:16 +02:00
// IP Block list object
2023-07-29 20:32:17 +02:00
function ipBlockList ( rawBlockList ) {
2023-08-12 12:35:46 +02:00
2023-07-29 20:44:13 +02:00
// Initialize the instance with empty arrays
if ( rawBlockList === undefined ) rawBlockList = [ ] ;
var instance = {
raw : [ ] ,
rawtoPreparedMap : [ ] ,
prepared : [ ] ,
cidrs : [ ]
} ;
// Function to normalize IPv4 address (remove leading zeros)
2023-07-29 20:32:17 +02:00
function normalizeIPv4Address ( address ) {
return address . replace ( /(^|\.)(?:0(?!\.|$))+/g , "" ) ;
}
2023-07-29 20:44:13 +02:00
// Function to expand IPv6 address to full format
2023-07-29 20:32:17 +02:00
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 ) ) {
2023-08-19 22:38:58 +02:00
var oldGroups = address . match ( extractIpv4 ) ;
for ( var i = 1 ; i < oldGroups . length ; i ++ ) {
ipv4 += ( "00" + ( parseInt ( oldGroups [ i ] , 10 ) . toString ( 16 ) ) ) . slice ( - 2 ) + ( i == 2 ? ":" : "" ) ;
2023-07-29 20:32:17 +02:00
}
address = address . replace ( extractIpv4 , ipv4 ) ;
}
if ( address . indexOf ( "::" ) == - 1 ) {
fullAddress = address ;
} else {
var sides = address . split ( "::" ) ;
var groupsPresent = 0 ;
2023-08-19 22:38:58 +02:00
sides . forEach ( function ( side ) {
groupsPresent += side . split ( ":" ) . length ;
} ) ;
2023-07-29 20:32:17 +02:00
fullAddress += sides [ 0 ] + ":" ;
2023-12-03 13:58:35 +01:00
if ( validGroupCount - groupsPresent > 1 ) {
2023-08-19 22:38:58 +02:00
fullAddress += "0000:" . repeat ( validGroupCount - groupsPresent ) ;
2023-07-29 20:32:17 +02:00
}
fullAddress += sides [ 1 ] ;
}
var groups = fullAddress . split ( ":" ) ;
for ( var i = 0 ; i < validGroupCount ; i ++ ) {
2023-08-19 22:38:58 +02:00
if ( groups [ i ] . length < validGroupSize ) {
groups [ i ] = "0" . repeat ( validGroupSize - groups [ i ] . length ) + groups [ i ] ;
2023-07-29 20:32:17 +02:00
}
expandedAddress += ( i != validGroupCount - 1 ) ? groups [ i ] + ":" : groups [ i ] ;
}
return expandedAddress ;
}
2023-07-29 20:44:13 +02:00
// Convert IPv4 address to an integer representation
2023-07-29 20:32:17 +02:00
function ipv4ToInt ( ip ) {
var ips = ip . split ( "." ) ;
return parseInt ( ips [ 0 ] ) * 16777216 + parseInt ( ips [ 1 ] ) * 65536 + parseInt ( ips [ 2 ] ) * 256 + parseInt ( ips [ 3 ] ) ;
}
2023-07-29 20:44:13 +02:00
// Get IPv4 CIDR block limits (min and max)
2023-07-29 20:32:17 +02:00
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
} ;
}
2023-07-29 20:44:13 +02:00
// Convert IPv6 address to an array of blocks
2023-07-29 20:32:17 +02:00
function ipv6ToBlocks ( ip ) {
var ips = ip . split ( ":" ) ;
var ip2s = [ ] ;
2023-08-19 22:38:58 +02:00
ips . forEach ( function ( ipe ) {
ip2s . push ( parseInt ( ipe ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
return ip2s ;
}
2023-07-29 20:44:13 +02:00
// Get IPv6 CIDR block limits (min and max)
2023-07-29 20:32:17 +02:00
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
} ;
}
2023-07-29 20:44:13 +02:00
// Check if the IPv4 address matches the given CIDR block
2023-07-29 20:32:17 +02:00
function checkIfIPv4CIDRMatches ( ipInt , cidrObject ) {
if ( cidrObject . v6 ) return false ;
return ipInt >= cidrObject . min && ipInt <= cidrObject . max ;
}
2023-07-29 20:44:13 +02:00
// Check if the IPv6 address matches the given CIDR block
2023-07-29 20:32:17 +02:00
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 ;
}
2023-07-29 20:44:13 +02:00
// Function to add an IP or CIDR block to the block list
2023-07-29 20:32:17 +02:00
instance . add = function ( rawValue ) {
2023-08-29 14:56:39 +02:00
// Add to raw block list
instance . raw . push ( rawValue ) ;
2023-07-29 20:44:13 +02:00
// Initialize variables
2023-07-29 20:32:17 +02:00
var beginIndex = instance . prepared . length ;
var cidrIndex = instance . cidrs . length ;
var cidrMask = null ;
var isIPv6 = false ;
2023-07-29 20:44:13 +02:00
// Check if the input contains CIDR notation
2023-07-29 20:32:17 +02:00
if ( rawValue . indexOf ( "/" ) > - 1 ) {
var rwArray = rawValue . split ( "/" ) ;
cidrMask = rwArray . pop ( ) ;
rawValue = rwArray . join ( "/" ) ;
}
2023-07-29 20:44:13 +02:00
// Normalize the IP address or expand the IPv6 address
2023-07-29 20:32:17 +02:00
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 ) ;
}
2023-07-29 20:44:13 +02:00
// Add the IP or CIDR block to the appropriate list
2023-07-29 20:32:17 +02:00
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
} ) ;
}
} ;
2023-07-29 20:44:13 +02:00
// Function to remove an IP or CIDR block from the block list
2023-07-29 20:32:17 +02:00
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 ;
} ;
2023-07-29 20:44:13 +02:00
// Function to check if an IP is blocked by the block list
2023-07-29 20:32:17 +02:00
instance . check = function ( rawValue ) {
if ( instance . raw . length == 0 ) return false ;
var isIPv6 = false ;
2023-07-29 20:44:13 +02:00
// Normalize or expand the IP address
2023-07-29 20:32:17 +02:00
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 ) ;
}
2023-07-29 20:44:13 +02:00
// Check if the IP is in the prepared list
2023-07-29 20:32:17 +02:00
if ( instance . prepared . indexOf ( rawValue ) > - 1 ) return true ;
2023-07-29 20:44:13 +02:00
// Check if the IP is within any CIDR block in the block list
2023-07-29 20:32:17 +02:00
if ( instance . cidrs . length == 0 ) return false ;
var ipParsedObject = ( ! isIPv6 ? ipv4ToInt : ipv6ToBlocks ) ( rawValue ) ;
var checkMethod = ( ! isIPv6 ? checkIfIPv4CIDRMatches : checkIfIPv6CIDRMatches ) ;
2023-08-29 14:56:39 +02:00
2023-08-29 15:03:13 +02:00
return instance . cidrs . some ( function ( iCidr ) {
2023-08-19 22:38:58 +02:00
return checkMethod ( ipParsedObject , iCidr ) ;
} ) ;
2023-07-29 20:32:17 +02:00
} ;
2023-07-29 20:44:13 +02:00
// Add initial raw block list values to the instance
2023-08-19 22:38:58 +02:00
rawBlockList . forEach ( function ( rbe ) {
instance . add ( rbe ) ;
} ) ;
2023-08-12 12:35:46 +02:00
2023-07-29 20:32:17 +02:00
return instance ;
}
2023-07-29 20:44:13 +02:00
// Generate V8-style error stack from Error object.
function generateErrorStack ( errorObject ) {
// Split the error stack by newlines.
var errorStack = errorObject . stack ? errorObject . stack . split ( "\n" ) : [ ] ;
// If the error stack starts with the error name, return the original stack (it is V8-style then).
2023-08-19 22:38:58 +02:00
if ( errorStack . some ( function ( errorStackLine ) {
2023-12-03 13:58:35 +01:00
return ( errorStackLine . indexOf ( errorObject . name ) == 0 ) ;
} ) ) {
2023-08-19 22:38:58 +02:00
return errorObject . stack ;
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
// Create a new error stack with the error name and code (if available).
var newErrorStack = [ errorObject . name + ( errorObject . code ? ": " + errorObject . code : "" ) + ( errorObject . message == "" ? "" : ": " + errorObject . message ) ] ;
// Process each line of the original error stack.
2023-08-19 22:38:58 +02:00
errorStack . forEach ( function ( errorStackLine ) {
if ( errorStackLine != "" ) {
2023-07-29 20:44:13 +02:00
// Split the line into function and location parts (if available).
2023-08-19 22:38:58 +02:00
var errorFrame = errorStackLine . split ( "@" ) ;
2023-07-29 20:32:17 +02:00
var location = "" ;
2023-07-29 20:44:13 +02:00
if ( errorFrame . length > 1 ) location = errorFrame . pop ( ) ;
var func = errorFrame . join ( "@" ) ;
// Build the new error stack entry with function and location information.
newErrorStack . push ( " at " + ( func == "" ? ( ! location || location == "" ? "<anonymous>" : location ) : ( func + ( ! location || location == "" ? "" : " (" + location + ")" ) ) ) ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:44:13 +02:00
// Join the new error stack entries with newlines and return the final stack.
return newErrorStack . join ( "\n" ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-02 18:15:00 +02:00
function calculateBroadcastIPv4FromCidr ( ipWithCidr ) {
// Check if CIDR notation is valid, if it's not, return null
2023-12-03 13:58:35 +01:00
if ( ! ipWithCidr ) return null ;
2023-09-02 18:15:00 +02:00
var ipCA = ipWithCidr . split ( "/" ) ;
2023-12-03 13:58:35 +01:00
if ( ipCA . length != 2 ) return null ;
2023-09-03 10:27:30 +02:00
2023-09-02 18:15:00 +02:00
// Extract IP and mask (numberic format)
var ip = ipCA [ 0 ] ;
var mask = parseInt ( ipCA [ 1 ] ) ;
2023-12-03 13:58:35 +01:00
return ip . split ( "." ) . map ( function ( num , index ) {
2023-09-02 18:15:00 +02:00
// Calculate resulting 8-bit
2023-12-03 13:58:35 +01:00
var power = Math . max ( Math . min ( mask - ( index * 8 ) , 8 ) , 0 ) ;
return ( ( parseInt ( num ) & ( ( Math . pow ( 2 , power ) - 1 ) << ( 8 - power ) ) ) | Math . pow ( 2 , 8 - power ) - 1 ) . toString ( ) ;
2023-09-02 18:15:00 +02:00
} ) . join ( "." ) ;
}
function calculateNetworkIPv4FromCidr ( ipWithCidr ) {
// Check if CIDR notation is valid, if it's not, return null
2023-12-03 13:58:35 +01:00
if ( ! ipWithCidr ) return null ;
2023-09-02 18:15:00 +02:00
var ipCA = ipWithCidr . split ( "/" ) ;
2023-12-03 13:58:35 +01:00
if ( ipCA . length != 2 ) return null ;
2023-09-03 10:27:30 +02:00
2023-09-02 18:15:00 +02:00
// Extract IP and mask (numberic format)
var ip = ipCA [ 0 ] ;
var mask = parseInt ( ipCA [ 1 ] ) ;
2023-12-03 13:58:35 +01:00
return ip . split ( "." ) . map ( function ( num , index ) {
2023-09-02 18:15:00 +02:00
// Calculate resulting 8-bit
2023-12-03 13:58:35 +01:00
var power = Math . max ( Math . min ( mask - ( index * 8 ) , 8 ) , 0 ) ;
return ( ( parseInt ( num ) & ( ( Math . pow ( 2 , power ) - 1 ) << ( 8 - power ) ) ) ) . toString ( ) ;
2023-09-02 18:15:00 +02:00
} ) . join ( "." ) ;
}
2023-07-29 20:44:13 +02:00
2023-07-29 20:32:17 +02:00
var ifaces = { } ;
var ifaceEx = null ;
try {
ifaces = os . networkInterfaces ( ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
ifaceEx = err ;
2023-07-29 20:32:17 +02:00
}
var ips = [ ] ;
2023-09-02 18:15:00 +02:00
var brdIPs = [ "255.255.255.255" , "127.255.255.255" , "0.255.255.255" ] ;
var netIPs = [ "127.0.0.0" ] ;
2023-07-29 20:32:17 +02:00
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 ) ;
}
2023-09-02 18:15:00 +02:00
brdIPs . push ( calculateBroadcastIPv4FromCidr ( iface . cidr ) ) ;
netIPs . push ( calculateNetworkIPv4FromCidr ( iface . cidr ) ) ;
2023-07-29 20:44:13 +02:00
alias ++ ;
2023-07-29 20:32:17 +02:00
} ) ;
} ) ;
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 ) ;
}
2023-07-29 20:44:13 +02:00
alias ++ ;
2023-07-29 20:32:17 +02:00
} ) ;
} ) ;
}
var host = ips [ ( ips . length ) - 1 ] ;
if ( ! host ) host = "[offline]" ;
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 ( ) ;
2023-08-28 03:44:04 +02:00
if ( domain ) {
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} else {
var callbackDone = false ;
2023-08-29 15:03:13 +02:00
var dnsTimeout = setTimeout ( function ( ) {
2023-08-28 03:44:04 +02:00
callbackDone = true ;
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} , 3000 ) ;
try {
2023-08-29 15:03:13 +02:00
dns . reverse ( pubip , function ( err , hostnames ) {
2023-12-03 13:58:35 +01:00
if ( callbackDone ) return ;
2023-08-28 03:44:04 +02:00
clearTimeout ( dnsTimeout ) ;
2023-12-03 13:58:35 +01:00
if ( ! err && hostnames . length > 0 ) domain = hostnames [ 0 ] ;
2023-08-28 03:44:04 +02:00
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-08-28 03:44:04 +02:00
clearTimeout ( dnsTimeout ) ;
callbackDone = true ;
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
2023-07-29 20:32:17 +02:00
}
}
} ) ;
} ) ;
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 ( ) ;
2023-08-28 03:44:04 +02:00
if ( domain ) {
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} else {
var callbackDone = false ;
2023-08-29 15:03:13 +02:00
var dnsTimeout = setTimeout ( function ( ) {
2023-08-28 03:44:04 +02:00
callbackDone = true ;
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} , 3000 ) ;
try {
2023-08-29 15:03:13 +02:00
dns . reverse ( pubip , function ( err , hostnames ) {
2023-12-03 13:58:35 +01:00
if ( callbackDone ) return ;
2023-08-28 03:44:04 +02:00
clearTimeout ( dnsTimeout ) ;
2023-12-03 13:58:35 +01:00
if ( ! err && hostnames . length > 0 ) domain = hostnames [ 0 ] ;
2023-08-28 03:44:04 +02:00
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-08-28 03:44:04 +02:00
clearTimeout ( dnsTimeout ) ;
callbackDone = true ;
ipRequestCompleted = true ;
process . emit ( "ipRequestCompleted" ) ;
2023-07-29 20:32:17 +02:00
}
}
} ) ;
} ) ;
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 = { } ;
2023-09-02 20:27:27 +02:00
var configJSONRErr = undefined ;
var configJSONPErr = undefined ;
2023-07-29 20:32:17 +02:00
if ( fs . existsSync ( _ _dirname + "/config.json" ) ) {
var configJSONf = "" ;
try {
2023-09-03 11:08:16 +02:00
configJSONf = fs . readFileSync ( _ _dirname + "/config.json" ) ; // Read JSON File
2023-09-02 20:27:27 +02:00
try {
2023-09-03 11:08:16 +02:00
configJSON = JSON . parse ( configJSONf ) ; // Parse JSON
2023-09-02 20:27:27 +02:00
} catch ( err2 ) {
configJSONPErr = err2 ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-02 20:27:27 +02:00
configJSONRErr = err2 ;
2023-09-03 11:08:16 +02:00
// throw new Error("Cannot read JSON file.");
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 11:08:16 +02:00
// Default server configuration properties
2023-07-29 20:32:17 +02:00
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 = [ ] ;
2023-08-12 13:37:06 +02:00
var disableUnusedWorkerTermination = false ;
2023-08-18 23:29:18 +02:00
var rewriteDirtyURLs = false ;
2023-08-31 22:47:07 +02:00
var errorPages = [ ] ;
2023-09-02 12:57:19 +02:00
var useWebRootServerSideScript = true ;
2023-09-05 00:05:20 +02:00
var exposeModsInErrorPages = true ;
2023-12-03 12:11:15 +01:00
var disableTrailingSlashRedirects = false ;
var environmentVariables = { } ;
2023-07-29 20:44:13 +02:00
2023-09-03 11:08:16 +02:00
// Get properties from config.json
2023-07-29 20:32:17 +02:00
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 ;
2023-09-02 18:15:00 +02:00
if ( typeof port === "string" ) {
2023-12-03 13:58:35 +01:00
if ( port . match ( /^[0-9]+$/ ) ) {
2023-09-02 18:15:00 +02:00
port = parseInt ( port ) ;
} else {
var portLMatch = port . match ( /^(\[[^ \]@\/\\]+\]|[^ \]\[:@\/\\]+):([0-9]+)$/ ) ;
2023-12-03 13:58:35 +01:00
if ( portLMatch ) {
listenAddress = portLMatch [ 1 ] . replace ( /^\[|\]$/g , "" ) . replace ( /^::ffff:/i , "" ) ;
2023-09-02 18:15:00 +02:00
port = parseInt ( portLMatch [ 2 ] ) ;
}
}
}
2023-07-29 20:32:17 +02:00
if ( configJSON . domian != undefined ) domain = configJSON . domian ;
if ( configJSON . domain != undefined ) domain = configJSON . domain ;
if ( configJSON . sport != undefined ) sport = configJSON . sport ;
2023-09-02 18:15:00 +02:00
if ( typeof sport === "string" ) {
2023-12-03 13:58:35 +01:00
if ( sport . match ( /^[0-9]+$/ ) ) {
2023-09-02 18:15:00 +02:00
sport = parseInt ( sport ) ;
} else {
var sportLMatch = sport . match ( /^(\[[^ \]@\/\\]+\]|[^ \]\[:@\/\\]+):([0-9]+)$/ ) ;
2023-12-03 13:58:35 +01:00
if ( sportLMatch ) {
sListenAddress = sportLMatch [ 1 ] . replace ( /^\[|\]$/g , "" ) . replace ( /^::ffff:/i , "" ) ;
2023-09-02 18:15:00 +02:00
sport = parseInt ( sportLMatch [ 2 ] ) ;
}
}
}
2023-07-29 20:32:17 +02:00
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 ;
2023-08-12 13:37:06 +02:00
if ( configJSON . disableUnusedWorkerTermination != undefined ) disableUnusedWorkerTermination = configJSON . disableUnusedWorkerTermination ;
2023-08-18 23:29:18 +02:00
if ( configJSON . rewriteDirtyURLs != undefined ) rewriteDirtyURLs = configJSON . rewriteDirtyURLs ;
2023-08-31 22:47:07 +02:00
if ( configJSON . errorPages != undefined ) errorPages = configJSON . errorPages ;
2023-09-02 12:57:19 +02:00
if ( configJSON . useWebRootServerSideScript != undefined ) useWebRootServerSideScript = configJSON . useWebRootServerSideScript ;
2023-09-05 00:15:00 +02:00
if ( configJSON . exposeModsInErrorPages != undefined ) exposeModsInErrorPages = configJSON . exposeModsInErrorPages ;
2023-12-03 12:11:15 +01:00
if ( configJSON . disableTrailingSlashRedirects != undefined ) disableTrailingSlashRedirects = configJSON . disableTrailingSlashRedirects ;
if ( configJSON . environmentVariables != undefined ) environmentVariables = configJSON . environmentVariables ;
2023-09-10 18:37:09 +02:00
var wwwrootError = null ;
try {
if ( cluster . isPrimary || cluster . isPrimary === undefined ) process . chdir ( configJSON . wwwroot != undefined ? configJSON . wwwroot : _ _dirname ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-09-10 18:37:09 +02:00
wwwrootError = err ;
2023-07-29 20:32:17 +02:00
}
2023-12-03 12:11:15 +01:00
try {
2023-12-03 13:58:35 +01:00
Object . keys ( environmentVariables ) . forEach ( function ( key ) {
2023-12-03 13:55:56 +01:00
process . env [ key ] = environmentVariables [ key ] ;
2023-12-03 12:11:15 +01:00
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-12-03 13:55:56 +01:00
// Failed to set environment variables.
2023-12-03 12:11:15 +01:00
}
2023-09-03 11:08:16 +02:00
// Compability for older mods
2023-07-29 20:32:17 +02:00
configJSON . version = version ;
configJSON . productName = "SVR.JS" ;
var blacklist = ipBlockList ( rawBlackList ) ;
var nonStandardCodes = [ ] ;
2023-08-19 22:38:58 +02:00
nonStandardCodesRaw . forEach ( function ( nonStandardCodeRaw ) {
2023-08-29 14:56:39 +02:00
var newObject = { } ;
2023-08-19 22:38:58 +02:00
Object . keys ( nonStandardCodeRaw ) . forEach ( function ( nsKey ) {
if ( nsKey != "users" ) {
2023-08-29 14:56:39 +02:00
newObject [ nsKey ] = nonStandardCodeRaw [ nsKey ] ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-29 14:56:39 +02:00
newObject [ "users" ] = ipBlockList ( nonStandardCodeRaw . users ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-19 22:38:58 +02:00
} ) ;
2023-08-29 14:56:39 +02:00
nonStandardCodes . push ( newObject ) ;
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:32:17 +02:00
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 ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Version number not retrieved
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
2023-07-29 20:32:17 +02:00
if ( vnum === undefined ) vnum = 0 ;
2023-07-29 20:44:13 +02:00
if ( process . isBun ) vnum = 64 ;
2023-07-29 20:32:17 +02:00
function sanitizeURL ( resource ) {
if ( resource == "*" ) return "*" ;
if ( resource == "" ) return "" ;
// Remove null characters
2023-12-03 13:58:35 +01:00
resource = resource . replace ( /%00/ig , "" ) . replace ( /\0/g , "" ) ;
2023-07-29 20:32:17 +02:00
// 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 ) ) ;
2023-08-18 21:54:58 +02:00
return /(?!["<>^`{|}?#%])[!-~]/ . test ( decodedChar ) ? decodedChar : "%" + hex ;
} ) ;
// Encode certain characters
resource = resource . replace ( /[<>^`{|}]]/g , function ( character ) {
var charCode = character . charCodeAt ( 0 ) ;
2023-08-31 23:03:02 +02:00
return "%" + ( charCode < 16 ? "0" : "" ) + charCode . toString ( 16 ) . toUpperCase ( ) ;
2023-07-29 20:32:17 +02:00
} ) ;
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 ;
}
2023-08-12 17:40:42 +02:00
function fixNodeMojibakeURL ( string ) {
var encoded = "" ;
2023-09-03 11:08:16 +02:00
//Encode URLs
2023-08-18 21:54:58 +02:00
Buffer . from ( string , "latin1" ) . forEach ( function ( value ) {
2023-12-03 13:58:35 +01:00
if ( value > 127 ) {
2023-08-12 17:40:42 +02:00
encoded += "%" + ( value < 16 ? "0" : "" ) + value . toString ( 16 ) . toUpperCase ( ) ;
} else {
2023-08-18 21:54:58 +02:00
encoded += String . fromCodePoint ( value ) ;
2023-08-12 17:40:42 +02:00
}
} ) ;
2023-09-03 11:08:16 +02:00
//Upper case the URL encodings
2023-08-18 21:54:58 +02:00
return encoded . replace ( /%[0-9a-f-A-F]{2}/g , function ( match ) {
return match . toUpperCase ( ) ;
} ) ;
2023-08-12 17:40:42 +02:00
}
2023-07-29 20:32:17 +02:00
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 ( ) ;
}
2023-09-10 10:35:07 +02:00
var certificateError = null ;
2023-09-11 21:50:42 +02:00
2023-09-03 11:08:16 +02:00
// Load SNI
2023-07-29 20:32:17 +02:00
if ( secure ) {
2023-09-10 10:35:07 +02:00
try {
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 = [ ] ;
sniNames . forEach ( function ( sniName ) {
sniCredentials . push ( {
name : sniName ,
cert : fs . readFileSync ( ( sni [ sniName ] . cert [ 0 ] != "/" && ! sni [ sniName ] . cert . match ( /^[A-Z0-9]:\\/ ) ) ? _ _dirname + "/" + sni [ sniName ] . cert : sni [ sniName ] . cert ) . toString ( ) ,
key : fs . readFileSync ( ( sni [ sniName ] . key [ 0 ] != "/" && ! sni [ sniName ] . key . match ( /^[A-Z0-9]:\\/ ) ) ? _ _dirname + "/" + sni [ sniName ] . key : sni [ sniName ] . key ) . toString ( )
} ) ;
2023-07-29 20:32:17 +02:00
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-09-10 10:35:07 +02:00
certificateError = err ;
}
2023-07-29 20:32:17 +02:00
}
var logFile = undefined ;
var logSync = false ;
2023-09-03 11:08:16 +02:00
// Logging function
2023-07-29 20:32:17 +02:00
function LOG ( s ) {
try {
if ( configJSON . enableLogging || configJSON . enableLogging == undefined ) {
if ( logSync ) {
2023-08-09 18:01:36 +02:00
fs . appendFileSync ( _ _dirname + "/log/" + ( cluster . isPrimary ? "master" : ( cluster . isPrimary === undefined ? "singlethread" : "worker" ) ) + "-" + timestamp + ".log" , "[" + new Date ( ) . toISOString ( ) + "] " + s + "\r\n" ) ;
2023-07-29 20:32:17 +02:00
} else {
if ( ! logFile ) {
2023-08-09 18:01:36 +02:00
logFile = fs . createWriteStream ( _ _dirname + "/log/" + ( cluster . isPrimary ? "master" : ( cluster . isPrimary === undefined ? "singlethread" : "worker" ) ) + "-" + timestamp + ".log" , {
2023-07-29 20:32:17 +02:00
flags : "a" ,
autoClose : false
} ) ;
}
if ( logFile . writable ) {
logFile . write ( "[" + new Date ( ) . toISOString ( ) + "] " + s + "\r\n" ) ;
} else {
throw new Error ( "Log file stream is closed." ) ;
}
}
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
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: / ) && ! reallyExiting ) serverconsole . locwarnmessage ( "There was a problem while saving logs! Logs will not be kept in log file. Reason: " + err . message ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 11:08:16 +02:00
// Server console function
2023-07-29 20:32:17 +02:00
var serverconsole = {
climessage : function ( msg ) {
if ( msg . indexOf ( "\n" ) != - 1 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . climessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
return ;
}
console . log ( "SERVER CLI MESSAGE: " + msg ) ;
LOG ( "SERVER CLI MESSAGE: " + msg ) ;
return ;
} ,
reqmessage : function ( msg ) {
if ( msg . indexOf ( "\n" ) != - 1 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . reqmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . resmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . errmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locerrmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locwarnmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
return ;
}
console . log ( "SERVER MESSAGE: " + msg ) ;
LOG ( "SERVER MESSAGE: " + msg ) ;
return ;
}
} ;
2023-09-03 11:08:16 +02:00
// Wrap around process.exit, so log contents can flush.
2023-07-29 20:32:17 +02:00
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 ) ;
} ) ;
2023-07-29 20:44:13 +02:00
if ( process . isBun ) {
setInterval ( function ( ) {
if ( ! logFile . writable ) {
logFile = undefined ;
logSync = true ;
process . unsafeExit ( code ) ;
}
2023-09-03 11:08:16 +02:00
} , 50 ) ; // Interval
2023-07-29 20:44:13 +02:00
}
2023-07-29 20:32:17 +02:00
setTimeout ( function ( ) {
logFile = undefined ;
logSync = true ;
process . unsafeExit ( code ) ;
2023-09-03 11:08:16 +02:00
} , 10000 ) ; // timeout
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
logFile = undefined ;
logSync = true ;
process . unsafeExit ( code ) ;
}
} else {
logSync = true ;
process . unsafeExit ( code ) ;
}
} ;
2023-09-02 20:27:27 +02:00
var modLoadingErrors = [ ] ;
var SSJSError = undefined ;
2023-09-08 19:26:40 +02:00
var svrmodpackUsed = false ;
2023-09-02 20:27:27 +02:00
2023-07-29 20:44:13 +02:00
// Load mods if the `disableMods` flag is not set
2023-07-29 20:32:17 +02:00
if ( ! disableMods ) {
2023-07-29 20:44:13 +02:00
// Define the modloader folder name
2023-07-29 20:32:17 +02:00
var modloaderFolderName = "modloader" ;
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === false ) {
2023-07-29 20:44:13 +02:00
// If not the master process, create a unique modloader folder name for each worker
2023-07-29 20:32:17 +02:00
modloaderFolderName = ".modloader_w" + Math . floor ( Math . random ( ) * 65536 ) ;
}
2023-08-12 12:35:46 +02:00
2023-08-04 21:19:23 +02:00
// Define the temporary server-side JavaScript file name
var tempServerSideScriptName = "serverSideScript.js" ;
2023-09-10 19:03:28 +02:00
if ( ! ( process . isBun && process . versions . bun && process . versions . bun [ 0 ] == "0" ) && cluster . isPrimary === false ) {
2023-08-04 21:19:23 +02:00
// If not the master process and it's not Bun, create a unique temporary server-side JavaScript file name for each worker
tempServerSideScriptName = ".serverSideScript_w" + Math . floor ( Math . random ( ) * 65536 ) + ".js" ;
}
2023-07-29 20:44:13 +02:00
// Iterate through the list of mod files
2023-08-19 22:38:58 +02:00
modFiles . forEach ( function ( modFileRaw ) {
2023-07-29 20:44:13 +02:00
// Build the path to the current mod file
2023-08-19 22:38:58 +02:00
var modFile = _ _dirname + "/mods/" + modFileRaw ;
2023-07-29 20:44:13 +02:00
2023-07-29 20:32:17 +02:00
try {
2023-07-29 20:44:13 +02:00
// Try creating the modloader folder (if not already exists)
2023-07-29 20:32:17 +02:00
try {
fs . mkdirSync ( _ _dirname + "/temp/" + modloaderFolderName ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:44:13 +02:00
// If the folder already exists, continue to the next step
2023-08-02 23:54:07 +02:00
if ( err . code != "EEXIST" ) {
2023-07-29 20:44:13 +02:00
// If there was another error, try creating the temp folder and then the modloader folder again
2023-07-29 20:32:17 +02:00
fs . mkdirSync ( _ _dirname + "/temp" ) ;
try {
fs . mkdirSync ( _ _dirname + "/temp/" + modloaderFolderName ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:44:13 +02:00
// If there was another error, throw it
2023-08-02 23:54:07 +02:00
if ( err . code != "EEXIST" ) throw err ;
2023-07-29 20:32:17 +02:00
}
}
}
2023-07-29 20:44:13 +02:00
// Create a subfolder for the current mod within the modloader folder
2023-08-19 22:38:58 +02:00
fs . mkdirSync ( _ _dirname + "/temp/" + modloaderFolderName + "/" + modFileRaw ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:44:13 +02:00
// If there was an error creating the folder, ignore it if it's a known error
2023-08-02 23:54:07 +02:00
if ( err . code != "EEXIST" && err . code != "ENOENT" ) throw err ;
2023-07-29 20:44:13 +02:00
// Some other SVR.JS process may have created the files.
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
// Check if the current mod file is a regular file
2023-07-29 20:32:17 +02:00
if ( fs . statSync ( modFile ) . isFile ( ) ) {
try {
2023-07-29 20:44:13 +02:00
// Determine if the mod file is a ".tar.gz" file or not
if ( modFile . indexOf ( ".tar.gz" ) == modFile . length - 7 ) {
// If it's a ".tar.gz" file, extract its contents using `tar`
if ( tar . _errored ) throw tar . _errored ;
tar . x ( {
file : modFile ,
sync : true ,
2023-08-19 22:38:58 +02:00
C : _ _dirname + "/temp/" + modloaderFolderName + "/" + modFileRaw
2023-07-29 20:44:13 +02:00
} ) ;
} else {
// If it's not a ".tar.gz" file, unpack it using `svrmodpack`
if ( svrmodpack . _errored ) throw svrmodpack . _errored ;
2023-08-19 22:38:58 +02:00
svrmodpack . unpack ( modFile , _ _dirname + "/temp/" + modloaderFolderName + "/" + modFileRaw ) ;
2023-09-08 20:17:38 +02:00
svrmodpackUsed = true ;
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
// Initialize variables for mod loading
2023-07-29 20:32:17 +02:00
var Mod = undefined ;
var mod = undefined ;
2023-07-29 20:44:13 +02:00
// Attempt to require the mod's index.js file, retrying up to 3 times in case of syntax errors
2023-07-29 20:32:17 +02:00
for ( var j = 0 ; j < 3 ; j ++ ) {
try {
2023-08-19 22:38:58 +02:00
Mod = require ( "./temp/" + modloaderFolderName + "/" + modFileRaw + "/index.js" ) ;
2023-07-29 20:32:17 +02:00
mod = new Mod ( ) ;
break ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
if ( j >= 2 || err . name == "SyntaxError" ) throw err ;
2023-07-29 20:44:13 +02:00
// Wait for a short time before retrying
2023-07-29 20:32:17 +02:00
var now = Date . now ( ) ;
while ( Date . now ( ) - now < 2 ) ;
2023-07-29 20:44:13 +02:00
// Try reloading mod
2023-07-29 20:32:17 +02:00
}
}
2023-07-29 20:44:13 +02:00
// Add the loaded mod to the mods list
2023-07-29 20:32:17 +02:00
mods . push ( mod ) ;
2023-07-29 20:44:13 +02:00
// Attempt to read the mod's info file, retrying up to 3 times
2023-07-29 20:32:17 +02:00
for ( var j = 0 ; j < 3 ; j ++ ) {
try {
2023-08-19 22:38:58 +02:00
modInfos . push ( JSON . parse ( fs . readFileSync ( _ _dirname + "/temp/" + modloaderFolderName + "/" + modFileRaw + "/mod.info" ) ) ) ;
2023-07-29 20:32:17 +02:00
break ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
if ( j >= 2 ) {
2023-07-29 20:44:13 +02:00
// If failed to read info file, add a placeholder entry to modInfos with an error message
2023-07-29 20:32:17 +02:00
modInfos . push ( {
2023-08-19 22:38:58 +02:00
name : "Unknown mod (" + modFileRaw + ";" + err . message + ")" ,
2023-07-29 20:32:17 +02:00
version : "ERROR"
} ) ;
}
2023-07-29 20:44:13 +02:00
// Wait for a short time before retrying
var now = Date . now ( ) ;
while ( Date . now ( ) - now < 2 ) ;
// Try reloading mod info
2023-07-29 20:32:17 +02:00
}
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-12-03 13:58:35 +01:00
modLoadingErrors . push ( {
error : err ,
modName : modFileRaw
} ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:44:13 +02:00
2023-09-02 12:57:19 +02:00
// Determine path of server-side script file
var SSJSPath = "./serverSideScript.js" ;
if ( ! useWebRootServerSideScript ) SSJSPath = _ _dirname + "/serverSideScript.js" ;
2023-07-29 20:44:13 +02:00
// Check if a custom server side script file exists
2023-09-02 12:57:19 +02:00
if ( fs . existsSync ( SSJSPath ) && fs . statSync ( SSJSPath ) . isFile ( ) ) {
2023-07-29 20:32:17 +02:00
try {
2023-07-29 20:44:13 +02:00
// Prepend necessary modules and variables to the custom server side script
2023-09-01 01:13:15 +02:00
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(e){var r={};return Object.keys(e).forEach((function(t){null!==e[t]&&void 0!==e[t]&&(\"object\"==typeof e[t]?r[t]=JSON.parse(JSON.stringify(e[t])):r[t]=e[t])})),r}\r\nfunction checkHostname(e){if(void 0===e||\"*\"==e)return!0;if(req.headers.host&&0==e.indexOf(\"*.\")&&\"*.\"!=e){var r=e.substr(2);if(req.headers.host==r||req.headers.host.indexOf(\".\"+r)==req.headers.host.length-r.length-1)return!0}else if(req.headers.host&&req.headers.host==e)return!0;return!1}\r\nfunction checkHref(e){return href==e||\"win32\"==os.platform()&&href.toLowerCase()==e.toLowerCase()}\r\n" ;
2023-08-02 23:54:07 +02:00
var modfoot = "\r\nif(!disableEndElseCallbackExecute) {\r\ntry{\r\nelseCallback();\r\n} catch(err) {\r\n}\r\n}\r\n}\r\n}\r\nmodule.exports = Mod;" ;
2023-07-29 20:44:13 +02:00
// Write the modified server side script to the temp folder
2023-09-02 12:57:19 +02:00
fs . writeFileSync ( _ _dirname + "/temp/" + tempServerSideScriptName , modhead + fs . readFileSync ( SSJSPath ) + modfoot ) ;
2023-07-29 20:44:13 +02:00
// Initialize variables for server side script loading
2023-07-29 20:32:17 +02:00
var aMod = undefined ;
var amod = undefined ;
2023-07-29 20:44:13 +02:00
2023-08-04 21:19:23 +02:00
// Attempt to require the custom server side script, retrying up to 5 times
for ( var i = 0 ; i < 5 ; i ++ ) {
2023-07-29 20:32:17 +02:00
try {
2023-08-04 21:19:23 +02:00
aMod = require ( "./temp/" + tempServerSideScriptName ) ;
2023-07-29 20:32:17 +02:00
amod = new aMod ( ) ;
break ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-08-04 21:19:23 +02:00
if ( i >= 4 || err . name == "SyntaxError" ) throw err ;
2023-07-29 20:44:13 +02:00
// Wait for a short time before retrying
2023-07-29 20:32:17 +02:00
var now = Date . now ( ) ;
while ( Date . now ( ) - now < 2 ) ;
2023-07-29 20:44:13 +02:00
// Try reloading mod
2023-07-29 20:32:17 +02:00
}
}
2023-07-29 20:44:13 +02:00
// Add the loaded server side script to the mods list
2023-07-29 20:32:17 +02:00
mods . push ( amod ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-02 20:27:27 +02:00
SSJSError = err ;
2023-07-29 20:32:17 +02:00
}
}
}
2023-07-29 20:44:13 +02:00
2023-09-03 11:08:16 +02:00
// SHA256 function
2023-07-29 20:32:17 +02:00
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 ;
}
}
2023-07-29 20:44:13 +02:00
function isForbiddenPath ( decodedHref , match ) {
var forbiddenPath = forbiddenPaths [ match ] ;
if ( ! forbiddenPath ) return false ;
if ( typeof forbiddenPath === "string" ) {
return decodedHref === forbiddenPath || ( os . platform ( ) === "win32" && decodedHref . toLowerCase ( ) === forbiddenPath . toLowerCase ( ) ) ;
}
if ( typeof forbiddenPath === "object" ) {
2023-08-19 22:38:58 +02:00
return forbiddenPath . some ( function ( forbiddenPathSingle ) {
return ( decodedHref === forbiddenPathSingle || ( os . platform ( ) === "win32" && decodedHref . toLowerCase ( ) === forbiddenPathSingle . toLowerCase ( ) ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
return false ;
}
2023-07-29 20:44:13 +02:00
function isIndexOfForbiddenPath ( decodedHref , match ) {
var forbiddenPath = forbiddenPaths [ match ] ;
if ( ! forbiddenPath ) return false ;
if ( typeof forbiddenPath === "string" ) {
2023-08-02 23:54:07 +02:00
return decodedHref === forbiddenPath || decodedHref . indexOf ( forbiddenPath + "/" ) === 0 || ( os . platform ( ) === "win32" && ( decodedHref . toLowerCase ( ) === forbiddenPath . toLowerCase ( ) || decodedHref . toLowerCase ( ) . indexOf ( forbiddenPath . toLowerCase ( ) + "/" ) === 0 ) ) ;
2023-07-29 20:44:13 +02:00
}
if ( typeof forbiddenPath === "object" ) {
2023-08-19 22:38:58 +02:00
return forbiddenPath . some ( function ( forbiddenPathSingle ) {
return ( decodedHref === forbiddenPathSingle || decodedHref . indexOf ( forbiddenPathSingle + "/" ) === 0 || ( os . platform ( ) === "win32" && ( decodedHref . toLowerCase ( ) === forbiddenPathSingle . toLowerCase ( ) || decodedHref . toLowerCase ( ) . indexOf ( forbiddenPathSingle . toLowerCase ( ) + "/" ) === 0 ) ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
return false ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 11:08:16 +02:00
// Set up forbidden paths
2023-07-29 20:32:17 +02:00
var forbiddenPaths = { } ;
forbiddenPaths . config = getInitializePath ( "./config.json" ) ;
forbiddenPaths . certificates = [ ] ;
if ( secure ) {
forbiddenPaths . certificates . push ( getInitializePath ( configJSON . cert ) ) ;
forbiddenPaths . certificates . push ( getInitializePath ( configJSON . key ) ) ;
2023-08-19 22:38:58 +02:00
Object . keys ( sni ) . forEach ( function ( sniHostName ) {
forbiddenPaths . certificates . push ( getInitializePath ( sni [ sniHostName ] . cert ) ) ;
forbiddenPaths . certificates . push ( getInitializePath ( sni [ sniHostName ] . key ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
forbiddenPaths . svrjs = getInitializePath ( "./" + ( ( _ _dirname [ _ _dirname . length - 1 ] != "/" ) ? _ _filename . replace ( _ _dirname + "/" , "" ) : _ _filename . replace ( _ _dirname , "" ) ) ) ;
forbiddenPaths . serverSideScripts = [ ] ;
2023-09-02 12:57:19 +02:00
if ( useWebRootServerSideScript ) {
forbiddenPaths . serverSideScripts . push ( "/serverSideScript.js" ) ;
} else {
forbiddenPaths . serverSideScripts . push ( getInitializePath ( "./serverSideScript.js" ) ) ;
}
2023-07-29 20:32:17 +02:00
forbiddenPaths . serverSideScriptDirectories = [ ] ;
forbiddenPaths . serverSideScriptDirectories . push ( getInitializePath ( "./node_modules" ) ) ;
forbiddenPaths . serverSideScriptDirectories . push ( getInitializePath ( "./mods" ) ) ;
2023-09-09 00:36:24 +02:00
forbiddenPaths . temp = getInitializePath ( "./temp" ) ;
2023-07-29 20:32:17 +02:00
forbiddenPaths . log = getInitializePath ( "./log" ) ;
2023-09-11 11:06:03 +02:00
// Error descriptions
var serverErrorDescs = {
200 : "The request succeeded! :)" ,
2023-11-12 19:47:32 +01:00
201 : "A new resource has been created." ,
2023-09-11 11:06:03 +02:00
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." ,
2023-11-12 18:59:24 +01:00
404 : "The requested file doesn't exist. If you have typed the URL manually, then please check the spelling." ,
2023-09-11 11:06:03 +02:00
405 : "Method used to access the requested file isn't allowed." ,
2023-11-12 19:47:32 +01:00
406 : "The request is capable of generating only unacceptable content." ,
2023-09-11 11:06:03 +02:00
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." ,
2023-11-12 18:59:24 +01:00
412 : "The server doesn't meet the preconditions you put in the request." ,
2023-09-11 11:06:03 +02:00
413 : "The request you sent is too large." ,
2023-11-12 18:59:24 +01:00
414 : "The URL you sent is too long." ,
2023-09-11 11:06:03 +02:00
415 : "The media type of request you sent isn't supported by the server." ,
2023-11-12 19:47:32 +01:00
416 : "The requested content range (Content-Range header) you sent is unsatisfiable." ,
417 : "The expectation specified in the Expect property couldn't be satisfied." ,
2023-09-11 11:06:03 +02:00
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." ,
2023-11-12 18:59:24 +01:00
426 : "You need to upgrade the protocols you use to request a file." ,
2023-09-11 11:06:03 +02:00
428 : "The request you sent needs to be conditional, but it isn't." ,
2023-11-12 18:59:24 +01:00
429 : "You sent too many requests to the server." ,
2023-11-12 19:47:32 +01:00
431 : "The request you sent contains headers that are too large." ,
2023-09-11 11:06:03 +02:00
451 : "The requested file isn't accessible for legal reasons." ,
2023-11-12 18:59:24 +01:00
497 : "You sent a non-TLS request to the HTTPS server." ,
2023-11-12 19:47:32 +01:00
500 : "The server had an unexpected error. Below, the error stack is shown: </p><code>{stack}</code><p>You may need to contact the server administrator at <i>{contact}</i>." ,
2023-11-12 18:59:24 +01:00
501 : "The request requires the use of a function, which isn't currently implemented by the server." ,
2023-11-12 19:47:32 +01:00
502 : "The server had an error while it was acting as a gateway.</p><p>You may need to contact the server administrator at <i>{contact}</i>." ,
503 : "The service provided by the server is currently unavailable, possibly due to maintenance downtime or capacity problems. Please try again later.</p><p>You may need to contact the server administrator at <i>{contact}</i>." ,
504 : "The server couldn't get a response in time while it was acting as a gateway.</p><p>You may need to contact the server administrator at <i>{contact}</i>." ,
505 : "The server doesn't support the HTTP version used in the request." ,
506 : "The Variant header is configured to be engaged in content negotiation.</p><p>You may need to contact the server administrator at <i>{contact}</i>." ,
2023-11-12 18:59:24 +01:00
507 : "The server ran out of disk space necessary to complete the request." ,
2023-09-11 11:06:03 +02:00
508 : "The server detected an infinite loop while processing the request." ,
2023-11-12 19:47:32 +01:00
509 : "The server has its bandwidth limit exceeded.</p><p>You may need to contact the server administrator at <i>{contact}</i>." ,
2023-09-11 11:06:03 +02:00
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." ,
2023-11-12 19:47:32 +01:00
598 : "The server couldn't get a 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."
2023-09-11 11:06:03 +02:00
} ;
2023-09-03 11:08:16 +02:00
// Create server
2023-08-09 18:01:36 +02:00
if ( ! cluster . isPrimary ) {
2023-07-29 20:32:17 +02:00
var reqcounter = 0 ;
2023-08-09 21:09:23 +02:00
var reqcounterKillReq = 0 ;
2023-07-29 20:32:17 +02:00
var server = { } ;
var server2 = { } ;
try {
server2 = http . createServer ( {
requireHostHeader : false
} ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
server2 = http . createServer ( ) ;
}
2023-09-02 19:56:45 +02:00
server2 . on ( "request" , function ( req , res ) {
reqhandler ( req , res , false ) ;
} ) ;
server2 . on ( "checkExpectation" , reqhandler ) ;
server2 . on ( "clientError" , function ( err , socket ) {
reqerrhandler ( err , socket , false ) ;
} ) ;
2023-07-29 20:32:17 +02:00
if ( ! disableToHTTPSRedirect ) {
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . climessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . reqmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . resmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . errmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locerrmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locwarnmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ;
2023-07-29 20:44:13 +02:00
serverconsole . locmessage ( "Somebody connected to " + ( typeof port == "number" ? "port " : "socket " ) + port + "..." ) ;
2023-08-09 21:09:23 +02:00
reqcounter ++ ;
2023-07-29 20:32:17 +02:00
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" ) ;
} ) ;
} else {
server2 . on ( "connect" , connhandler ) ;
}
2023-09-03 11:08:16 +02:00
2023-07-29 20:32:17 +02:00
server2 . on ( "error" , function ( err ) {
2023-08-12 12:47:48 +02:00
attmtsRedir -- ;
2023-08-12 13:23:59 +02:00
if ( cluster . isPrimary === undefined && attmtsRedir >= 0 ) {
2023-08-12 12:47:48 +02:00
if ( err . code == "EADDRINUSE" ) {
serverconsole . locerrmessage ( "Address is already in use by another process." ) ;
} else if ( err . code == "EADDRNOTAVAIL" ) {
serverconsole . locerrmessage ( "Address is not available on this machine." ) ;
} else if ( err . code == "EACCES" ) {
serverconsole . locerrmessage ( "Permission denied. You may not have sufficient privileges to access the requested address." ) ;
} else if ( err . code == "EAFNOSUPPORT" ) {
serverconsole . locerrmessage ( "Address family not supported. The address family (IPv4 or IPv6) of the requested address is not supported." ) ;
} else if ( err . code == "EALREADY" ) {
serverconsole . locerrmessage ( "Operation already in progress. The server is already in the process of establishing a connection on the requested address." ) ;
} else if ( err . code == "ECONNABORTED" ) {
serverconsole . locerrmessage ( "Connection aborted. The connection to the server was terminated abruptly." ) ;
} else if ( err . code == "ECONNREFUSED" ) {
serverconsole . locerrmessage ( "Connection refused. The server refused the connection attempt." ) ;
} else if ( err . code == "ECONNRESET" ) {
serverconsole . locerrmessage ( "Connection reset by peer. The connection to the server was reset by the remote host." ) ;
} else if ( err . code == "EDESTADDRREQ" ) {
serverconsole . locerrmessage ( "Destination address required. The destination address must be specified." ) ;
} else if ( err . code == "ENETDOWN" ) {
serverconsole . locerrmessage ( "Network is down. The network interface used for the connection is not available." ) ;
} else if ( err . code == "ENETUNREACH" ) {
serverconsole . locerrmessage ( "Network is unreachable. The network destination is not reachable from this host." ) ;
} else if ( err . code == "ENOBUFS" ) {
serverconsole . locerrmessage ( "No buffer space available. Insufficient buffer space is available for the server to process the request." ) ;
} else if ( err . code == "ENOTSOCK" ) {
serverconsole . locerrmessage ( "Not a socket. The file descriptor provided is not a valid socket." ) ;
} else if ( err . code == "EPROTO" ) {
serverconsole . locerrmessage ( "Protocol error. An unspecified protocol error occurred." ) ;
} else if ( err . code == "EPROTONOSUPPORT" ) {
serverconsole . locerrmessage ( "Protocol not supported. The requested network protocol is not supported." ) ;
} else if ( err . code == "ETIMEDOUT" ) {
serverconsole . locerrmessage ( "Connection timed out. The server did not respond within the specified timeout period." ) ;
2023-09-02 18:15:00 +02:00
} else if ( err . code == "ENOTFOUND" ) {
serverconsole . locerrmessage ( "Domain name doesn't exist (invalid IP address?)." ) ;
} else if ( err . code == "EINVAL" ) {
serverconsole . locerrmessage ( "Invalid argument (invalid IP address?)." ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-12 12:47:48 +02:00
serverconsole . locerrmessage ( "There was an unknown error with the server." ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-12 12:47:48 +02:00
serverconsole . locmessage ( attmtsRedir + " attempts left." ) ;
} else {
2023-08-12 13:23:59 +02:00
try {
process . send ( "\x12ERRLIST" + attmtsRedir + err . code ) ;
2023-12-03 14:00:52 +01:00
} catch ( err ) {
2023-08-12 13:23:59 +02:00
// Probably main process exited
}
2023-08-12 12:47:48 +02:00
}
if ( attmtsRedir > 0 ) {
server2 . close ( ) ;
setTimeout ( start , 900 ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-12 13:23:59 +02:00
try {
if ( cluster . isPrimary !== undefined ) process . send ( "\x12ERRCRASH" + err . code ) ;
2023-12-03 14:00:52 +01:00
} catch ( err ) {
2023-08-12 13:23:59 +02:00
// Probably main process exited
}
setTimeout ( function ( ) {
var errno = errors [ err . code ] ;
2023-12-03 13:58:35 +01:00
if ( errno ) {
2023-08-12 13:23:59 +02:00
process . exit ( errno ) ;
} else {
process . exit ( 1 ) ;
}
} , 50 ) ;
2023-07-29 20:32:17 +02:00
}
} ) ;
2023-08-09 22:37:53 +02:00
server2 . on ( "listening" , function ( ) {
2023-09-03 10:27:30 +02:00
attmtsRedir = 5 ;
2023-07-29 20:32:17 +02:00
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
} ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
server = http . createServer ( ) ;
}
}
}
if ( secure ) {
2023-08-19 22:38:58 +02:00
sniCredentials . forEach ( function ( sniCredentialsSingle ) {
server . addContext ( sniCredentialsSingle . name , {
cert : sniCredentialsSingle . cert ,
key : sniCredentialsSingle . key
2023-07-29 20:32:17 +02:00
} ) ;
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:32:17 +02:00
}
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 ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Socket is probably already destroyed.
2023-07-29 20:32:17 +02:00
}
} ;
} else {
sock . _parent . destroy = sock . _parent . reallyDestroy ;
try {
if ( sock . _parent . toDestroy ) sock . _parent . destroy ( ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Socket is probably already destroyed.
2023-07-29 20:32:17 +02:00
}
}
} ) ;
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 ) ;
} ) ;
} ) ;
}
}
2023-09-03 11:08:16 +02:00
// Patches from Node.JS v18.0.0
2023-07-29 20:32:17 +02:00
if ( server . requestTimeout !== undefined && server . requestTimeout === 0 ) server . requestTimeout = 300000 ;
if ( server2 . requestTimeout !== undefined && server2 . requestTimeout === 0 ) server2 . requestTimeout = 300000 ;
2023-09-03 10:27:30 +02:00
2023-07-29 20:32:17 +02:00
function reqerrhandler ( err , socket , fromMain ) {
if ( fromMain === undefined ) fromMain = true ;
2023-09-03 11:08:16 +02:00
// Define response object similar to Node.JS native one
2023-07-29 20:32:17 +02:00
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 ( ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Socket is probably already destroyed
2023-07-29 20:32:17 +02:00
}
} ) ;
} ;
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" ;
2023-08-19 22:38:58 +02:00
Object . keys ( headers ) . forEach ( function ( headername ) {
if ( headername . toLowerCase ( ) == "set-cookie" ) {
headers [ headername ] . forEach ( function ( headerValueS ) {
if ( headername . match ( /[^\x09\x20-\x7e\x80-\xff]|.:/ ) || headerValueS . match ( /[^\x09\x20-\x7e\x80-\xff]/ ) ) throw new Error ( "Invalid header!!! (" + headername + ")" ) ;
head += ( headername + ": " + headerValueS ) ;
} ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-21 19:32:31 +02:00
if ( headername . match ( /[^\x09\x20-\x7e\x80-\xff]|.:/ ) || headers [ headername ] . match ( /[^\x09\x20-\x7e\x80-\xff]/ ) ) throw new Error ( "Invalid header!!! (" + headername + ")" ) ;
2023-08-19 22:38:58 +02:00
head += ( headername + ": " + headers [ headername ] ) ;
2023-07-29 20:32:17 +02:00
}
head += "\r\n" ;
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . climessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . reqmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . resmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . errmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locerrmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locwarnmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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
2023-09-11 23:21:14 +02:00
function responseEnd ( body ) {
//If body is Buffer, then it is converted to String anyway.
res . write ( head + body + foot ) ;
2023-07-29 20:32:17 +02:00
res . end ( ) ;
}
2023-09-03 11:08:16 +02:00
// Server error calling method
2023-07-29 20:32:17 +02:00
function callServerError ( errorCode , extName , stack , ch ) {
2023-08-31 22:47:07 +02:00
function getErrorFileName ( list , callback , _i ) {
2023-12-03 13:58:35 +01:00
if ( err . code == "ERR_SSL_HTTP_REQUEST" && process . version && parseInt ( process . version . split ( "." ) [ 0 ] . substr ( 1 ) ) >= 16 ) {
2023-09-03 11:08:16 +02:00
// Disable custom error page for HTTP SSL error
2023-08-31 22:47:07 +02:00
callback ( errorCode . toString ( ) + ".html" ) ;
return ;
}
2023-12-03 13:58:35 +01:00
2023-08-31 22:47:07 +02:00
function medCallback ( p ) {
2023-12-03 13:58:35 +01:00
if ( p ) callback ( p ) ;
2023-08-31 22:47:07 +02:00
else {
2023-12-03 13:58:35 +01:00
if ( errorCode == 404 ) {
fs . access ( page404 , fs . constants . F _OK , function ( err ) {
if ( err ) {
fs . access ( "." + errorCode . toString ( ) , fs . constants . F _OK , function ( err ) {
2023-09-01 11:04:04 +02:00
try {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-01 11:04:04 +02:00
callback ( errorCode . toString ( ) + ".html" ) ;
} else {
2023-09-09 00:53:24 +02:00
callback ( "." + errorCode . toString ( ) ) ;
2023-09-01 11:04:04 +02:00
}
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-09-01 11:04:04 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
2023-08-31 22:47:07 +02:00
}
2023-09-01 11:04:04 +02:00
} ) ;
} else {
try {
callback ( page404 ) ;
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-08-31 22:47:07 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
}
2023-09-01 11:04:04 +02:00
}
} ) ;
} else {
2023-12-03 13:58:35 +01:00
fs . access ( "." + errorCode . toString ( ) , fs . constants . F _OK , function ( err ) {
2023-08-31 22:47:07 +02:00
try {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-01 11:04:04 +02:00
callback ( errorCode . toString ( ) + ".html" ) ;
} else {
2023-09-09 00:53:24 +02:00
callback ( "." + errorCode . toString ( ) ) ;
2023-09-01 11:04:04 +02:00
}
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-08-31 22:47:07 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
}
2023-09-01 11:04:04 +02:00
} ) ;
}
2023-08-31 22:47:07 +02:00
}
}
2023-09-03 10:27:30 +02:00
2023-12-03 13:58:35 +01:00
if ( ! _i ) _i = 0 ;
if ( _i >= list . length ) {
2023-08-31 22:47:07 +02:00
medCallback ( false ) ;
return ;
}
2023-09-03 10:27:30 +02:00
2023-12-03 13:58:35 +01:00
if ( list [ _i ] . scode != errorCode ) {
getErrorFileName ( list , callback , _i + 1 ) ;
2023-08-31 22:47:07 +02:00
return ;
} else {
2023-12-03 13:58:35 +01:00
fs . access ( list [ _i ] . path , fs . constants . F _OK , function ( err ) {
if ( err ) {
getErrorFileName ( list , callback , _i + 1 ) ;
2023-08-31 22:47:07 +02:00
} else {
2023-09-09 00:53:24 +02:00
medCallback ( list [ _i ] . path ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-21 19:32:31 +02:00
} ) ;
}
2023-07-29 20:32:17 +02:00
}
2023-08-31 22:47:07 +02:00
2023-12-03 13:58:35 +01:00
getErrorFileName ( errorPages , function ( errorFile ) {
2023-08-31 22:47:07 +02:00
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 ) ;
Object . keys ( ch ) . forEach ( function ( chnS ) {
var nhn = chnS ;
for ( var j = 0 ; j < chon . length ; j ++ ) {
if ( chon [ j ] . toLowerCase ( ) == chnS . toLowerCase ( ) ) {
nhn = chon [ j ] ;
break ;
}
}
if ( ch [ chnS ] ) cheaders [ nhn ] = ch [ chnS ] ;
} ) ;
}
cheaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
if ( errorCode == 405 && ! cheaders [ "Allow" ] ) cheaders [ "Allow" ] = "GET, POST, HEAD, OPTIONS" ;
2023-12-03 13:58:35 +01:00
if ( err . code == "ERR_SSL_HTTP_REQUEST" && process . version && parseInt ( process . version . split ( "." ) [ 0 ] . substr ( 1 ) ) >= 16 ) {
2023-09-03 11:08:16 +02:00
// Disable custom error page for HTTP SSL error
2023-08-31 22:47:07 +02:00
res . writeHead ( errorCode , http . STATUS _CODES [ errorCode ] , cheaders ) ;
2023-09-05 00:05:20 +02:00
res . write ( ( "<html><head><title>{errorMessage}</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p><p><i>{server}</i></p></body></html>" ) . replace ( /{errorMessage}/g , errorCode . toString ( ) + " " + http . STATUS _CODES [ errorCode ] ) . replace ( /{errorDesc}/g , serverErrorDescs [ errorCode ] ) . replace ( /{stack}/g , stack . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . 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" ) + ( ( ! exposeModsInErrorPages || extName == undefined ) ? "" : " " + extName ) ) . replace ( /{contact}/g , serverAdmin . replace ( /\./g , "[dot]" ) . replace ( /@/g , "[at]" ) ) ) ;
2023-08-31 22:47:07 +02:00
res . end ( ) ;
} else {
fs . readFile ( errorFile , function ( err , data ) {
try {
if ( err ) throw err ;
res . writeHead ( errorCode , http . STATUS _CODES [ errorCode ] , cheaders ) ;
2023-09-11 23:01:46 +02:00
responseEnd ( 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 ( />/g , ">" ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . 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" ) + ( ( ! exposeModsInErrorPages || extName == undefined ) ? "" : " " + extName ) ) . replace ( /{contact}/g , serverAdmin . replace ( /\./g , "[dot]" ) . replace ( /@/g , "[at]" ) ) ) ;
2023-08-31 22:47:07 +02:00
} catch ( err ) {
var additionalError = 500 ;
if ( err . code == "ENOENT" ) {
additionalError = 404 ;
} else if ( err . code == "ENOTDIR" ) {
additionalError = 404 ; // Assume that file doesn't exist
} else if ( err . code == "EACCES" ) {
additionalError = 403 ;
} else if ( err . code == "ENAMETOOLONG" ) {
additionalError = 414 ;
} else if ( err . code == "EMFILE" ) {
additionalError = 503 ;
} else if ( err . code == "ELOOP" ) {
additionalError = 508 ;
}
res . writeHead ( errorCode , http . STATUS _CODES [ errorCode ] , cheaders ) ;
2023-09-05 00:05:20 +02:00
res . write ( ( "<html><head><title>{errorMessage}</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>" + ( ( additionalError == 404 ) ? "" : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>" ) + "<p><i>{server}</i></p></body></html>" ) . replace ( /{errorMessage}/g , errorCode . toString ( ) + " " + http . STATUS _CODES [ errorCode ] ) . replace ( /{errorDesc}/g , serverErrorDescs [ errorCode ] ) . replace ( /{stack}/g , stack . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . 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" ) + ( ( ! exposeModsInErrorPages || extName == undefined ) ? "" : " " + extName ) ) . replace ( /{contact}/g , serverAdmin . replace ( /\./g , "[dot]" ) . replace ( /@/g , "[at]" ) ) . replace ( /{additionalError}/g , additionalError . toString ( ) ) ) ;
2023-08-31 22:47:07 +02:00
res . end ( ) ;
}
} ) ;
}
}
} ) ;
2023-07-29 20:32:17 +02:00
}
var reqip = socket . remoteAddress ;
var reqport = socket . remotePort ;
2023-08-09 21:09:23 +02:00
reqcounter ++ ;
2023-07-29 20:44:13 +02:00
serverconsole . locmessage ( "Somebody connected to " + ( secure && fromMain ? ( ( typeof sport == "number" ? "port " : "socket " ) + sport ) : ( ( typeof port == "number" ? "port " : "socket " ) + port ) ) + "..." ) ;
2023-07-29 20:32:17 +02:00
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 ;
}
}
2023-08-12 12:35:46 +02:00
2023-07-29 20:44:13 +02:00
if ( err . code && err . code . indexOf ( "ERR_HTTP2_" ) == 0 ) {
serverconsole . errmessage ( "An HTTP/2 error occured: " + err . code ) ;
callServerError ( 400 ) ;
return ;
}
2023-07-29 20:32:17 +02:00
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 ] ;
2023-09-03 11:08:16 +02:00
if ( header == "" ) return false ; // Beginning of body
2023-07-29 20:32:17 +02:00
else if ( header . indexOf ( ":" ) < 1 ) {
serverconsole . errmessage ( "Invalid header." ) ;
callServerError ( 400 ) ;
return true ;
} else if ( header . length > 8192 ) {
serverconsole . errmessage ( "Header too large." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 431 ) ; // Headers too large
2023-07-29 20:32:17 +02:00
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 ) ) {
2023-07-29 20:44:13 +02:00
serverconsole . errmessage ( "The request is invalid (it may be a part of larger invalid request)." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 400 ) ; // Also malformed Packet
2023-07-29 20:32:17 +02:00
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." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 400 ) ; // Malformed Packet
2023-07-29 20:32:17 +02:00
} else if ( ! httpVersion . toString ( ) . match ( /^HTTP[\/]/i ) ) {
serverconsole . errmessage ( "Invalid protocol." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 400 ) ; // bad protocol version
2023-07-29 20:32:17 +02:00
} else if ( http . METHODS . indexOf ( method ) == - 1 ) {
serverconsole . errmessage ( "Invalid method." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 405 ) ; // Also malformed Packet
2023-07-29 20:32:17 +02:00
} else {
if ( checkHeaders ( false ) ) return ;
if ( packetLine1 [ 0 ] . length > 255 ) {
serverconsole . errmessage ( "URI too long." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 414 ) ; // Also malformed Packet
2023-07-29 20:32:17 +02:00
} else {
2023-07-29 20:44:13 +02:00
serverconsole . errmessage ( "The request is invalid." ) ;
2023-09-03 11:08:16 +02:00
callServerError ( 400 ) ; // Also malformed Packet
2023-07-29 20:32:17 +02:00
}
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . climessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . reqmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . resmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . errmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locerrmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locwarnmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ;
2023-08-09 21:09:23 +02:00
reqcounter ++ ;
2023-07-29 20:44:13 +02:00
serverconsole . locmessage ( "Somebody connected to " + ( secure ? ( ( typeof sport == "number" ? "port " : "socket " ) + sport ) : ( ( typeof port == "number" ? "port " : "socket " ) + port ) ) + "..." ) ;
2023-07-29 20:32:17 +02:00
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 = [ ] ;
2023-08-19 22:38:58 +02:00
mods . forEach ( function ( mod ) {
if ( mod . proxyCallback !== undefined ) proxyMods . push ( mod ) ;
} ) ;
2023-07-29 20:32:17 +02:00
var modFunction = ffinals ;
2023-09-12 23:19:14 +02:00
proxyMods . reverse ( ) . forEach ( function ( proxyMod ) {
2023-08-19 22:38:58 +02:00
modFunction = proxyMod . proxyCallback ( req , socket , head , configJSON , serverconsole , modFunction ) ;
} ) ;
2023-08-29 15:44:01 +02:00
modFunction ( ) ;
2023-07-29 20:32:17 +02:00
}
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 ) ) ;
}
2023-08-31 23:03:02 +02:00
function reqhandler ( req , res , fromMain ) {
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . climessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . reqmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . resmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . errmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locerrmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locwarnmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-19 22:38:58 +02:00
msg . split ( "\n" ) . forEach ( function ( nmsg ) {
serverconsole . locmessage ( nmsg ) ;
} ) ;
2023-07-29 20:32:17 +02:00
return ;
}
console . log ( "SERVER MESSAGE [Request Id: " + reqId + "]: " + msg ) ;
LOG ( "SERVER MESSAGE [Request Id: " + reqId + "]: " + msg ) ;
return ;
}
} ;
2023-08-31 22:47:07 +02:00
function matchHostname ( hostname ) {
if ( typeof hostname == "undefined" || hostname == "*" ) {
return true ;
2023-08-31 23:03:02 +02:00
} else if ( req . headers . host && hostname . indexOf ( "*." ) == 0 && hostname != "*." ) {
2023-08-31 22:47:07 +02:00
var hostnamesRoot = hostname . substr ( 2 ) ;
2023-08-31 23:03:02 +02:00
if ( req . headers . host == hostnamesRoot || req . headers . host . indexOf ( "." + hostnamesRoot ) == req . headers . host . length - hostnamesRoot . length - 1 ) {
2023-08-31 22:47:07 +02:00
return true ;
}
2023-08-31 23:03:02 +02:00
} else if ( req . headers . host && req . headers . host == hostname ) {
2023-08-31 22:47:07 +02:00
return true ;
}
return false ;
}
2023-09-03 10:27:30 +02:00
2023-07-29 20:32:17 +02:00
function getCustomHeaders ( ) {
var ph = JSON . parse ( JSON . stringify ( customHeaders ) ) ;
2023-12-03 13:58:35 +01:00
if ( configJSON . customHeadersVHost ) {
2023-08-31 22:47:07 +02:00
var vhostP = null ;
2023-12-03 13:58:35 +01:00
configJSON . customHeadersVHost . every ( function ( vhost ) {
if ( matchHostname ( vhost . host ) ) {
2023-08-31 22:47:07 +02:00
vhostP = vhost ;
return false ;
} else {
return true ;
}
} ) ;
2023-12-03 13:58:35 +01:00
if ( vhostP && vhostP . headers ) {
2023-08-31 22:47:07 +02:00
var phNu = JSON . parse ( JSON . stringify ( vhostP . headers ) ) ;
Object . keys ( phNu ) . forEach ( function ( phNuK ) {
ph [ phNuK ] = phNu [ phNuK ] ;
} ) ;
}
}
2023-08-19 22:38:58 +02:00
Object . keys ( ph ) . forEach ( function ( phk ) {
2023-08-31 23:03:02 +02:00
if ( typeof ph [ phk ] == "string" ) ph [ phk ] = ph [ phk ] . replace ( /\{path\}/g , req . url ) ;
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:32:17 +02:00
return ph ;
}
2023-09-03 11:08:16 +02:00
// Make HTTP/1.x API-based scripts compatible with HTTP/2.0 API
2023-08-31 23:03:02 +02:00
if ( configJSON . enableHTTP2 == true && req . httpVersion == "2.0" ) {
2023-07-29 20:32:17 +02:00
try {
2023-09-03 11:08:16 +02:00
// Set HTTP/1.x methods (to prevent process warnings)
2023-08-31 23:03:02 +02:00
res . writeHeadNodeApi = res . writeHead ;
res . setHeaderNodeApi = res . setHeader ;
res . writeHead = function ( a , b , c ) {
2023-07-29 20:32:17 +02:00
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" ] ;
2023-12-03 13:58:35 +01:00
if ( res . stream && res . stream . destroyed ) {
2023-11-12 18:41:06 +01:00
return false ;
} else {
return res . writeHeadNodeApi ( a , table ) ;
}
2023-07-29 20:32:17 +02:00
} ;
2023-08-31 23:03:02 +02:00
res . setHeader = function ( a , b ) {
if ( a != "transfer-encoding" && a != "connection" && a != "keep-alive" && a != "upgrade" ) return res . setHeaderNodeApi ( a , b ) ;
2023-07-29 20:32:17 +02:00
return false ;
} ;
2023-09-03 11:08:16 +02:00
// Set HTTP/1.x headers
2023-08-31 23:03:02 +02:00
if ( ! req . headers . host ) req . headers . host = req . headers [ ":authority" ] ;
( req . headers [ ":path" ] == undefined ? ( function ( ) { } ) ( ) : req . url = req . headers [ ":path" ] ) ;
req . protocol = req . headers [ ":scheme" ] ;
2023-08-19 22:38:58 +02:00
var headers = [ ":path" , ":method" ] ;
2023-07-29 20:32:17 +02:00
for ( var i = 0 ; i < headers . length ; i ++ ) {
2023-08-31 23:03:02 +02:00
if ( req . headers [ headers [ i ] ] == undefined ) {
2023-07-29 20:32:17 +02:00
var cheaders = getCustomHeaders ( ) ;
cheaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
2023-08-31 23:03:02 +02:00
res . writeHead ( 400 , "Bad Request" , cheaders ) ;
res . write ( "<html><head><title>400 Bad Request</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>400 Bad Request</h1><p>The request you sent is invalid. <p><i>" + ( 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 [ ":authority" ] == undefined ? "" : " on " + req . headers [ ":authority" ] ) + "</i></p></body></html>" ) ;
res . end ( ) ;
2023-07-29 20:32:17 +02:00
return ;
}
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
var cheaders = getCustomHeaders ( ) ;
cheaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
cheaders [ ":status" ] = "500" ;
2023-08-31 23:03:02 +02:00
res . stream . respond ( cheaders ) ;
res . stream . write ( "<html><head><title>500 Internal Server Error</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>500 Internal Server Error</h1><p>The server had an unexpected error. Below, error stack is shown: </p><code>" + ( stackHidden ? "[error stack hidden]" : generateErrorStack ( err ) ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . replace ( / {2}/g , " " ) + "</code><p>Please contact with developer/administrator of the website.</p><p><i>" + ( 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 [ ":authority" ] == undefined ? "" : " on " + req . headers [ ":authority" ] ) + "</i></p></body></html>" ) ;
res . stream . end ( ) ;
2023-07-29 20:32:17 +02:00
return ;
}
}
2023-08-31 23:03:02 +02:00
if ( req . headers [ "x-svr-js-from-main-thread" ] == "true" && ( ! req . socket . remoteAddress || req . socket . remoteAddress == "::1" || req . socket . remoteAddress == "::ffff:127.0.0.1" || req . socket . remoteAddress == "127.0.0.1" || req . socket . remoteAddress == "localhost" || req . socket . remoteAddress == host || req . socket . remoteAddress == "::ffff:" + host ) ) {
2023-08-09 21:09:23 +02:00
var headers = getCustomHeaders ( ) ;
2023-08-31 23:03:02 +02:00
res . writeHead ( 204 , "No Content" , headers ) ;
res . end ( ) ;
2023-07-29 20:32:17 +02:00
return ;
}
2023-08-29 14:56:39 +02:00
2023-08-31 23:03:02 +02:00
req . url = fixNodeMojibakeURL ( req . url ) ;
2023-07-29 20:32:17 +02:00
var headWritten = false ;
2023-07-29 20:44:13 +02:00
var lastStatusCode = null ;
2023-08-31 23:03:02 +02:00
res . writeHeadNative = res . writeHead ;
res . writeHead = function ( a , b , c ) {
2023-07-29 20:32:17 +02:00
if ( ! ( headWritten && process . isBun && a === lastStatusCode && b === undefined && c === undefined ) ) {
if ( headWritten ) {
process . emitWarning ( "res.writeHead called multiple times." , {
code : "WARN_SVRJS_MULTIPLE_WRITEHEAD"
} ) ;
2023-08-31 23:03:02 +02:00
return res ;
2023-07-29 20:32:17 +02:00
} 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." ) ;
}
2023-12-03 13:58:35 +01:00
if ( typeof b != "string" && http . STATUS _CODES [ a ] ) {
if ( ! c ) c = b ;
2023-07-29 20:44:13 +02:00
b = http . STATUS _CODES [ a ] ;
}
2023-07-29 20:32:17 +02:00
lastStatusCode = a ;
}
2023-08-31 23:03:02 +02:00
res . writeHeadNative ( a , b , c ) ;
2023-07-29 20:32:17 +02:00
} ;
2023-09-03 10:27:30 +02:00
2023-09-03 10:18:52 +02:00
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." ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} ) ;
var isProxy = false ;
if ( req . url . indexOf ( "/" ) != 0 && req . url != "*" ) isProxy = true ;
serverconsole . locmessage ( "Somebody connected to " + ( secure && fromMain ? ( ( typeof sport == "number" ? "port " : "socket " ) + sport ) : ( ( typeof port == "number" ? "port " : "socket " ) + port ) ) + "..." ) ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
if ( req . socket == null ) {
serverconsole . errmessage ( "Client socket is null!!!" ) ;
return ;
}
2023-09-03 11:08:16 +02:00
// Set up X-Forwarded-For
2023-09-03 14:40:41 +02:00
var reqip = req . socket . remoteAddress ;
var reqport = req . socket . remotePort ;
2023-09-03 10:18:52 +02:00
var oldip = "" ;
2023-09-03 14:40:41 +02:00
var oldport = "" ;
var isForwardedValid = true ;
2023-12-03 13:58:35 +01:00
if ( enableIPSpoofing ) {
2023-09-03 14:40:41 +02:00
if ( req . headers [ "x-forwarded-for" ] != undefined ) {
var preparedReqIP = req . headers [ "x-forwarded-for" ] . split ( "," ) [ 0 ] . replace ( / /g , "" ) ;
var preparedReqIPvalid = net . isIP ( preparedReqIP ) ;
2023-12-03 13:58:35 +01:00
if ( preparedReqIPvalid ) {
2023-09-03 14:40:41 +02:00
if ( preparedReqIPvalid == 4 && req . socket . remoteAddress && req . socket . remoteAddress . indexOf ( ":" ) > - 1 ) preparedReqIP = "::ffff:" + preparedReqIP ;
2023-09-03 22:31:07 +02:00
reqip = preparedReqIP ;
2023-09-03 14:40:41 +02:00
reqport = null ;
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 ( err ) {
// Address setting failed
}
} else {
isForwardedValid = false ;
}
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
reqcounter ++ ;
2023-08-12 12:35:46 +02:00
2023-09-03 10:18:52 +02:00
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" ] ) ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
var acceptEncoding = req . headers [ "accept-encoding" ] ;
if ( ! acceptEncoding ) acceptEncoding = "" ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
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
2023-07-29 20:32:17 +02:00
2023-09-11 23:21:14 +02:00
function responseEnd ( body ) {
//If body is Buffer, then it is converted to String anyway.
res . write ( head + body + foot ) ;
2023-09-03 10:18:52 +02:00
res . end ( ) ;
}
2023-09-11 21:56:08 +02:00
2023-09-03 10:18:52 +02:00
// 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." ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// 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." ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
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." ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Determine error file
function getErrorFileName ( list , callback , _i ) {
function medCallback ( p ) {
2023-12-03 13:58:35 +01:00
if ( p ) callback ( p ) ;
2023-09-03 10:18:52 +02:00
else {
2023-12-03 13:58:35 +01:00
if ( errorCode == 404 ) {
fs . access ( page404 , fs . constants . F _OK , function ( err ) {
if ( err ) {
fs . access ( "." + errorCode . toString ( ) , fs . constants . F _OK , function ( err ) {
2023-09-01 11:04:04 +02:00
try {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-03 10:18:52 +02:00
callback ( errorCode . toString ( ) + ".html" ) ;
} else {
2023-09-11 21:56:08 +02:00
callback ( "." + errorCode . toString ( ) ) ;
2023-09-03 10:18:52 +02:00
}
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-08-31 22:47:07 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
}
2023-09-03 10:18:52 +02:00
} ) ;
} else {
2023-08-31 22:47:07 +02:00
try {
2023-09-03 10:18:52 +02:00
callback ( page404 ) ;
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-08-31 22:47:07 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
}
2023-09-03 10:18:52 +02:00
}
} ) ;
} else {
2023-12-03 13:58:35 +01:00
fs . access ( "." + errorCode . toString ( ) , fs . constants . F _OK , function ( err ) {
2023-09-03 10:18:52 +02:00
try {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-03 10:18:52 +02:00
callback ( errorCode . toString ( ) + ".html" ) ;
} else {
2023-09-11 21:56:08 +02:00
callback ( "." + errorCode . toString ( ) ) ;
2023-09-03 10:18:52 +02:00
}
2023-12-03 13:58:35 +01:00
} catch ( err2 ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err2 ) ) ;
}
} ) ;
2023-08-31 22:47:07 +02:00
}
}
2023-09-03 10:18:52 +02:00
}
2023-09-03 10:27:30 +02:00
2023-12-03 13:58:35 +01:00
if ( ! _i ) _i = 0 ;
if ( _i >= list . length ) {
2023-09-03 10:18:52 +02:00
medCallback ( false ) ;
return ;
}
2023-09-03 10:27:30 +02:00
2023-12-03 13:58:35 +01:00
if ( list [ _i ] . scode != errorCode || ! matchHostname ( list [ _i ] . host ) ) {
getErrorFileName ( list , callback , _i + 1 ) ;
2023-09-03 10:18:52 +02:00
return ;
} else {
2023-12-03 13:58:35 +01:00
fs . access ( list [ _i ] . path , fs . constants . F _OK , function ( err ) {
if ( err ) {
getErrorFileName ( list , callback , _i + 1 ) ;
2023-09-03 10:18:52 +02:00
} else {
2023-09-11 21:56:08 +02:00
medCallback ( list [ _i ] . path ) ;
2023-09-03 10:18:52 +02:00
}
} ) ;
2023-08-31 22:47:07 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-12-03 13:58:35 +01:00
getErrorFileName ( errorPages , function ( errorFile ) {
2023-09-03 10:18:52 +02:00
// 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" ) ) ;
2023-08-31 22:47:07 +02:00
2023-09-03 10:18:52 +02:00
if ( errorCode == 500 || errorCode == 502 ) {
serverconsole . errmessage ( "There was an error while processing the request!" ) ;
serverconsole . errmessage ( "Stack:" ) ;
serverconsole . errmessage ( stack ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Hide the error stack if specified
if ( stackHidden ) stack = "[error stack hidden]" ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Validate the error code and handle unknown codes
if ( serverErrorDescs [ errorCode ] === undefined ) {
callServerError ( 501 , extName , stack ) ;
} else {
var cheaders = getCustomHeaders ( ) ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Process custom headers if provided
if ( ch ) {
var chon = Object . keys ( cheaders ) ;
Object . keys ( ch ) . forEach ( function ( chnS ) {
var nhn = chnS ;
for ( var j = 0 ; j < chon . length ; j ++ ) {
if ( chon [ j ] . toLowerCase ( ) == chnS . toLowerCase ( ) ) {
nhn = chon [ j ] ;
break ;
2023-08-31 22:47:07 +02:00
}
}
2023-09-03 10:18:52 +02:00
if ( ch [ chnS ] ) cheaders [ nhn ] = ch [ chnS ] ;
2023-08-31 22:47:07 +02:00
} ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
cheaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Set default Allow header for 405 error if not provided
if ( errorCode == 405 && ! cheaders [ "Allow" ] ) cheaders [ "Allow" ] = "GET, POST, HEAD, OPTIONS" ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Read the error file and replace placeholders with error information
fs . readFile ( errorFile , function ( err , data ) {
try {
if ( err ) throw err ;
res . writeHead ( errorCode , http . STATUS _CODES [ errorCode ] , cheaders ) ;
2023-09-11 23:01:46 +02:00
responseEnd ( 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 ( />/g , ">" ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . replace ( / {2}/g , " " ) ) . replace ( /{path}/g , req . url . replace ( /&/g , "&" ) . 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" ) + ( ( ! exposeModsInErrorPages || extName == undefined ) ? "" : " " + extName ) + ( ( req . headers . host == undefined || isProxy ) ? "" : " on " + String ( req . headers . host ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) ) ) . replace ( /{contact}/g , serverAdmin . replace ( /\./g , "[dot]" ) . replace ( /@/g , "[at]" ) ) ) ; // Replace placeholders in error response
2023-09-03 10:18:52 +02:00
} catch ( err ) {
var additionalError = 500 ;
// Handle additional error cases
if ( err . code == "ENOENT" ) {
additionalError = 404 ;
} else if ( err . code == "ENOTDIR" ) {
additionalError = 404 ; // Assume that file doesn't exist
} else if ( err . code == "EACCES" ) {
additionalError = 403 ;
} else if ( err . code == "ENAMETOOLONG" ) {
additionalError = 414 ;
} else if ( err . code == "EMFILE" ) {
additionalError = 503 ;
} else if ( err . code == "ELOOP" ) {
additionalError = 508 ;
}
res . writeHead ( errorCode , http . STATUS _CODES [ errorCode ] , cheaders ) ;
2023-09-05 00:05:20 +02:00
res . write ( ( "<html><head><title>{errorMessage}</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>{errorMessage}</h1><p>{errorDesc}</p>" + ( ( additionalError == 404 ) ? "" : "<p>Additionally, a {additionalError} error occurred while loading an error page.</p>" ) + "<p><i>{server}</i></p></body></html>" ) . replace ( /{errorMessage}/g , errorCode . toString ( ) + " " + http . STATUS _CODES [ errorCode ] ) . replace ( /{errorDesc}/g , serverErrorDescs [ errorCode ] ) . replace ( /{stack}/g , stack . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) . replace ( /\r\n/g , "<br/>" ) . replace ( /\n/g , "<br/>" ) . replace ( /\r/g , "<br/>" ) . replace ( / {2}/g , " " ) ) . replace ( /{path}/g , req . url . replace ( /&/g , "&" ) . 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" ) + ( ( ! exposeModsInErrorPages || extName == undefined ) ? "" : " " + extName ) + ( ( req . headers . host == undefined || isProxy ) ? "" : " on " + String ( req . headers . host ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) ) ) . replace ( /{contact}/g , serverAdmin . replace ( /\./g , "[dot]" ) . replace ( /@/g , "[at]" ) ) . replace ( /{additionalError}/g , additionalError . toString ( ) ) ) ; // Replace placeholders in error response
2023-09-03 10:18:52 +02:00
res . end ( ) ;
}
} ) ;
}
} ) ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Function to perform HTTP redirection to a specified destination URL
function redirect ( destination , isTemporary , customHeaders ) {
// If customHeaders are not provided, get the default custom headers
if ( customHeaders === undefined ) customHeaders = getCustomHeaders ( ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Set the "Location" header to the destination URL
customHeaders [ "Location" ] = destination ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Determine the status code for redirection based on the isTemporary flag
var statusCode = isTemporary ? 302 : 301 ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Write the response header with the appropriate status code and message
res . writeHead ( statusCode , http . STATUS _CODES [ statusCode ] , customHeaders ) ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Log the redirection message
serverconsole . resmessage ( "Client redirected to " + destination ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// End the response
res . end ( ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Return from the function
return ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Function to parse incoming POST data from the request
function parsePostData ( options , callback ) {
// If the request method is not POST, return a 405 Method Not Allowed error
if ( req . method != "POST" ) {
// Get the default custom headers and add "Allow" header with value "POST"
var customHeaders = getCustomHeaders ( ) ;
customHeaders [ "Allow" ] = "POST" ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Call the server error function with 405 status code and custom headers
callServerError ( 405 , undefined , undefined , customHeaders ) ;
return ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Set formidableOptions to options, if provided; otherwise, set it to an empty object
var formidableOptions = options ? options : { } ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// If no callback is provided, set the callback to options and reset formidableOptions
if ( ! callback ) {
callback = options ;
formidableOptions = { } ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
// If the formidable module had an error, call the server error function with 500 status code and error stack
if ( formidable . _errored ) callServerError ( 500 , undefined , generateErrorStack ( formidable . _errored ) ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Create a new formidable form
var form = formidable ( formidableOptions ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Parse the request and process the fields and files
form . parse ( req , function ( err , fields , files ) {
// If there was an error, call the server error function with status code determined by error
if ( err ) {
2023-12-03 13:58:35 +01:00
if ( err . httpCode ) callServerError ( err . httpCode ) ;
2023-09-03 10:18:52 +02:00
else callServerError ( 400 ) ;
return ;
}
// Otherwise, call the provided callback function with the parsed fields and files
callback ( fields , files ) ;
} ) ;
}
// Function to parse a URL string into a URL object
function parseURL ( uri ) {
// Check if the URL API is available (Node.js version >= 10)
if ( typeof URL !== "undefined" && url . Url ) {
try {
// Create a new URL object using the provided URI and base URL
var uobject = new URL ( uri , "http" + ( req . socket . encrypted ? "s" : "" ) + "://" + ( req . headers . host ? req . headers . host : ( domain ? domain : "unknown.invalid" ) ) ) ;
// Create a new URL object (similar to deprecated url.Url)
var nuobject = new url . Url ( ) ;
// Set properties of the new URL object from the provided 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 ;
// Adjust the pathname and href properties if the URI doesn't start with "/"
if ( uri . indexOf ( "/" ) != 0 ) {
2023-07-29 20:32:17 +02:00
if ( nuobject . pathname ) {
2023-09-03 10:18:52 +02:00
nuobject . pathname = nuobject . pathname . substr ( 1 ) ;
nuobject . href = nuobject . pathname + ( nuobject . search ? nuobject . search : "" ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Set the path property as a combination of pathname and search
if ( nuobject . pathname ) {
nuobject . path = nuobject . pathname + ( nuobject . search ? nuobject . search : "" ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
// Initialize the query object and copy URL search parameters to it
nuobject . query = { } ;
uobject . searchParams . forEach ( function ( value , key ) {
nuobject . query [ key ] = value ;
} ) ;
// Return the created URL object
return nuobject ;
} catch ( err ) {
// If there was an error using the URL API, fall back to deprecated url.parse
2023-07-29 20:32:17 +02:00
return url . parse ( uri , true ) ;
}
2023-09-03 10:18:52 +02:00
} else {
// If the URL API is not available, fall back to deprecated url.parse
return url . parse ( uri , true ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
var uobject = parseURL ( 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 ( err ) {
2023-09-03 11:08:16 +02:00
// Return 400 error
2023-09-03 10:18:52 +02:00
callServerError ( 400 ) ;
serverconsole . errmessage ( "Bad request!" ) ;
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
if ( req . headers [ "expect" ] && req . headers [ "expect" ] != "100-continue" ) {
callServerError ( 417 ) ;
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 11:08:16 +02:00
// MOD EXCECUTION FUNCTION
2023-09-03 10:18:52 +02:00
function modExecute ( mods , ffinals ) {
2023-09-03 11:08:16 +02:00
// Prepare modFunction
2023-09-03 10:18:52 +02:00
var modFunction = ffinals ;
2023-09-12 23:19:14 +02:00
var useMods = mods . slice ( ) ;
2023-09-11 21:56:08 +02:00
2023-12-03 13:58:35 +01:00
if ( isProxy ) {
2023-09-07 18:00:58 +02:00
// Get list of forward proxy mods
useMods = [ ] ;
mods . forEach ( function ( mod ) {
if ( mod . proxyCallback !== undefined ) useMods . push ( mod ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-11 21:56:08 +02:00
2023-09-12 23:19:14 +02:00
useMods . reverse ( ) . forEach ( function ( modO ) {
2023-09-11 23:01:46 +02:00
modFunction = modO . callback ( req , res , serverconsole , responseEnd , href , ext , uobject , search , "index.html" , users , page404 , head , foot , "" , modFunction , configJSON , callServerError , getCustomHeaders , origHref , redirect , parsePostData ) ;
2023-09-07 18:00:58 +02:00
} ) ;
2023-09-03 11:08:16 +02:00
// Execute modfunction
2023-09-03 10:18:52 +02:00
modFunction ( ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
var vresCalled = false ;
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
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 ;
}
if ( req . socket == null ) {
serverconsole . errmessage ( "Client socket is null!!!" ) ;
return ;
}
2023-09-11 21:56:08 +02:00
2023-09-03 10:18:52 +02:00
// Function to check the level of a path relative to the web root
function checkPathLevel ( path ) {
// Split the path into an array of components based on "/"
var pathComponents = path . split ( "/" ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Initialize counters for level up (..) and level down (.)
var levelUpCount = 0 ;
var levelDownCount = 0 ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Loop through the path components
2023-12-03 14:04:38 +01:00
for ( var i = 0 ; i < pathComponents . length ; i ++ ) {
2023-09-03 10:18:52 +02:00
// If the component is "..", decrement the levelUpCount
if ( ".." === pathComponents [ i ] ) {
2023-12-03 14:04:38 +01:00
levelUpCount -- ;
2023-07-29 20:44:13 +02:00
}
2023-09-03 10:18:52 +02:00
// If the component is not "." or an empty string, increment the levelDownCount
else if ( "." !== pathComponents [ i ] && "" !== pathComponents [ i ] ) {
2023-12-03 14:04:38 +01:00
levelDownCount ++ ;
2023-09-03 10:18:52 +02:00
}
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Calculate the overall level by subtracting levelUpCount from levelDownCount
var overallLevel = levelDownCount - levelUpCount ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Return the overall level
return overallLevel ;
}
2023-07-29 20:32:17 +02:00
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
if ( isProxy ) {
var eheaders = getCustomHeaders ( ) ;
eheaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
2023-12-03 14:04:38 +01:00
res . writeHead ( 501 , "Not Implemented" , eheaders ) ;
2023-09-03 10:18:52 +02:00
res . write ( "<html><head><title>Proxy not implemented</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><h1>Proxy not implemented</h1><p>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.</p><p><i>" + ( exposeServerVersion ? "SVR.JS/" + version + " (" + getOS ( ) + "; " + ( process . isBun ? ( "Bun/v" + process . versions . bun + "; like Node.JS/" + process . version ) : ( "Node.JS/" + process . version ) ) + ")" : "SVR.JS" ) + "</i></p></body></html>" ) ;
res . end ( ) ;
serverconsole . errmessage ( "SVR.JS doesn't support proxy without proxy mod." ) ;
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
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 ;
}
2023-07-29 20:32:17 +02:00
2023-09-12 18:11:11 +02:00
if ( allowStatus && ( href == "/svrjsstatus.svr" || ( os . platform ( ) == "win32" && href . toLowerCase ( ) == "/svrjsstatus.svr" ) ) ) {
2023-09-03 10:18:52 +02:00
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 ) ;
2023-12-03 12:51:05 +01:00
res . end ( ( head == "" ? "<html><head><title>SVR.JS status" + ( req . headers . host == undefined ? "" : " for " + String ( req . headers . host ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) ) + "</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body>" : head . replace ( /<head>/i , "<head><title>SVR.JS status" + ( req . headers . host == undefined ? "" : " for " + String ( req . headers . host ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) ) + "</title>" ) ) + "<h1>SVR.JS status" + ( req . headers . host == undefined ? "" : " for " + String ( req . headers . host ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) ) + "</h1>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" ) + "<br/><hr/>Current time: " + new Date ( ) . toString ( ) + "<br/>Thread start time: " + new Date ( new Date ( ) - ( process . uptime ( ) * 1000 ) ) . toString ( ) + "<br/>Thread uptime: " + formatRelativeTime ( Math . floor ( process . uptime ( ) ) ) + "<br/>OS uptime: " + formatRelativeTime ( os . uptime ( ) ) + "<br/>Total request count: " + reqcounter + "<br/>Average request rate: " + ( Math . round ( ( reqcounter / process . uptime ( ) ) * 100 ) / 100 ) + " requests/s" + ( process . memoryUsage ? ( "<br/>Memory usage of thread: " + sizify ( process . memoryUsage ( ) . rss , true ) + "B" ) : "" ) + ( process . cpuUsage ? ( "<br/>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 ) + "%" ) : "" ) + "<br/>Thread PID: " + process . pid + "<br/>" + ( foot == "" ? "</body></html>" : foot ) ) ;
2023-09-03 10:18:52 +02:00
return ;
}
2023-08-29 14:56:39 +02:00
2023-09-03 10:18:52 +02:00
/////////////////////////////////////////////
////THERE IS NO MORE "THE BOOK OF ZSOIE"!////
//// But it's in easteregg.tar.gz mod... ////
/////////////////////////////////////////////
2023-08-29 14:56:39 +02:00
2023-09-03 10:18:52 +02:00
var pth = decodeURIComponent ( href ) . replace ( /\/+/g , "/" ) . substr ( 1 ) ;
var readFrom = "./" + pth ;
fs . stat ( readFrom , function ( err , stats ) {
if ( err ) {
if ( err . code == "ENOENT" ) {
if ( _ _dirname != process . cwd ( ) && pth . match ( /^\.dirimages\/(?:(?!\.png$).)+\.png$/ ) ) {
stats = {
isDirectory : function isDirectory ( ) {
return false ;
} ,
isFile : function isFile ( ) {
return true ;
}
} ;
readFrom = _ _dirname + "/" + pth ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
callServerError ( 404 ) ;
serverconsole . errmessage ( "Resource not found." ) ;
2023-07-29 20:44:13 +02:00
return ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} else if ( err . code == "ENOTDIR" ) {
callServerError ( 404 ) ; // Assume that file doesn't exist.
serverconsole . errmessage ( "Resource not found." ) ;
return ;
} else if ( err . code == "EACCES" ) {
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access denied." ) ;
return ;
} else if ( err . code == "ENAMETOOLONG" ) {
callServerError ( 414 ) ;
return ;
} else if ( err . code == "EMFILE" ) {
callServerError ( 503 ) ;
return ;
} else if ( err . code == "ELOOP" ) {
callServerError ( 508 ) ; // The symbolic link loop is detected during file system operations.
serverconsole . errmessage ( "Symbolic link loop detected." ) ;
return ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
return ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-09-03 11:08:16 +02:00
// Check if index file exists
2023-09-03 10:18:52 +02:00
if ( req . url == "/" || stats . isDirectory ( ) ) {
2023-09-12 19:34:34 +02:00
fs . stat ( ( readFrom + "/index.html" ) . replace ( /\/+/g , "/" ) , function ( e , s ) {
if ( e || ! s . isFile ( ) ) {
fs . stat ( ( readFrom + "/index.htm" ) . replace ( /\/+/g , "/" ) , function ( e , s ) {
2023-09-03 10:18:52 +02:00
if ( e || ! s . isFile ( ) ) {
2023-09-12 19:34:34 +02:00
fs . stat ( ( readFrom + "/index.xhtml" ) . replace ( /\/+/g , "/" ) , function ( e , s ) {
2023-12-03 13:58:35 +01:00
if ( e || ! s . isFile ( ) ) {
properDirectoryListingAndStaticFileServe ( ) ;
} else {
stats = s ;
pth = ( pth + "/index.xhtml" ) . replace ( /\/+/g , "/" ) ;
ext = "xhtml" ;
readFrom = "./" + pth ;
properDirectoryListingAndStaticFileServe ( ) ;
}
} ) ;
2023-09-03 10:18:52 +02:00
} else {
stats = s ;
2023-09-12 19:34:34 +02:00
pth = ( pth + "/index.htm" ) . replace ( /\/+/g , "/" ) ;
ext = "htm" ;
2023-09-03 10:18:52 +02:00
readFrom = "./" + pth ;
2023-09-12 19:50:39 +02:00
properDirectoryListingAndStaticFileServe ( ) ;
2023-09-03 10:18:52 +02:00
}
} ) ;
2023-09-12 19:34:34 +02:00
} else {
stats = s ;
pth = ( pth + "/index.html" ) . replace ( /\/+/g , "/" ) ;
ext = "html" ;
readFrom = "./" + pth ;
2023-09-12 19:50:39 +02:00
properDirectoryListingAndStaticFileServe ( ) ;
2023-09-03 10:18:52 +02:00
}
} ) ;
} else {
2023-09-12 19:50:39 +02:00
properDirectoryListingAndStaticFileServe ( ) ;
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-09-12 19:50:39 +02:00
function properDirectoryListingAndStaticFileServe ( ) {
2023-09-03 10:18:52 +02:00
if ( stats . isDirectory ( ) ) {
// Check if directory listing is enabled in the configuration
if ( checkForEnabledDirectoryListing ( req . headers . host ) ) {
var customHeaders = getCustomHeaders ( ) ;
customHeaders [ "Content-Type" ] = "text/html; charset=utf-8" ;
res . writeHead ( 200 , http . STATUS _CODES [ 200 ] , customHeaders ) ;
// Read custom header and footer content (if available)
2023-12-03 13:58:35 +01:00
var customDirListingHeader = 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 ( ) :
"" ;
var customDirListingFooter = 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 ( ) :
"" ;
2023-09-03 10:18:52 +02:00
// Check if custom header has HTML tag
var headerHasHTMLTag = customDirListingHeader . replace ( /<!--(?:(?:(?!--\>)[\s\S])*|)(?:-->|$)/g , "" ) . match ( /<html(?![a-zA-Z0-9])(?:"(?:\\(?:[\s\S]|$)|[^\\"])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^\\'])*(?:'|$)|[^'">])*(?:>|$)/i ) ;
// Generate HTML head and footer based on configuration and custom content
2023-12-03 13:58:35 +01:00
var htmlHead = ( ! configJSON . enableDirectoryListingWithDefaultHead || head == "" ?
( ! headerHasHTMLTag ?
"<!DOCTYPE html><html><head><title>Directory: " + decodeURIComponent ( origHref ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) + "</title><meta charset=\"UTF-8\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body>" :
customDirListingHeader . replace ( /<head>/i , "<head><title>Directory: " + decodeURIComponent ( origHref ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) + "</title>" ) ) :
head . replace ( /<head>/i , "<head><title>Directory: " + decodeURIComponent ( origHref ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) + "</title>" ) ) +
( ! headerHasHTMLTag ? customDirListingHeader : "" ) +
"<h1>Directory: " + decodeURIComponent ( origHref ) . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) + "</h1><table id=\"directoryListing\"> <tr> <th></th> <th>Filename</th> <th>Size</th> <th>Date</th> </tr>" + ( checkPathLevel ( decodeURIComponent ( origHref ) ) < 1 ? "" : "<tr><td style=\"width: 24px;\"><img src=\"/.dirimages/return.png\" width=\"24px\" height=\"24px\" alt=\"[RET]\" /></td><td style=\"word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;\"><a href=\"" + ( origHref ) . replace ( /\/+/g , "/" ) . replace ( /\/[^\/]*\/?$/ , "/" ) + "\">Return</a></td><td></td><td></td></tr>" ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
var htmlFoot = "</table><p><i>" + ( 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 , "<" ) . replace ( />/g , ">" ) ) + "</i></p>" + customDirListingFooter + ( ! configJSON . enableDirectoryListingWithDefaultHead || foot == "" ? "</body></html>" : foot ) ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
if ( fs . existsSync ( "." + decodeURIComponent ( href ) + "/.maindesc" . replace ( /\/+/g , "/" ) ) ) {
htmlFoot = "</table><hr/>" + fs . readFileSync ( "." + decodeURIComponent ( href ) + "/.maindesc" . replace ( /\/+/g , "/" ) ) + htmlFoot ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
fs . readdir ( "." + decodeURIComponent ( href ) , function ( err , list ) {
try {
if ( err ) throw err ;
list = list . sort ( ) ;
// Function to get stats for all files in the directory
function getStatsForAllFilesI ( fileList , callback , prefix , pushArray , index ) {
if ( fileList . length == 0 ) {
callback ( pushArray ) ;
return ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
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 ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
callback ( pushArray ) ;
2023-07-29 20:32:17 +02:00
}
} else {
2023-09-03 10:18:52 +02:00
pushArray . push ( {
name : fileList [ index ] ,
stats : stats ,
errored : true
} ) ;
if ( index < fileList . length - 1 ) {
getStatsForAllFilesI ( fileList , callback , prefix , pushArray , index + 1 ) ;
} else {
callback ( pushArray ) ;
}
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} ) ;
} 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 ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
} ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Wrapper function to get stats for all files
function getStatsForAllFiles ( fileList , prefix , callback ) {
if ( ! prefix ) prefix = "" ;
getStatsForAllFilesI ( fileList , callback , prefix , [ ] , 0 ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Get stats for all files in the directory and generate the listing
getStatsForAllFiles ( list , "." + decodeURIComponent ( href ) , function ( filelist ) {
// Function to check file extension
function checkEXT ( filename , ext ) {
2023-12-03 13:58:35 +01:00
return filename . match ( new RegExp ( "\\." + ext . replace ( /^\./ , "" ) . replace ( /([.+*?^$()\[\]{}|\\])/ , "\\$1" ) + "$" , "i" ) ) ;
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
var directoryListingRows = [ ] ;
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 ) {
directoryListingRows . push (
"<tr><td style=\"width: 24px;\"><img src=\"/.dirimages/bad.png\" alt=\"[BAD]\" width=\"24px\" height=\"24px\" /></td><td style=\"word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;\"><a href=\"" +
2023-12-03 13:58:35 +01:00
( href + "/" + encodeURI ( ename ) ) . replace ( /\/+/g , "/" ) +
"\"><nocode>" +
ename . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) +
"</nocode></a></td><td>-</td><td>" +
estats . mtime . toDateString ( ) +
"</td></tr>\r\n"
2023-09-03 10:18:52 +02:00
) ;
} else {
directoryListingRows . push (
"<tr><td style=\"width: 24px;\"><img src=\"/.dirimages/bad.png\" alt=\"[BAD]\" width=\"24px\" height=\"24px\" /></td><td style=\"word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;\"><a href=\"" +
2023-12-03 13:58:35 +01:00
( href + "/" + encodeURI ( ename ) ) . replace ( /\/+/g , "/" ) +
"\"><nocode>" +
ename . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) +
"</nocode></a></td><td>-</td><td>-</td></tr>\r\n"
2023-09-03 10:18:52 +02:00
) ;
}
} else {
var entry = "<tr><td style=\"width: 24px;\"><img src=\"[img]\" alt=\"[alt]\" width=\"24px\" height=\"24px\" /></td><td style=\"word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;\"><a href=\"" +
2023-12-03 13:58:35 +01:00
( origHref + "/" + encodeURIComponent ( ename ) ) . replace ( /\/+/g , "/" ) +
( estats . isDirectory ( ) ? "/" : "" ) +
"\">" +
ename . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) +
"</a></td><td>" +
( estats . isDirectory ( ) ? "-" : sizify ( estats . size . toString ( ) ) ) +
"</td><td>" +
estats . mtime . toDateString ( ) +
"</td></tr>\r\n" ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Determine the file type and set the appropriate image and alt text
if ( estats . isDirectory ( ) ) {
entry = entry . replace ( "[img]" , "/.dirimages/directory.png" ) . replace ( "[alt]" , "[DIR]" ) ;
} else if ( ! estats . isFile ( ) ) {
entry = "<tr><td style=\"width: 24px;\"><img src=\"[img]\" alt=\"[alt]\" width=\"24px\" height=\"24px\" /></td><td style=\"word-wrap: break-word; word-break: break-word; overflow-wrap: break-word;\"><a href=\"" +
2023-12-03 13:58:35 +01:00
( origHref + "/" + encodeURIComponent ( ename ) ) . replace ( /\/+/g , "/" ) +
"\">" +
ename . replace ( /&/g , "&" ) . replace ( /</g , "<" ) . replace ( />/g , ">" ) +
"</a></td><td>-</td><td>" +
estats . mtime . toDateString ( ) +
"</td></tr>\r\n" ;
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Determine the special file types (block device, character device, etc.)
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]" ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} 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]" ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
directoryListingRows . push ( entry ) ;
2023-07-29 20:32:17 +02:00
}
}
}
2023-08-12 12:35:46 +02:00
2023-09-03 10:18:52 +02:00
// Push the information about empty directory
if ( directoryListingRows . length == 0 ) {
directoryListingRows . push ( "<tr><td></td><td>No files found</td><td></td><td></td></tr>" ) ;
}
2023-07-29 20:44:13 +02:00
2023-09-03 10:18:52 +02:00
// Send the directory listing response
res . end ( htmlHead + directoryListingRows . join ( "" ) + htmlFoot ) ;
serverconsole . resmessage ( "Client successfully received content." ) ;
} ) ;
2023-08-12 12:35:46 +02:00
2023-09-03 10:18:52 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
if ( err . code == "ENOENT" ) {
callServerError ( 404 ) ;
serverconsole . errmessage ( "Resource not found." ) ;
2023-08-02 23:54:07 +02:00
} else if ( err . code == "ENOTDIR" ) {
callServerError ( 404 ) ; // Assume that file doesn't exist.
serverconsole . errmessage ( "Resource not found." ) ;
2023-07-29 20:32:17 +02:00
} else if ( err . code == "EACCES" ) {
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access denied." ) ;
2023-08-21 19:38:38 +02:00
} else if ( err . code == "ENAMETOOLONG" ) {
callServerError ( 414 ) ;
2023-07-29 20:32:17 +02:00
} else if ( err . code == "EMFILE" ) {
2023-08-13 00:43:21 +02:00
callServerError ( 503 ) ;
2023-07-29 20:32:17 +02:00
} else if ( err . code == "ELOOP" ) {
2023-07-29 20:44:13 +02:00
callServerError ( 508 ) ; // The symbolic link loop is detected during file system operations.
serverconsole . errmessage ( "Symbolic link loop detected." ) ;
2023-07-29 20:32:17 +02:00
} else {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
}
}
2023-09-03 10:18:52 +02:00
} ) ;
} else {
// Directory listing is disabled, call 403 Forbidden error
callServerError ( 403 ) ;
serverconsole . errmessage ( "Directory listing is disabled." ) ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
} else {
var acceptEncoding = req . headers [ "accept-encoding" ] ;
if ( ! acceptEncoding ) acceptEncoding = "" ;
// Check if the requested file exists and handle errors
fs . stat ( readFrom , function ( err , stats ) {
if ( err ) {
if ( err . code == "ENOENT" ) {
callServerError ( 404 ) ;
serverconsole . errmessage ( "Resource not found." ) ;
} else if ( err . code == "ENOTDIR" ) {
callServerError ( 404 ) ; // Assume that file doesn't exist.
serverconsole . errmessage ( "Resource not found." ) ;
} else if ( err . code == "EACCES" ) {
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access denied." ) ;
} else if ( err . code == "ENAMETOOLONG" ) {
callServerError ( 414 ) ;
} else if ( err . code == "EMFILE" ) {
callServerError ( 503 ) ;
} else if ( err . code == "ELOOP" ) {
callServerError ( 508 ) ; // The symbolic link loop is detected during file system operations.
serverconsole . errmessage ( "Symbolic link loop detected." ) ;
} else {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Check if the requested resource is a file
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 ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
var filelen = stats . size ;
2023-09-03 11:08:16 +02:00
// ETag code
2023-09-03 10:18:52 +02:00
var fileETag = undefined ;
if ( configJSON . enableETag == undefined || configJSON . enableETag ) {
fileETag = generateETag ( href , stats ) ;
// Check if the client's request matches the ETag value (If-None-Match)
var clientETag = req . headers [ "if-none-match" ] ;
if ( clientETag === fileETag ) {
var headers = getCustomHeaders ( ) ;
headers . ETag = clientETag ;
res . writeHead ( 304 , "Not Modified" , headers ) ;
res . end ( ) ;
return ;
2023-07-29 20:44:13 +02:00
}
2023-08-12 12:35:46 +02:00
2023-09-03 10:18:52 +02:00
// Check if the client's request doesn't match the ETag value (If-Match)
var ifMatchETag = req . headers [ "if-match" ] ;
if ( ifMatchETag && ifMatchETag !== "*" && ifMatchETag !== fileETag ) {
var headers = getCustomHeaders ( ) ;
headers . ETag = clientETag ;
2023-12-03 13:58:35 +01:00
callServerError ( 412 , undefined , undefined , headers ) ;
2023-09-03 10:18:52 +02:00
return ;
}
}
// 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 ;
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 10:18:52 +02:00
return canCompress ;
}
2023-07-29 20:32:17 +02:00
2023-12-03 13:09:56 +01:00
var isCompressable = true ;
try {
isCompressable = canCompress ( href , dontCompress ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-12-03 13:09:56 +01:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// 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" ] ) ) ) {
2023-09-03 11:08:16 +02:00
isCompressable = false ; // Netscape 4.x doesn't handle compressed data properly outside of HTML documents.
2023-09-03 10:18:52 +02:00
} 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" ] ) ) ) {
2023-09-03 11:08:16 +02:00
isCompressable = false ; // Netscape 4.06-4.08 doesn't handle compressed data properly.
2023-09-03 10:18:52 +02:00
} else if ( ext != "html" && ext != "htm" && ext != "xhtml" && ext != "xht" && ext != "shtml" && /^w3m\/[^ ]*$/ . test ( req . headers [ "user-agent" ] ) ) {
2023-09-03 11:08:16 +02:00
isCompressable = false ; // w3m doesn't handle compressed data properly outside of HTML documents.
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Handle partial content request
if ( ext != "html" && req . headers [ "range" ] ) {
try {
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 == "" ) {
2023-07-29 20:32:17 +02:00
callServerError ( 416 , undefined , undefined , rhd ) ;
2023-09-03 10:18:52 +02:00
return ;
} else if ( beginOrig == "" ) {
begin = end - parseInt ( endOrig ) + 1 ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
begin = parseInt ( beginOrig ) ;
if ( endOrig != "" ) end = parseInt ( endOrig ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
if ( begin > end || begin < 0 || begin > filelen - 1 ) {
callServerError ( 416 , undefined , undefined , rhd ) ;
return ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
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 ) ;
2023-12-03 13:58:35 +01:00
if ( fileETag ) rhd [ "ETag" ] = fileETag ;
2023-07-29 20:32:17 +02:00
if ( req . method != "HEAD" ) {
2023-09-03 10:18:52 +02:00
var readStream = fs . createReadStream ( readFrom , {
start : begin ,
end : end
} ) ;
2023-08-02 23:54:07 +02:00
readStream . on ( "error" , function ( err ) {
if ( err . code == "ENOENT" ) {
2023-07-29 20:32:17 +02:00
callServerError ( 404 ) ;
serverconsole . errmessage ( "Resource not found." ) ;
2023-08-02 23:54:07 +02:00
} else if ( err . code == "ENOTDIR" ) {
callServerError ( 404 ) ; // Assume that file doesn't exist.
serverconsole . errmessage ( "Resource not found." ) ;
} else if ( err . code == "EACCES" ) {
2023-07-29 20:32:17 +02:00
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access denied." ) ;
2023-08-21 19:38:38 +02:00
} else if ( err . code == "ENAMETOOLONG" ) {
callServerError ( 414 ) ;
2023-08-02 23:54:07 +02:00
} else if ( err . code == "EMFILE" ) {
2023-08-13 00:43:21 +02:00
callServerError ( 503 ) ;
2023-08-02 23:54:07 +02:00
} else if ( err . code == "ELOOP" ) {
2023-07-29 20:44:13 +02:00
callServerError ( 508 ) ; // The symbolic link loop is detected during file system operations.
serverconsole . errmessage ( "Symbolic link loop detected." ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-02 23:54:07 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
2023-07-29 20:32:17 +02:00
}
} ) . on ( "open" , function ( ) {
try {
2023-09-03 10:18:52 +02:00
res . writeHead ( 206 , http . STATUS _CODES [ 206 ] , rhd ) ;
readStream . pipe ( res ) ;
2023-07-29 20:32:17 +02:00
serverconsole . resmessage ( "Client successfully received content." ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
2023-07-29 20:32:17 +02:00
}
} ) ;
} else {
2023-09-03 10:18:52 +02:00
res . writeHead ( 206 , http . STATUS _CODES [ 206 ] , rhd ) ;
2023-07-29 20:32:17 +02:00
res . end ( ) ;
}
}
2023-09-03 10:18:52 +02:00
} catch ( err ) {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} else {
try {
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 ) ;
2023-12-03 13:58:35 +01:00
if ( fileETag ) hdhds [ "ETag" ] = fileETag ;
2023-09-03 10:18:52 +02:00
if ( req . method != "HEAD" ) {
var readStream = fs . createReadStream ( readFrom ) ;
readStream . on ( "error" , function ( err ) {
if ( err . code == "ENOENT" ) {
callServerError ( 404 ) ;
serverconsole . errmessage ( "Resource not found." ) ;
} else if ( err . code == "ENOTDIR" ) {
callServerError ( 404 ) ; // Assume that file doesn't exist.
serverconsole . errmessage ( "Resource not found." ) ;
} else if ( err . code == "EACCES" ) {
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access denied." ) ;
} else if ( err . code == "ENAMETOOLONG" ) {
callServerError ( 414 ) ;
} else if ( err . code == "EMFILE" ) {
callServerError ( 503 ) ;
} else if ( err . code == "ELOOP" ) {
callServerError ( 508 ) ; // The symbolic link loop is detected during file system operations.
serverconsole . errmessage ( "Symbolic link loop detected." ) ;
} else {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
}
} ) . 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 ( err ) {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
}
} ) ;
} else {
res . writeHead ( 200 , http . STATUS _CODES [ 200 ] , hdhds ) ;
res . end ( ) ;
serverconsole . resmessage ( "Client successfully received content." ) ;
}
} catch ( err ) {
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
}
}
} ) ;
}
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} ) ;
} ;
}
2023-09-03 10:27:30 +02:00
2023-09-03 10:18:52 +02:00
try {
2023-09-03 11:08:16 +02:00
// scan blacklist
2023-09-03 10:18:52 +02:00
if ( blacklist . check ( reqip ) && href != "/favicon.ico" ) {
2023-09-03 11:08:16 +02:00
// Return client blocked message
2023-09-03 10:18:52 +02:00
var bheaders = getCustomHeaders ( ) ;
bheaders [ "Content-Type" ] = "text/html; charset=utf8" ;
res . writeHead ( 403 , "Client blocked" , bheaders ) ;
res . write ( "<!DOCTYPE html><html><head><title>Access denied - SVR.JS</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><br/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /></head><body><div style=\"height: auto; width: 70%; border-style: solid; border-width: 5; border-color: red; text-align: center; margin: 0 auto;\"><h1>ACCESS DENIED</h1><p style=\"font-size:20px\">Request from " + reqip + " is denied. The client is now in the blacklist.</p><p style=\"font-style: italic; font-weight: normal;\">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 , "<" ) . replace ( />/g , ">" ) ) + "</p></div></body></html>" ) ;
serverconsole . errmessage ( "Client blocked" ) ;
return ;
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
if ( req . url == "*" ) {
2023-09-03 11:08:16 +02:00
// Handle "*" URL
2023-09-03 10:18:52 +02:00
if ( req . method == "OPTIONS" ) {
2023-09-03 11:08:16 +02:00
// Respond with list of methods
2023-09-03 10:18:52 +02:00
var hdss = getCustomHeaders ( ) ;
hdss [ "Allow" ] = "GET, POST, HEAD, OPTIONS" ;
res . writeHead ( 204 , "No Content" , hdss ) ;
res . end ( ) ;
return ;
} else {
2023-12-03 12:51:05 +01:00
// SVR.JS doesn't understand that request, so throw an 400 error
2023-09-03 10:18:52 +02:00
callServerError ( 400 ) ;
2023-07-29 20:32:17 +02:00
return ;
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
if ( req . method == "CONNECT" ) {
2023-09-03 11:08:16 +02:00
// CONNECT requests should be handled in "connect" event.
2023-09-03 10:18:52 +02:00
callServerError ( 501 ) ;
serverconsole . errmessage ( "CONNECT requests aren't supported. Your JS runtime probably doesn't support 'connect' handler for HTTP library." ) ;
return ;
}
2023-09-03 22:40:10 +02:00
// Check for invalid X-Forwarded-For header
2023-12-03 13:58:35 +01:00
if ( ! isForwardedValid ) {
2023-09-03 22:40:10 +02:00
serverconsole . errmessage ( "X-Forwarded-For header is invalid." ) ;
callServerError ( 400 ) ;
return ;
}
2023-09-03 11:08:16 +02:00
// Sanitize URL
2023-09-03 10:18:52 +02:00
var sanitizedHref = sanitizeURL ( href ) ;
2023-09-06 19:22:03 +02:00
var preparedReqUrl = uobject . pathname + ( uobject . search ? uobject . search : "" ) + ( uobject . hash ? uobject . hash : "" ) ;
2023-09-11 21:56:08 +02:00
2023-09-03 11:08:16 +02:00
// Check if URL is "dirty"
2023-09-03 10:18:52 +02:00
if ( href != sanitizedHref && ! 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 ) ;
2023-12-03 13:58:35 +01:00
if ( rewriteDirtyURLs ) {
2023-09-03 10:18:52 +02:00
req . url = sanitizedURL ;
uobject = parseURL ( req . url ) ;
search = uobject . search ;
href = uobject . pathname ;
ext = path . extname ( href ) . toLowerCase ( ) ;
ext = ext . substr ( 1 , ext . length ) ;
try {
decodedHref = decodeURIComponent ( href ) ;
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Return 400 error
2023-09-03 10:18:52 +02:00
callServerError ( 400 ) ;
serverconsole . errmessage ( "Bad request!" ) ;
2023-08-18 23:29:18 +02:00
return ;
}
2023-09-03 10:18:52 +02:00
} else {
redirect ( sanitizedURL , false ) ;
return ;
2023-07-29 20:32:17 +02:00
}
2023-12-03 13:58:35 +01:00
} else if ( req . url != preparedReqUrl && ! isProxy ) {
2023-09-06 19:22:03 +02:00
serverconsole . resmessage ( "URL sanitized: " + req . url + " => " + preparedReqUrl ) ;
2023-12-03 13:58:35 +01:00
if ( rewriteDirtyURLs ) {
2023-09-06 19:22:03 +02:00
req . url = preparedReqUrl ;
} else {
redirect ( preparedReqUrl , false ) ;
return ;
}
2023-09-03 10:18:52 +02:00
}
2023-09-11 21:56:08 +02:00
2023-09-03 11:08:16 +02:00
// Handle redirects to HTTPS
2023-12-03 13:58:35 +01:00
if ( secure && ! fromMain && ! disableNonEncryptedServer && ! disableToHTTPSRedirect ) {
2023-09-03 10:18:52 +02:00
var hostx = req . headers . host ;
if ( hostx === undefined ) {
2023-09-03 14:40:41 +02:00
serverconsole . errmessage ( "Host header is missing." ) ;
2023-09-03 10:18:52 +02:00
callServerError ( 400 ) ;
return ;
}
2023-09-02 19:56:45 +02:00
2023-09-03 10:18:52 +02:00
if ( isProxy ) {
callServerError ( 501 ) ;
serverconsole . errmessage ( "This server will never be a proxy." ) ;
return ;
2023-09-02 19:56:45 +02:00
}
2023-09-03 10:27:30 +02:00
2023-09-03 10:18:52 +02:00
var urlp = parseURL ( "http://" + hostx ) ;
try {
if ( urlp . path . indexOf ( "//" ) == 0 ) {
urlp = parseURL ( "http:" + url . path ) ;
}
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// URL parse error...
2023-09-02 19:56:45 +02:00
}
2023-09-03 11:08:16 +02:00
2023-09-03 10:18:52 +02:00
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 == ( listenAddress ? listenAddress : host ) || urlp . host == ( listenAddress ? listenAddress : 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 ( ) ;
}
2023-09-02 19:56:45 +02:00
} else {
2023-09-03 10:18:52 +02:00
urlp . protocol = "https:" ;
2023-09-02 19:56:45 +02:00
}
2023-09-03 10:18:52 +02:00
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 ( err ) {
2023-09-03 11:08:16 +02:00
// Leave URL as it is...
2023-09-02 19:56:45 +02:00
}
2023-09-03 11:08:16 +02:00
2023-09-03 10:18:52 +02:00
redirect ( lloc + requestURL ) ;
return ;
2023-09-02 19:56:45 +02:00
}
2023-09-03 10:27:30 +02:00
2023-09-03 11:08:16 +02:00
// Handle redirects to addresses with www.
2023-09-03 10:18:52 +02:00
if ( wwwredirect ) {
var hostname = req . headers . host . split [ ":" ] ;
var hostport = null ;
if ( hostname . length > 1 && ( hostname [ 0 ] != "[" || hostname [ hostname . length - 1 ] != "]" ) ) hostport = hostname . pop ( ) ;
hostname = hostname . join ( ":" ) ;
if ( hostname == domain && hostname . indexOf ( "www." ) != 0 ) {
redirect ( ( req . socket . encrypted ? "https" : "http" ) + "://www." + hostname + ( hostport ? ":" + hostport : "" ) + req . url . replace ( /\/+/g , "/" ) ) ;
2023-09-02 19:56:45 +02:00
}
}
2023-09-03 10:27:30 +02:00
2023-09-03 11:08:16 +02:00
// Handle URL rewriting
2023-09-03 10:18:52 +02:00
function rewriteURL ( address , map ) {
var rewrittenAddress = address ;
2023-12-03 13:58:35 +01:00
map . every ( function ( mapEntry ) {
2023-09-03 10:18:52 +02:00
if ( matchHostname ( mapEntry . host ) && createRegex ( mapEntry . definingRegex ) . test ( address ) ) {
mapEntry . replacements . forEach ( function ( replacement ) {
rewrittenAddress = rewrittenAddress . replace ( createRegex ( replacement . regex ) , replacement . replacement ) ;
} ) ;
if ( mapEntry . append ) rewrittenAddress += mapEntry . append ;
return false ;
} else {
return true ;
2023-09-02 19:35:01 +02:00
}
2023-09-03 10:18:52 +02:00
} ) ;
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 = parseURL ( req . url ) ;
search = uobject . search ;
href = uobject . pathname ;
ext = path . extname ( href ) . toLowerCase ( ) ;
ext = ext . substr ( 1 , ext . length ) ;
try {
decodedHref = decodeURIComponent ( href ) ;
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Return 400 error
2023-09-03 10:18:52 +02:00
callServerError ( 400 ) ;
serverconsole . errmessage ( "Bad request!" ) ;
return ;
}
var sHref = sanitizeURL ( href ) ;
2023-09-06 20:22:51 +02:00
var preparedReqUrl2 = uobject . pathname + ( uobject . search ? uobject . search : "" ) + ( uobject . hash ? uobject . hash : "" ) ;
2023-09-11 21:56:08 +02:00
2023-09-06 20:22:51 +02:00
if ( req . url != preparedReqUrl2 || sHref != href . replace ( /\/\.(?=\/|$)/g , "/" ) . replace ( /\/+/g , "/" ) ) {
2023-09-03 10:18:52 +02:00
callServerError ( 403 ) ;
serverconsole . errmessage ( "Content blocked." ) ;
return ;
} else if ( sHref != href ) {
var rewrittenAgainURL = uobject ;
rewrittenAgainURL . path = null ;
rewrittenAgainURL . href = null ;
rewrittenAgainURL . pathname = sHref ;
rewrittenAgainURL . hostname = null ;
rewrittenAgainURL . host = null ;
rewrittenAgainURL . port = null ;
rewrittenAgainURL . protocol = null ;
rewrittenAgainURL . slashes = null ;
rewrittenAgainURL = url . format ( rewrittenAgainURL ) ;
serverconsole . resmessage ( "URL sanitized: " + req . url + " => " + rewrittenAgainURL ) ;
req . url = rewrittenAgainURL ;
2023-07-29 20:44:13 +02:00
uobject = parseURL ( req . url ) ;
2023-07-29 20:32:17 +02:00
search = uobject . search ;
href = uobject . pathname ;
ext = path . extname ( href ) . toLowerCase ( ) ;
ext = ext . substr ( 1 , ext . length ) ;
try {
decodedHref = decodeURIComponent ( href ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Return 400 error
2023-07-29 20:32:17 +02:00
callServerError ( 400 ) ;
serverconsole . errmessage ( "Bad request!" ) ;
return ;
}
}
}
2023-09-03 10:18:52 +02:00
}
2023-08-12 12:35:46 +02:00
2023-09-03 11:08:16 +02:00
// Set response headers
2023-09-03 10:18:52 +02:00
if ( ! isProxy ) {
var hkh = getCustomHeaders ( ) ;
2023-12-03 13:58:35 +01:00
Object . keys ( hkh ) . forEach ( function ( hkS ) {
2023-09-03 10:18:52 +02:00
try {
res . setHeader ( hkS , hkh [ hkS ] ) ;
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Headers will not be set.
2023-09-03 10:18:52 +02:00
}
} ) ;
}
2023-08-12 12:35:46 +02:00
2023-09-03 11:08:16 +02:00
// Check if path is forbidden
2023-09-03 10:18:52 +02:00
if ( ( isForbiddenPath ( decodedHref , "config" ) || isForbiddenPath ( decodedHref , "certificates" ) ) && ! isProxy ) {
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access to configuration file/certificates is denied." ) ;
return ;
2023-09-10 10:50:18 +02:00
} else if ( isIndexOfForbiddenPath ( decodedHref , "temp" ) && ! isProxy ) {
2023-09-09 00:36:24 +02:00
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access to temporary folder is denied." ) ;
return ;
} else if ( isIndexOfForbiddenPath ( decodedHref , "log" ) && ! isProxy && ( configJSON . enableLogging || configJSON . enableLogging == undefined ) && ! configJSON . enableRemoteLogBrowsing ) {
2023-09-03 10:18:52 +02:00
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access to log files is denied." ) ;
return ;
2023-09-09 00:53:24 +02:00
} else if ( isForbiddenPath ( decodedHref , "svrjs" ) && ! isProxy && ! exposeServerVersion ) {
2023-09-03 10:18:52 +02:00
callServerError ( 403 ) ;
serverconsole . errmessage ( "Access to SVR.JS script is denied." ) ;
return ;
} else if ( ( isForbiddenPath ( decodedHref , "svrjs" ) || isForbiddenPath ( decodedHref , "serverSideScripts" ) || isIndexOfForbiddenPath ( 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 = [ ] ;
2023-09-03 11:08:16 +02:00
// Scan for non-standard codes
2023-09-03 10:18:52 +02:00
if ( ! isProxy && nonStandardCodes != undefined ) {
for ( var i = 0 ; i < nonStandardCodes . length ; i ++ ) {
2023-12-03 13:58:35 +01:00
if ( matchHostname ( nonStandardCodes [ i ] . host ) ) {
2023-09-03 10:18:52 +02:00
var isMatch = false ;
if ( nonStandardCodes [ i ] . regex ) {
2023-09-03 11:08:16 +02:00
// Regex match
2023-09-03 10:18:52 +02:00
var createdRegex = createRegex ( nonStandardCodes [ i ] . regex , true ) ;
isMatch = req . url . match ( createdRegex ) || href . match ( createdRegex ) ;
2023-09-17 23:32:42 +02:00
regexI [ i ] = createdRegex ;
2023-09-03 10:18:52 +02:00
} else {
2023-09-03 11:08:16 +02:00
// Non-regex match
2023-09-03 10:18:52 +02:00
isMatch = nonStandardCodes [ i ] . url == href || ( os . platform ( ) == "win32" && nonStandardCodes [ i ] . url . toLowerCase ( ) == href . toLowerCase ( ) ) ;
}
if ( isMatch ) {
if ( nonStandardCodes [ i ] . scode == 401 ) {
2023-09-03 11:08:16 +02:00
// HTTP authentication
2023-09-03 10:18:52 +02:00
if ( authIndex == - 1 ) {
authIndex = i ;
}
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
if ( nonscodeIndex == - 1 ) {
if ( ( nonStandardCodes [ i ] . scode == 403 || nonStandardCodes [ i ] . scode == 451 ) && nonStandardCodes [ i ] . users !== undefined ) {
2023-09-03 11:08:16 +02:00
if ( nonStandardCodes [ i ] . users . check ( reqip ) ) nonscodeIndex = i ;
2023-09-03 10:18:52 +02:00
} else {
nonscodeIndex = i ;
2023-07-29 20:32:17 +02:00
}
}
}
}
}
}
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
2023-09-03 10:18:52 +02:00
// Handle non-standard codes
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 ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
location = nonscode . location + "?" + req . url . split ( "?" ) [ 1 ] ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
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 ) ;
2023-12-03 12:05:14 +01:00
serverconsole . errmessage ( "Client fails receiving content." ) ;
2023-09-03 10:18:52 +02:00
return ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-08-12 12:35:46 +02:00
2023-12-03 11:55:19 +01:00
// Trailing slash redirection
function redirectTrailingSlashes ( callback ) {
2023-12-03 13:58:35 +01:00
if ( ! disableTrailingSlashRedirects && href [ href . length - 1 ] != "/" ) {
2023-12-03 11:55:19 +01:00
fs . stat ( "." + decodeURIComponent ( href ) , function ( err , stats ) {
2023-12-03 13:58:35 +01:00
if ( err || ! stats . isDirectory ( ) ) {
2023-12-03 11:55:19 +01:00
try {
callback ( ) ;
2023-12-03 14:00:52 +01:00
} catch ( err ) {
callServerError ( 500 , undefined , err ) ;
2023-12-03 11:55:19 +01:00
}
} else {
var destinationURL = uobject ;
destinationURL . path = null ;
destinationURL . href = null ;
destinationURL . pathname += "/" ;
destinationURL . hostname = null ;
destinationURL . host = null ;
destinationURL . port = null ;
destinationURL . protocol = null ;
destinationURL . slashes = null ;
destinationURL = url . format ( destinationURL ) ;
redirect ( destinationURL ) ;
}
} ) ;
} else {
callback ( ) ;
}
}
2023-12-03 13:58:35 +01:00
2023-09-03 10:18:52 +02:00
// Handle HTTP authentication
if ( authIndex > - 1 ) {
var authcode = nonStandardCodes [ authIndex ] ;
2023-09-03 11:08:16 +02:00
// Function to check if passwords match
2023-09-03 10:18:52 +02:00
function checkIfPasswordMatches ( list , password , callback , _i ) {
2023-12-03 13:58:35 +01:00
if ( ! _i ) _i = 0 ;
2023-09-03 10:18:52 +02:00
var cb = function ( hash ) {
var matches = ( hash == list [ _i ] . pass ) ;
2023-12-03 13:58:35 +01:00
if ( matches ) {
2023-09-03 10:18:52 +02:00
callback ( true ) ;
2023-12-03 13:58:35 +01:00
} else if ( _i >= list . length - 1 ) {
2023-09-03 10:18:52 +02:00
callback ( false ) ;
} else {
2023-12-03 13:58:35 +01:00
checkIfPasswordMatches ( list , password , callback , _i + 1 ) ;
2023-09-03 10:18:52 +02:00
}
} ;
var hashedPassword = sha256 ( password + list [ _i ] . salt ) ;
2023-12-03 13:58:35 +01:00
if ( list [ _i ] . scrypt ) {
if ( ! crypto . scrypt ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , new Error ( "SVR.JS doesn't support scrypt-hashed passwords on Node.JS versions without scrypt hash support." ) ) ;
return ;
} else {
var cacheEntry = scryptCache . find ( function ( entry ) {
return ( entry . password == hashedPassword && entry . salt == list [ _i ] . salt ) ;
} ) ;
2023-12-03 13:58:35 +01:00
if ( cacheEntry ) {
2023-09-03 10:18:52 +02:00
cb ( cacheEntry . hash ) ;
2023-08-31 22:47:07 +02:00
} else {
2023-09-03 10:18:52 +02:00
crypto . scrypt ( password , list [ _i ] . salt , 64 , function ( err , derivedKey ) {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , err ) ;
} else {
var key = derivedKey . toString ( "hex" ) ;
2023-12-03 13:58:35 +01:00
scryptCache . push ( {
hash : key ,
password : hashedPassword ,
salt : list [ _i ] . salt ,
addDate : new Date ( )
} ) ;
2023-09-03 10:18:52 +02:00
cb ( key ) ;
}
2023-08-31 22:47:07 +02:00
} ) ;
}
2023-09-03 10:18:52 +02:00
}
2023-12-03 13:58:35 +01:00
} else if ( list [ _i ] . pbkdf2 ) {
if ( crypto . _ _disabled _ _ !== undefined ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , new Error ( "SVR.JS doesn't support PBKDF2-hashed passwords on Node.JS versions without crypto support." ) ) ;
return ;
} else {
var cacheEntry = pbkdf2Cache . find ( function ( entry ) {
return ( entry . password == hashedPassword && entry . salt == list [ _i ] . salt ) ;
} ) ;
2023-12-03 13:58:35 +01:00
if ( cacheEntry ) {
2023-09-03 10:18:52 +02:00
cb ( cacheEntry . hash ) ;
2023-08-31 22:47:07 +02:00
} else {
2023-09-03 10:18:52 +02:00
crypto . pbkdf2 ( password , list [ _i ] . salt , 36250 , 64 , "sha512" , function ( err , derivedKey ) {
2023-12-03 13:58:35 +01:00
if ( err ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , err ) ;
} else {
var key = derivedKey . toString ( "hex" ) ;
2023-12-03 13:58:35 +01:00
pbkdf2Cache . push ( {
hash : key ,
password : hashedPassword ,
salt : list [ _i ] . salt ,
addDate : new Date ( )
} ) ;
2023-09-03 10:18:52 +02:00
cb ( key ) ;
}
2023-08-31 22:47:07 +02:00
} ) ;
2023-08-15 19:05:44 +02:00
}
2023-08-31 22:47:07 +02:00
}
2023-09-03 10:18:52 +02:00
} else {
cb ( hashedPassword ) ;
2023-08-15 14:04:29 +02:00
}
2023-09-03 10:18:52 +02:00
}
2023-08-29 14:56:39 +02:00
2023-09-03 10:18:52 +02:00
function authorizedCallback ( bruteProtection ) {
try {
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 credentialsMatch = credentials . match ( /^Basic (.+)$/ ) ;
if ( ! credentialsMatch ) {
callServerError ( 401 , undefined , undefined , ha ) ;
serverconsole . errmessage ( "Malformed credentials." ) ;
return ;
}
var decodedCredentials = Buffer . from ( credentialsMatch [ 1 ] , "base64" ) . toString ( "utf8" ) ;
var decodedCredentialsMatch = decodedCredentials . match ( /^([^:]*):(.*)$/ ) ;
if ( ! decodedCredentialsMatch ) {
callServerError ( 401 , undefined , undefined , ha ) ;
serverconsole . errmessage ( "Malformed credentials." ) ;
return ;
}
var username = decodedCredentialsMatch [ 1 ] ;
var password = decodedCredentialsMatch [ 2 ] ;
var usernameMatch = [ ] ;
2023-12-03 13:58:35 +01:00
if ( ! authcode . userList || authcode . userList . indexOf ( username ) > - 1 ) {
2023-09-03 10:18:52 +02:00
usernameMatch = users . filter ( function ( entry ) {
return entry . name == username ;
} ) ;
}
2023-12-03 13:58:35 +01:00
if ( usernameMatch . length == 0 ) {
usernameMatch . push ( {
name : username ,
pass : "FAKEPASS" ,
salt : "FAKESALT"
} ) ; // Fake credentials
2023-09-03 10:18:52 +02:00
}
checkIfPasswordMatches ( usernameMatch , password , function ( authorized ) {
try {
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 ( ) ;
2023-08-31 22:47:07 +02:00
}
2023-08-15 19:05:44 +02:00
}
2023-09-03 10:18:52 +02:00
}
callServerError ( 401 , undefined , undefined , ha ) ;
2023-09-03 10:27:30 +02:00
serverconsole . errmessage ( "User \"" + username + "\" failed to log in." ) ;
2023-09-03 10:18:52 +02:00
} else {
if ( bruteProtection ) {
if ( process . send ) {
process . send ( "\x12AUTHR" + reqip ) ;
} else {
if ( bruteForceDb [ reqip ] ) bruteForceDb [ reqip ] = {
invalidAttempts : 0
} ;
2023-08-31 22:47:07 +02:00
}
2023-08-15 19:05:44 +02:00
}
2023-09-03 10:27:30 +02:00
serverconsole . reqmessage ( "Client is logged in as \"" + username + "\"" ) ;
2023-12-03 11:55:19 +01:00
redirectTrailingSlashes ( function ( ) {
modExecute ( mods , vres ( req , res , serverconsole , responseEnd , href , ext , uobject , search , "index.html" , users , page404 , head , foot , "" , callServerError , getCustomHeaders , origHref , redirect , parsePostData ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
return ;
}
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-09-03 10:18:52 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
return ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
}
if ( authcode . disableBruteProtection ) {
2023-09-03 11:08:16 +02:00
// Don't brute-force protect it, just do HTTP authentication
2023-09-03 10:18:52 +02:00
authorizedCallback ( false ) ;
} else if ( ! process . send ) {
2023-09-03 11:08:16 +02:00
// Query data from JS object database
2023-09-03 10:18:52 +02:00
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 ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-03 10:18:52 +02:00
callServerError ( 429 ) ;
serverconsole . errmessage ( "Brute force limit reached!" ) ;
}
} else {
var listenerEmitted = false ;
2023-07-29 20:32:17 +02:00
2023-09-03 11:08:16 +02:00
// Listen for brute-force protection response
2023-09-03 10:18:52 +02:00
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 ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 10:18:52 +02:00
process . on ( "message" , authMessageListener ) ;
process . send ( "\x12AUTHQ" + reqip ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:18:52 +02:00
} else {
2023-12-03 11:55:19 +01:00
redirectTrailingSlashes ( function ( ) {
modExecute ( mods , vres ( req , res , serverconsole , responseEnd , href , ext , uobject , search , "index.html" , users , page404 , head , foot , "" , callServerError , getCustomHeaders , origHref , redirect , parsePostData ) ) ;
} ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 10:18:52 +02:00
} catch ( err ) {
2023-09-03 10:27:30 +02:00
callServerError ( 500 , undefined , generateErrorStack ( err ) ) ;
2023-09-03 10:18:52 +02:00
}
2023-07-29 20:32:17 +02:00
}
2023-09-03 10:27:30 +02:00
2023-07-29 20:32:17 +02:00
server . on ( "error" , function ( err ) {
2023-08-12 12:47:48 +02:00
attmts -- ;
2023-08-12 13:23:59 +02:00
if ( cluster . isPrimary === undefined && attmts >= 0 ) {
2023-08-12 12:47:48 +02:00
if ( err . code == "EADDRINUSE" ) {
serverconsole . locerrmessage ( "Address is already in use by another process." ) ;
} else if ( err . code == "EADDRNOTAVAIL" ) {
serverconsole . locerrmessage ( "Address is not available on this machine." ) ;
} else if ( err . code == "EACCES" ) {
serverconsole . locerrmessage ( "Permission denied. You may not have sufficient privileges to access the requested address." ) ;
} else if ( err . code == "EAFNOSUPPORT" ) {
serverconsole . locerrmessage ( "Address family not supported. The address family (IPv4 or IPv6) of the requested address is not supported." ) ;
} else if ( err . code == "EALREADY" ) {
serverconsole . locerrmessage ( "Operation already in progress. The server is already in the process of establishing a connection on the requested address." ) ;
} else if ( err . code == "ECONNABORTED" ) {
serverconsole . locerrmessage ( "Connection aborted. The connection to the server was terminated abruptly." ) ;
} else if ( err . code == "ECONNREFUSED" ) {
serverconsole . locerrmessage ( "Connection refused. The server refused the connection attempt." ) ;
} else if ( err . code == "ECONNRESET" ) {
serverconsole . locerrmessage ( "Connection reset by peer. The connection to the server was reset by the remote host." ) ;
} else if ( err . code == "EDESTADDRREQ" ) {
serverconsole . locerrmessage ( "Destination address required. The destination address must be specified." ) ;
} else if ( err . code == "ENETDOWN" ) {
serverconsole . locerrmessage ( "Network is down. The network interface used for the connection is not available." ) ;
} else if ( err . code == "ENETUNREACH" ) {
serverconsole . locerrmessage ( "Network is unreachable. The network destination is not reachable from this host." ) ;
} else if ( err . code == "ENOBUFS" ) {
serverconsole . locerrmessage ( "No buffer space available. Insufficient buffer space is available for the server to process the request." ) ;
} else if ( err . code == "ENOTSOCK" ) {
serverconsole . locerrmessage ( "Not a socket. The file descriptor provided is not a valid socket." ) ;
} else if ( err . code == "EPROTO" ) {
serverconsole . locerrmessage ( "Protocol error. An unspecified protocol error occurred." ) ;
} else if ( err . code == "EPROTONOSUPPORT" ) {
serverconsole . locerrmessage ( "Protocol not supported. The requested network protocol is not supported." ) ;
} else if ( err . code == "ETIMEDOUT" ) {
serverconsole . locerrmessage ( "Connection timed out. The server did not respond within the specified timeout period." ) ;
2023-09-02 18:15:00 +02:00
} else if ( err . code == "ENOTFOUND" ) {
serverconsole . locerrmessage ( "Domain name doesn't exist (invalid IP address?)." ) ;
} else if ( err . code == "EINVAL" ) {
serverconsole . locerrmessage ( "Invalid argument (invalid IP address?)." ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-12 12:47:48 +02:00
serverconsole . locerrmessage ( "There was an unknown error with the server." ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-12 12:47:48 +02:00
serverconsole . locmessage ( attmts + " attempts left." ) ;
} else {
2023-08-12 13:23:59 +02:00
try {
process . send ( "\x12ERRLIST" + attmts + err . code ) ;
2023-12-03 14:00:52 +01:00
} catch ( err ) {
2023-08-12 13:23:59 +02:00
// Probably main process exited
}
2023-08-12 12:47:48 +02:00
}
if ( attmts > 0 ) {
server2 . close ( ) ;
setTimeout ( start , 900 ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-12 13:23:59 +02:00
try {
if ( cluster . isPrimary !== undefined ) process . send ( "\x12ERRCRASH" + err . code ) ;
2023-12-03 14:00:52 +01:00
} catch ( err ) {
2023-08-12 13:23:59 +02:00
// Probably main process exited
}
setTimeout ( function ( ) {
var errno = errors [ err . code ] ;
2023-12-03 13:58:35 +01:00
if ( errno ) {
2023-08-12 13:23:59 +02:00
process . exit ( errno ) ;
} else {
process . exit ( 1 ) ;
}
} , 50 ) ;
2023-07-29 20:32:17 +02:00
}
} ) ;
2023-08-09 22:37:53 +02:00
server . on ( "listening" , function ( ) {
2023-09-03 10:27:30 +02:00
attmts = 5 ;
2023-07-29 20:32:17 +02:00
listeningMessage ( ) ;
} ) ;
}
2023-08-09 22:37:53 +02:00
var closedMaster = true ;
2023-07-29 20:32:17 +02:00
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 ( ) ;
}
}
} ;
}
2023-08-09 21:09:23 +02:00
var isWorkerHungUpBuff = true ;
2023-11-12 18:33:29 +01:00
var isWorkerHungUpBuff2 = true ;
2023-08-09 21:09:23 +02:00
2023-07-29 20:32:17 +02:00
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" ) {
2023-09-03 11:08:16 +02:00
// Do nothing!
2023-08-09 21:09:23 +02:00
} else if ( msg == "\x12KILLOK" ) {
2023-12-03 13:58:35 +01:00
if ( typeof isWorkerHungUpBuff != "undefined" ) isWorkerHungUpBuff = false ;
2023-11-12 18:33:29 +01:00
} else if ( msg == "\x12PINGOK" ) {
2023-12-03 13:58:35 +01:00
if ( typeof isWorkerHungUpBuff2 != "undefined" ) isWorkerHungUpBuff2 = false ;
2023-08-09 21:09:23 +02:00
} else if ( msg == "\x12KILLTERMMSG" ) {
serverconsole . locmessage ( "Terminating unused worker process..." ) ;
2023-07-29 20:32:17 +02:00
} else if ( msg == "\x12SAVEGOOD" ) {
serverconsole . locmessage ( "Configuration saved." ) ;
} else if ( msg . indexOf ( "\x12SAVEERR" ) == 0 ) {
2023-11-12 19:52:59 +01:00
serverconsole . locwarnmessage ( "There was a problem while saving configuration file. Reason: " + msg . substr ( 8 ) ) ;
2023-07-29 20:32:17 +02:00
} else if ( msg == "\x12END" ) {
cluster . workers [ Object . keys ( cluster . workers ) [ 0 ] ] . on ( "message" , function ( msg ) {
2023-08-12 13:23:59 +02:00
if ( msg . length >= 8 && msg . indexOf ( "\x12ERRLIST" ) == 0 ) {
2023-07-29 20:32:17 +02:00
var tries = parseInt ( msg . substr ( 8 , 1 ) ) ;
var errCode = msg . substr ( 9 ) ;
if ( errCode == "EADDRINUSE" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Address is already in use by another process." ) ;
2023-07-29 20:32:17 +02:00
} else if ( errCode == "EADDRNOTAVAIL" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Address is not available on this machine." ) ;
2023-07-29 20:32:17 +02:00
} else if ( errCode == "EACCES" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Permission denied. You may not have sufficient privileges to access the requested address." ) ;
} else if ( errCode == "EAFNOSUPPORT" ) {
serverconsole . locerrmessage ( "Address family not supported. The address family (IPv4 or IPv6) of the requested address is not supported." ) ;
} else if ( errCode == "EALREADY" ) {
serverconsole . locerrmessage ( "Operation already in progress. The server is already in the process of establishing a connection on the requested address." ) ;
} else if ( errCode == "ECONNABORTED" ) {
serverconsole . locerrmessage ( "Connection aborted. The connection to the server was terminated abruptly." ) ;
} else if ( errCode == "ECONNREFUSED" ) {
serverconsole . locerrmessage ( "Connection refused. The server refused the connection attempt." ) ;
} else if ( errCode == "ECONNRESET" ) {
serverconsole . locerrmessage ( "Connection reset by peer. The connection to the server was reset by the remote host." ) ;
} else if ( errCode == "EDESTADDRREQ" ) {
serverconsole . locerrmessage ( "Destination address required. The destination address must be specified." ) ;
} else if ( errCode == "ENETDOWN" ) {
serverconsole . locerrmessage ( "Network is down. The network interface used for the connection is not available." ) ;
} else if ( errCode == "ENETUNREACH" ) {
serverconsole . locerrmessage ( "Network is unreachable. The network destination is not reachable from this host." ) ;
} else if ( errCode == "ENOBUFS" ) {
serverconsole . locerrmessage ( "No buffer space available. Insufficient buffer space is available for the server to process the request." ) ;
} else if ( errCode == "ENOTSOCK" ) {
serverconsole . locerrmessage ( "Not a socket. The file descriptor provided is not a valid socket." ) ;
} else if ( errCode == "EPROTO" ) {
serverconsole . locerrmessage ( "Protocol error. An unspecified protocol error occurred." ) ;
} else if ( errCode == "EPROTONOSUPPORT" ) {
serverconsole . locerrmessage ( "Protocol not supported. The requested network protocol is not supported." ) ;
} else if ( errCode == "ETIMEDOUT" ) {
serverconsole . locerrmessage ( "Connection timed out. The server did not respond within the specified timeout period." ) ;
2023-09-02 18:15:00 +02:00
} else if ( errCode == "ENOTFOUND" ) {
serverconsole . locerrmessage ( "Domain name doesn't exist (invalid IP address?)." ) ;
} else if ( errCode == "EINVAL" ) {
serverconsole . locerrmessage ( "Invalid argument (invalid IP address?)." ) ;
2023-07-29 20:44:13 +02:00
} else {
serverconsole . locerrmessage ( "There was an unknown error with the server." ) ;
2023-07-29 20:32:17 +02:00
}
serverconsole . locmessage ( tries + " attempts left." ) ;
}
2023-08-12 13:23:59 +02:00
if ( msg . length >= 9 && msg . indexOf ( "\x12ERRCRASH" ) == 0 ) {
var errno = errors [ msg . substr ( 9 ) ] ;
2023-12-03 13:58:35 +01:00
if ( errno ) {
2023-08-12 13:23:59 +02:00
process . exit ( errno ) ;
} else {
process . exit ( 1 ) ;
}
}
2023-07-29 20:32:17 +02:00
} ) ;
} else {
serverconsole . climessage ( msg ) ;
}
}
var messageTransmitted = false ;
function listeningMessage ( ) {
2023-12-03 13:58:35 +01:00
if ( typeof closedMaster !== "undefined" ) closedMaster = false ;
2023-08-09 18:01:36 +02:00
if ( ! cluster . isPrimary && cluster . isPrimary !== undefined ) {
2023-07-29 20:32:17 +02:00
process . send ( "\x12LISTEN" ) ;
return ;
}
2023-09-02 18:15:00 +02:00
var listenToLocalhost = ( listenAddress && ( listenAddress == "localhost" || listenAddress . match ( /^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/ ) || listenAddress . match ( /^(?:0{0,4}:)+0{0,3}1$/ ) ) ) ;
var listenToAny = ( ! listenAddress || listenAddress . match ( /^0{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/ ) || listenAddress . match ( /^(?:0{0,4}:)+0{0,4}$/ ) ) ;
var sListenToLocalhost = ( sListenAddress && ( sListenAddress == "localhost" || sListenAddress . match ( /^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/ ) || sListenAddress . match ( /^(?:0{0,4}:)+0{0,3}1$/ ) ) ) ;
var sListenToAny = ( ! sListenAddress || sListenAddress . match ( /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/ ) || sListenAddress . match ( /^(?:0{0,4}:)+0{0,4}$/ ) ) ;
var accHost = host ;
var sAccHost = host ;
2023-12-03 13:58:35 +01:00
if ( ! listenToAny ) accHost = listenAddress ;
if ( ! sListenToAny ) sAccHost = sListenAddress ;
2023-08-09 22:37:53 +02:00
if ( messageTransmitted ) return ;
messageTransmitted = true ;
2023-07-29 20:32:17 +02:00
serverconsole . locmessage ( "Started server at: " ) ;
2023-09-02 18:15:00 +02:00
if ( secure && ( sListenToLocalhost || sListenToAny ) ) {
2023-07-29 20:44:13 +02:00
if ( typeof sport === "number" ) {
serverconsole . locmessage ( "* https://localhost" + ( sport == 443 ? "" : ( ":" + sport ) ) ) ;
} else {
2023-09-03 11:08:16 +02:00
serverconsole . locmessage ( "* " + sport ) ; // Unix socket or Windows named pipe
2023-07-29 20:44:13 +02:00
}
}
2023-09-02 18:15:00 +02:00
if ( ! ( secure && disableNonEncryptedServer ) && ( listenToLocalhost || listenToAny ) ) {
2023-07-29 20:44:13 +02:00
if ( typeof port === "number" ) {
serverconsole . locmessage ( "* http://localhost" + ( port == 80 ? "" : ( ":" + port ) ) ) ;
} else {
2023-09-03 11:08:16 +02:00
serverconsole . locmessage ( "* " + port ) ; // Unix socket or Windows named pipe
2023-07-29 20:44:13 +02:00
}
}
2023-09-02 18:15:00 +02:00
if ( secure && typeof sport === "number" && ! sListenToLocalhost && ( ! sListenToAny || ( host != "" && host != "[offline]" ) ) ) serverconsole . locmessage ( "* https://" + ( sAccHost . indexOf ( ":" ) > - 1 ? "[" + sAccHost + "]" : sAccHost ) + ( sport == 443 ? "" : ( ":" + sport ) ) ) ;
if ( ! ( secure && disableNonEncryptedServer ) && ! listenToLocalhost && ( ! listenToAny || ( host != "" && host != "[offline]" ) ) && typeof port === "number" ) serverconsole . locmessage ( "* http://" + ( accHost . indexOf ( ":" ) > - 1 ? "[" + accHost + "]" : accHost ) + ( port == 80 ? "" : ( ":" + port ) ) ) ;
2023-07-29 20:32:17 +02:00
ipStatusCallback ( function ( ) {
if ( pubip != "" ) {
2023-09-02 18:15:00 +02:00
if ( secure && ! sListenToLocalhost ) serverconsole . locmessage ( "* https://" + ( pubip . indexOf ( ":" ) > - 1 ? "[" + pubip + "]" : pubip ) + ( spubport == 443 ? "" : ( ":" + spubport ) ) ) ;
if ( ! ( secure && disableNonEncryptedServer ) && ! listenToLocalhost ) serverconsole . locmessage ( "* http://" + ( pubip . indexOf ( ":" ) > - 1 ? "[" + pubip + "]" : pubip ) + ( pubport == 80 ? "" : ( ":" + pubport ) ) ) ;
2023-07-29 20:32:17 +02:00
}
if ( domain != "" ) {
2023-09-02 18:15:00 +02:00
if ( secure && ! sListenToLocalhost ) serverconsole . locmessage ( "* https://" + domain + ( spubport == 443 ? "" : ( ":" + spubport ) ) ) ;
if ( ! ( secure && disableNonEncryptedServer ) && ! listenToLocalhost ) serverconsole . locmessage ( "* http://" + domain + ( pubport == 80 ? "" : ( ":" + pubport ) ) ) ;
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
serverconsole . locmessage ( "For CLI help, you can type \"help\"" ) ;
2023-07-29 20:32:17 +02:00
} ) ;
}
function start ( init ) {
init = Boolean ( init ) ;
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary || cluster . isPrimary === undefined ) {
2023-07-29 20:32:17 +02:00
if ( init ) {
2023-09-03 11:08:16 +02:00
for ( i = 0 ; i < logo . length ; i ++ ) console . log ( logo [ i ] ) ; // Print logo
2023-07-29 20:32:17 +02:00
console . log ( ) ;
console . log ( "Welcome to DorianTech SVR.JS server." ) ;
2023-09-03 11:08:16 +02:00
// Print warnings
2023-07-29 20:32:17 +02:00
if ( version . indexOf ( "Nightly-" ) === 0 ) serverconsole . locwarnmessage ( "This version is only for test purposes and may be unstable." ) ;
2023-09-08 19:26:40 +02:00
if ( svrmodpackUsed ) serverconsole . locwarnmessage ( "The \"svrmodpack\" library is deprecated. Mods using svrmodpack format may not work in future SVR.JS versions." ) ;
2023-07-29 20:44:13 +02:00
if ( configJSON . enableHTTP2 && ! secure ) serverconsole . locwarnmessage ( "HTTP/2 without HTTPS may not work in web browsers. Web browsers only support HTTP/2 with HTTPS!" ) ;
2023-08-15 19:05:44 +02:00
if ( process . isBun ) {
serverconsole . locwarnmessage ( "Bun support is experimental. Some features of SVR.JS, SVR.JS mods and SVR.JS server-side JavaScript may not work as expected." ) ;
2023-12-03 13:58:35 +01:00
if ( users . some ( function ( entry ) {
return entry . pbkdf2 ;
} ) ) serverconsole . locwarnmessage ( "PBKDF2 password hashing function in Bun blocks the event loop, which may result in denial of service." ) ;
if ( users . some ( function ( entry ) {
return entry . scrypt ;
} ) ) serverconsole . locwarnmessage ( "scrypt password hashing function in Bun blocks the event loop, which may result in denial of service." ) ;
2023-08-15 19:05:44 +02:00
}
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . locwarnmessage ( "You're running SVR.JS on single thread. Reliability may suffer, as the server is stopped after crash." ) ;
2023-08-18 21:35:09 +02:00
if ( crypto . _ _disabled _ _ !== undefined ) serverconsole . locwarnmessage ( "Your Node.JS version doesn't have crypto support! The 'crypto' module is essential for providing cryptographic functionality in Node.JS. Without crypto support, certain security features may be unavailable, and some functionality may not work as expected. It's recommended to use a Node.JS version that includes crypto support to ensure the security and proper functioning of your server." ) ;
if ( crypto . _ _disabled _ _ === undefined && ! crypto . scrypt ) serverconsole . locwarnmessage ( "Your JavaScript runtime doesn't have native scrypt support. HTTP authentication involving scrypt hashes will not work." ) ;
2023-07-29 20:44:13 +02:00
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. Running SVR.JS as root may increase the risks of OS command execution vulnerabilities." ) ;
2023-07-29 20:32:17 +02:00
if ( secure && process . versions && process . versions . openssl && process . versions . openssl . substr ( 0 , 2 ) == "1." ) {
if ( new Date ( ) > new Date ( "11 September 2023" ) ) {
2023-12-03 12:05:14 +01:00
serverconsole . locwarnmessage ( "OpenSSL 1.x is no longer receiving security updates after 11th September 2023. Your HTTPS communication might be vulnerable. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data." ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-12-03 12:05:14 +01:00
serverconsole . locwarnmessage ( "OpenSSL 1.x will no longer receive security updates after 11th September 2023. Your HTTPS communication might be vulnerable in future. It is recommended to update to a newer version of Node.JS that includes OpenSSL 3.0 or higher to ensure the security of your server and data." ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-07-29 20:44:13 +02:00
if ( secure && configJSON . enableOCSPStapling && ocsp . _errored ) serverconsole . locwarnmessage ( "Can't load OCSP module. OCSP stapling will be disabled. OCSP stapling is a security feature that improves the performance and security of HTTPS connections by caching the certificate status response. If you require this feature, consider updating your Node.JS version or checking for any issues with the 'ocsp' module." ) ;
if ( disableMods ) serverconsole . locwarnmessage ( "SVR.JS is running without mods and server-side JavaScript enabled. Web applications may not work as expected" ) ;
2023-07-29 20:32:17 +02:00
console . log ( ) ;
2023-09-03 10:27:30 +02:00
2023-09-03 11:08:16 +02:00
// Display mod and server-side JavaScript errors
2023-12-03 13:58:35 +01:00
if ( process . isPrimary || process . isPrimary === undefined ) {
modLoadingErrors . forEach ( function ( modLoadingError ) {
2023-09-02 20:27:27 +02:00
serverconsole . locwarnmessage ( "There was a problem while loading a \"" + modLoadingError . modName + "\" mod." ) ;
serverconsole . locwarnmessage ( "Stack:" ) ;
serverconsole . locwarnmessage ( generateErrorStack ( modLoadingError . error ) ) ;
} ) ;
2023-12-03 13:58:35 +01:00
if ( SSJSError ) {
2023-09-02 20:27:27 +02:00
serverconsole . locwarnmessage ( "There was a problem while loading server-side JavaScript." ) ;
serverconsole . locwarnmessage ( "Stack:" ) ;
serverconsole . locwarnmessage ( generateErrorStack ( SSJSError ) ) ;
}
2023-12-03 13:58:35 +01:00
if ( SSJSError || modLoadingErrors . length > 0 ) console . log ( ) ;
2023-09-02 20:27:27 +02:00
}
2023-09-03 10:27:30 +02:00
2023-09-03 11:08:16 +02:00
// Print info
2023-07-29 20:32:17 +02:00
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 ) ;
2023-09-03 11:08:16 +02:00
// Throw errors
2023-09-02 18:15:00 +02:00
if ( vnum < 64 ) throw new Error ( "SVR.JS requires Node.JS 10.0.0 and newer, but your Node.JS version isn't supported by SVR.JS." ) ;
2023-09-02 20:27:27 +02:00
if ( configJSONRErr ) throw new Error ( "Can't read SVR.JS configuration file: " + configJSONRErr . message ) ;
if ( configJSONPErr ) throw new Error ( "SVR.JS configuration parse error: " + configJSONPErr . message ) ;
2023-09-02 18:15:00 +02:00
if ( configJSON . enableHTTP2 && ! secure && ( typeof port != "number" ) ) throw new Error ( "HTTP/2 without HTTPS, along with Unix sockets/Windows named pipes aren't supported by SVR.JS." ) ;
2023-09-08 19:39:18 +02:00
if ( configJSON . enableHTTP2 && http2 . _ _disabled _ _ !== undefined ) throw new Error ( "HTTP/2 isn't supported by your Node.JS version! You may not be able to use HTTP/2 with SVR.JS" ) ;
2023-09-02 18:15:00 +02:00
if ( listenAddress ) {
if ( listenAddress . match ( /^[0-9]+$/ ) ) throw new Error ( "Listening network address can't be numeric (it need to be either valid IP address, or valid domain name)." ) ;
if ( listenAddress . match ( /^(?:2(?:2[4-9]|3[0-9])\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$|ff[0-9a-f][0-9a-f]:[0-9a-f:])/i ) ) throw new Error ( "SVR.JS can't listen on multicast address." ) ;
if ( brdIPs . indexOf ( listenAddress ) > - 1 ) throw new Error ( "SVR.JS can't listen on broadcast address." ) ;
if ( netIPs . indexOf ( listenAddress ) > - 1 ) throw new Error ( "SVR.JS can't listen on subnet address." ) ;
2023-07-29 20:32:17 +02:00
}
2023-12-03 13:58:35 +01:00
if ( certificateError ) throw new Error ( "There was a problem with SSL certificate/private key: " + certificateError . message ) ;
if ( wwwrootError ) throw new Error ( "There was a problem with your web root: " + wwwrootError . message ) ;
2023-07-29 20:32:17 +02:00
}
2023-09-03 11:08:16 +02:00
// Information about starting the server
2023-09-03 11:10:01 +02:00
if ( ! ( secure && disableNonEncryptedServer ) ) serverconsole . locmessage ( "Starting HTTP server at " + ( typeof port == "number" ? ( listenAddress ? ( ( listenAddress . indexOf ( ":" ) > - 1 ? "[" + listenAddress + "]" : listenAddress ) ) + ":" : "port " ) : "" ) + port . toString ( ) + "..." ) ;
if ( secure ) serverconsole . locmessage ( "Starting HTTPS server at " + ( typeof sport == "number" ? ( sListenAddress ? ( ( sListenAddress . indexOf ( ":" ) > - 1 ? "[" + sListenAddress + "]" : sListenAddress ) ) + ":" : "port " ) : "" ) + sport . toString ( ) + "..." ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-09 18:01:36 +02:00
if ( ! cluster . isPrimary ) {
2023-08-25 00:26:51 +02:00
try {
2023-12-03 13:58:35 +01:00
if ( typeof ( secure ? sport : port ) == "number" && ( secure ? sListenAddress : listenAddress ) ) {
2023-09-02 18:15:00 +02:00
server . listen ( secure ? sport : port , secure ? sListenAddress : listenAddress ) ;
} else {
server . listen ( secure ? sport : port ) ;
}
2023-12-03 13:58:35 +01:00
} catch ( err ) {
if ( err . code != "ERR_SERVER_ALREADY_LISTEN" ) throw err ;
2023-08-25 00:26:51 +02:00
}
if ( secure && ! disableNonEncryptedServer ) {
try {
2023-12-03 13:58:35 +01:00
if ( typeof port == "number" && listenAddress ) {
2023-09-02 18:15:00 +02:00
server2 . listen ( port , listenAddress ) ;
} else {
server2 . listen ( port ) ;
}
2023-12-03 13:58:35 +01:00
} catch ( err ) {
if ( err . code != "ERR_SERVER_ALREADY_LISTEN" ) throw err ;
2023-08-25 00:26:51 +02:00
}
2023-07-29 20:32:17 +02:00
}
}
2023-09-03 11:08:16 +02:00
// SVR.JS commmands
2023-07-29 20:32:17 +02:00
var commands = {
close : function ( ) {
try {
2023-08-10 04:01:50 +02:00
server . close ( ) ;
if ( secure && ! disableNonEncryptedServer ) {
server2 . close ( ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Server closed." ) ;
2023-07-29 20:32:17 +02:00
else {
process . send ( "Server closed." ) ;
process . send ( "\x12CLOSE" ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Cannot close server! Reason: " + err . message ) ;
2023-08-02 23:54:07 +02:00
else process . send ( "Cannot close server! Reason: " + err . message ) ;
2023-07-29 20:32:17 +02:00
}
} ,
open : function ( ) {
try {
2023-12-03 13:58:35 +01:00
if ( typeof ( secure ? sport : port ) == "number" && ( secure ? sListenAddress : listenAddress ) ) {
2023-09-02 18:15:00 +02:00
server . listen ( secure ? sport : port , secure ? sListenAddress : listenAddress ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-09-02 18:15:00 +02:00
server . listen ( secure ? sport : port ) ;
}
if ( secure && ! disableNonEncryptedServer ) {
2023-12-03 13:58:35 +01:00
if ( typeof port == "number" && listenAddress ) {
2023-09-02 18:15:00 +02:00
server2 . listen ( port , listenAddress ) ;
} else {
server2 . listen ( port ) ;
}
2023-07-29 20:32:17 +02:00
}
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Server opened." ) ;
2023-07-29 20:32:17 +02:00
else {
process . send ( "Server opened." ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Cannot open server! Reason: " + err . message ) ;
2023-08-02 23:54:07 +02:00
else process . send ( "Cannot open server! Reason: " + err . message ) ;
2023-07-29 20:32:17 +02:00
}
} ,
help : function ( ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Server commands:\n" + Object . keys ( commands ) . join ( " " ) ) ;
2023-07-29 20:32:17 +02:00
else process . send ( "Server commands:\n" + Object . keys ( commands ) . join ( " " ) ) ;
} ,
mods : function ( ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Mods:" ) ;
2023-07-29 20:32:17 +02:00
else process . send ( "Mods:" ) ;
for ( var i = 0 ; i < modInfos . length ; i ++ ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( ( i + 1 ) . toString ( ) + ". " + modInfos [ i ] . name + " " + modInfos [ i ] . version ) ;
2023-07-29 20:32:17 +02:00
else process . send ( ( i + 1 ) . toString ( ) + ". " + modInfos [ i ] . name + " " + modInfos [ i ] . version ) ;
}
if ( modInfos . length == 0 ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "No mods installed." ) ;
2023-07-29 20:32:17 +02:00
else process . send ( "No mods installed." ) ;
}
} ,
stop : function ( retcode ) {
2023-07-29 20:44:13 +02:00
reallyExiting = true ;
2023-08-15 19:05:44 +02:00
clearInterval ( pbkdf2CacheIntervalId ) ;
2023-12-03 13:58:35 +01:00
if ( ( ! cluster . isPrimary && cluster . isPrimary !== undefined ) && server . listening ) {
2023-08-10 01:14:10 +02:00
try {
2023-08-29 15:03:13 +02:00
server . close ( function ( ) {
2023-12-03 13:58:35 +01:00
if ( server2 . listening ) {
2023-08-10 01:14:10 +02:00
try {
2023-08-29 15:03:13 +02:00
server2 . close ( function ( ) {
2023-12-03 13:58:35 +01:00
if ( ! process . removeFakeIPC ) {
2023-08-10 04:01:50 +02:00
if ( typeof retcode == "number" ) {
process . exit ( retcode ) ;
} else {
process . exit ( 0 ) ;
}
}
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
if ( ! process . removeFakeIPC ) {
2023-08-10 01:14:10 +02:00
if ( typeof retcode == "number" ) {
process . exit ( retcode ) ;
} else {
process . exit ( 0 ) ;
}
2023-08-10 04:01:50 +02:00
}
}
} else {
2023-12-03 13:58:35 +01:00
if ( ! process . removeFakeIPC ) {
2023-08-10 01:14:10 +02:00
if ( typeof retcode == "number" ) {
process . exit ( retcode ) ;
} else {
process . exit ( 0 ) ;
}
}
}
} ) ;
2023-12-03 13:58:35 +01:00
} catch ( err ) {
2023-08-10 01:14:10 +02:00
if ( typeof retcode == "number" ) {
process . exit ( retcode ) ;
} else {
process . exit ( 0 ) ;
}
}
2023-12-03 13:58:35 +01:00
if ( process . removeFakeIPC ) process . removeFakeIPC ( ) ;
2023-07-29 20:32:17 +02:00
} else {
2023-08-10 01:14:10 +02:00
if ( typeof retcode == "number" ) {
process . exit ( retcode ) ;
} else {
process . exit ( 0 ) ;
}
2023-07-29 20:32:17 +02:00
}
} ,
clear : function ( ) {
console . clear ( ) ;
} ,
block : function ( ip ) {
if ( ip == undefined || JSON . stringify ( ip ) == "[]" ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Cannot block non-existent IP." ) ;
else if ( ! cluster . isPrimary ) process . send ( "Cannot block non-existent IP." ) ;
2023-07-29 20:32:17 +02:00
} 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 ] ) ;
}
}
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "IPs successfully blocked." ) ;
else if ( ! cluster . isPrimary ) process . send ( "IPs successfully blocked." ) ;
2023-07-29 20:32:17 +02:00
}
} ,
unblock : function ( ip ) {
if ( ip == undefined || JSON . stringify ( ip ) == "[]" ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "Cannot unblock non-existent IP." ) ;
else if ( ! cluster . isPrimary ) process . send ( "Cannot unblock non-existent IP." ) ;
2023-07-29 20:32:17 +02:00
} else {
for ( var i = 0 ; i < ip . length ; i ++ ) {
if ( ip [ i ] . indexOf ( ":" ) == - 1 ) {
ip [ i ] = "::ffff:" + ip [ i ] ;
}
blacklist . remove ( ip [ i ] ) ;
}
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "IPs successfully unblocked." ) ;
else if ( ! cluster . isPrimary ) process . send ( "IPs successfully unblocked." ) ;
2023-07-29 20:32:17 +02:00
}
} ,
restart : function ( ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) serverconsole . climessage ( "This command is not supported on single-threaded SVR.JS." ) ;
2023-07-29 20:32:17 +02:00
else process . send ( "This command need to be run in SVR.JS master." ) ;
}
} ;
if ( init ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary === undefined ) {
2023-07-29 20:32:17 +02:00
setInterval ( function ( ) {
try {
saveConfig ( ) ;
serverconsole . locmessage ( "Configuration saved." ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
throw new Error ( err ) ;
2023-07-29 20:32:17 +02:00
}
} , 300000 ) ;
2023-08-09 18:01:36 +02:00
} else if ( cluster . isPrimary ) {
2023-07-29 20:32:17 +02:00
setInterval ( function ( ) {
var allClusters = Object . keys ( cluster . workers ) ;
2023-11-12 18:33:29 +01:00
var goodWorkers = [ ] ;
2023-12-03 13:58:35 +01:00
2023-11-12 18:33:29 +01:00
function checkWorker ( callback , _id ) {
2023-12-03 13:58:35 +01:00
if ( typeof _id === "undefined" ) _id = 0 ;
if ( _id >= allClusters . length ) {
2023-11-12 18:33:29 +01:00
callback ( ) ;
return ;
}
2023-07-29 20:32:17 +02:00
try {
2023-11-12 18:33:29 +01:00
if ( cluster . workers [ allClusters [ _id ] ] ) {
isWorkerHungUpBuff2 = true ;
cluster . workers [ allClusters [ _id ] ] . on ( "message" , msgListener ) ;
cluster . workers [ allClusters [ _id ] ] . send ( "\x14PINGPING" ) ;
setTimeout ( function ( ) {
if ( isWorkerHungUpBuff2 ) {
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-11-12 18:33:29 +01:00
} else {
goodWorkers . push ( allClusters [ _id ] ) ;
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-11-12 18:33:29 +01:00
}
} , 250 ) ;
} else {
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-11-12 18:33:29 +01:00
if ( cluster . workers [ allClusters [ _id ] ] ) {
cluster . workers [ allClusters [ _id ] ] . removeAllListeners ( "message" ) ;
cluster . workers [ allClusters [ _id ] ] . on ( "message" , bruteForceListenerWrapper ( cluster . workers [ allClusters [ _id ] ] ) ) ;
cluster . workers [ allClusters [ _id ] ] . on ( "message" , listenConnListener ) ;
2023-07-29 20:32:17 +02:00
}
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-07-29 20:32:17 +02:00
}
}
2023-11-12 18:33:29 +01:00
checkWorker ( function ( ) {
2023-12-03 13:58:35 +01:00
var wN = Math . floor ( Math . random ( ) * goodWorkers . length ) ; //Send a configuration saving message to a random worker.
try {
if ( cluster . workers [ goodWorkers [ wN ] ] ) {
isWorkerHungUpBuff2 = true ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , msgListener ) ;
cluster . workers [ goodWorkers [ wN ] ] . send ( "\x14SAVECONF" ) ;
2023-11-12 18:33:29 +01:00
}
2023-12-03 13:58:35 +01:00
} catch ( err ) {
if ( cluster . workers [ goodWorkers [ wN ] ] ) {
cluster . workers [ goodWorkers [ wN ] ] . removeAllListeners ( "message" ) ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , bruteForceListenerWrapper ( cluster . workers [ goodWorkers [ wN ] ] ) ) ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , listenConnListener ) ;
}
serverconsole . locwarnmessage ( "There was a problem while saving configuration file. Reason: " + err . message ) ;
}
2023-11-12 18:33:29 +01:00
} ) ;
2023-07-29 20:32:17 +02:00
} , 300000 ) ;
}
2023-08-15 19:05:44 +02:00
if ( ! cluster . isPrimary ) {
pbkdf2CacheIntervalId = setInterval ( function ( ) {
2023-08-29 15:03:13 +02:00
pbkdf2Cache = pbkdf2Cache . filter ( function ( entry ) {
2023-08-15 19:05:44 +02:00
return entry . addDate > ( new Date ( ) - 3600000 ) ;
} ) ;
2023-08-29 15:03:13 +02:00
scryptCache = scryptCache . filter ( function ( entry ) {
2023-08-18 21:35:09 +02:00
return entry . addDate > ( new Date ( ) - 3600000 ) ;
} ) ;
2023-08-21 19:38:38 +02:00
} , 1800000 ) ;
2023-08-15 19:05:44 +02:00
}
2023-08-09 18:01:36 +02:00
if ( ! cluster . isPrimary && cluster . isPrimary !== undefined ) {
2023-07-29 20:32:17 +02:00
process . on ( "message" , function ( line ) {
try {
if ( line == "" ) {
2023-09-03 11:08:16 +02:00
// Does Nothing
2023-07-29 20:32:17 +02:00
process . send ( "\x12END" ) ;
} else if ( line == "\x14SAVECONF" ) {
2023-09-03 11:08:16 +02:00
// Save configuration file
2023-07-29 20:32:17 +02:00
try {
saveConfig ( ) ;
process . send ( "\x12SAVEGOOD" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
process . send ( "\x12SAVEERR" + err . message ) ;
2023-07-29 20:32:17 +02:00
}
process . send ( "\x12END" ) ;
2023-08-09 21:09:23 +02:00
} else if ( line == "\x14KILLPING" ) {
2023-12-03 13:58:35 +01:00
if ( ! reallyExiting ) {
2023-08-10 01:14:10 +02:00
process . send ( "\x12KILLOK" ) ;
process . send ( "\x12END" ) ;
}
// Refuse to send, when it's really exiting. Main process will treat the worker as hung up anyway...
2023-11-12 18:33:29 +01:00
} else if ( line == "\x14PINGPING" ) {
2023-12-03 13:58:35 +01:00
if ( ! reallyExiting ) {
2023-11-12 18:33:29 +01:00
process . send ( "\x12PINGOK" ) ;
process . send ( "\x12END" ) ;
}
// Refuse to send, when it's really exiting. Main process will treat the worker as hung up anyway...
2023-08-09 21:09:23 +02:00
} else if ( line == "\x14KILLREQ" ) {
2023-12-03 13:58:35 +01:00
if ( reqcounter - reqcounterKillReq < 2 ) {
2023-08-09 21:09:23 +02:00
process . send ( "\x12KILLTERMMSG" ) ;
2023-08-09 21:23:50 +02:00
process . nextTick ( commands . stop ) ;
2023-08-09 21:09:23 +02:00
} else {
reqcounterKillReq = reqcounter ;
}
2023-07-29 20:32:17 +02:00
} 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" ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
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 != "" ) {
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary !== undefined ) {
2023-07-29 20:32:17 +02:00
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 ( ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
stopError = true ;
}
}
if ( stopError ) serverconsole . climessage ( "Some SVR.JS workers might not be stopped." ) ;
SVRJSInitialized = false ;
2023-08-09 22:37:53 +02:00
closedMaster = true ;
2023-07-29 20:32:17 +02:00
var cpus = os . cpus ( ) . length ;
if ( cpus > 16 ) cpus = 16 ;
try {
2023-09-03 11:08:16 +02:00
var useAvailableCores = Math . round ( ( os . freemem ( ) ) / 50000000 ) - 1 ; // 1 core deleted for safety...
2023-07-29 20:32:17 +02:00
if ( cpus > useAvailableCores ) cpus = useAvailableCores ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Nevermind... Don't want SVR.JS to fail starting, because os.freemem function is not working.
2023-07-29 20:32:17 +02:00
}
2023-09-03 11:08:16 +02:00
if ( cpus < 1 ) cpus = 1 ; // If SVR.JS is run on Haiku or if useAvailableCores = 0
2023-07-29 20:32:17 +02:00
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 ) ;
}
2023-08-19 22:38:58 +02:00
allClusters . forEach ( function ( clusterID ) {
2023-07-29 20:32:17 +02:00
try {
2023-08-19 22:38:58 +02:00
if ( cluster . workers [ clusterID ] ) {
cluster . workers [ clusterID ] . on ( "message" , msgListener ) ;
cluster . workers [ clusterID ] . send ( line ) ;
2023-07-29 20:32:17 +02:00
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-08-19 22:38:58 +02:00
if ( cluster . workers [ clusterID ] ) {
cluster . workers [ clusterID ] . removeAllListeners ( "message" ) ;
cluster . workers [ clusterID ] . on ( "message" , bruteForceListenerWrapper ( cluster . workers [ clusterID ] ) ) ;
cluster . workers [ clusterID ] . on ( "message" , listenConnListener ) ;
2023-07-29 20:32:17 +02:00
}
serverconsole . climessage ( "Can't run command \"" + command + "\"." ) ;
}
2023-08-19 22:38:58 +02:00
} ) ;
2023-07-29 20:32:17 +02:00
if ( command == "stop" ) {
setTimeout ( function ( ) {
2023-07-29 20:44:13 +02:00
reallyExiting = true ;
2023-07-29 20:32:17 +02:00
process . exit ( 0 ) ;
} , 50 ) ;
}
} else {
2023-07-29 20:44:13 +02:00
if ( command == "stop" ) {
reallyExiting = true ;
process . exit ( 0 ) ;
}
2023-07-29 20:32:17 +02:00
try {
commands [ command ] ( argss ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
serverconsole . climessage ( "Unrecognized command \"" + command + "\"." ) ;
}
}
}
rla . prompt ( ) ;
} ) ;
}
2023-08-12 12:35:46 +02:00
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary || cluster . isPrimary === undefined ) {
2023-09-03 11:08:16 +02:00
// Cluster forking code
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary !== undefined && init ) {
2023-07-29 20:32:17 +02:00
var cpus = os . cpus ( ) . length ;
if ( cpus > 16 ) cpus = 16 ;
try {
2023-09-03 11:08:16 +02:00
var useAvailableCores = Math . round ( ( os . freemem ( ) ) / 50000000 ) - 1 ; // 1 core deleted for safety...
2023-07-29 20:32:17 +02:00
if ( cpus > useAvailableCores ) cpus = useAvailableCores ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Nevermind... Don't want SVR.JS to fail starting, because os.freemem function is not working.
2023-07-29 20:32:17 +02:00
}
2023-09-03 11:08:16 +02:00
if ( cpus < 1 ) cpus = 1 ; // If SVR.JS is run on Haiku (os.cpus in Haiku returns empty array) or if useAvailableCores = 0
2023-07-29 20:32:17 +02:00
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 ) {
2023-08-12 13:23:59 +02:00
if ( msg . length >= 8 && msg . indexOf ( "\x12ERRLIST" ) == 0 ) {
2023-07-29 20:32:17 +02:00
var tries = parseInt ( msg . substr ( 8 , 1 ) ) ;
var errCode = msg . substr ( 9 ) ;
if ( errCode == "EADDRINUSE" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Address is already in use by another process." ) ;
2023-07-29 20:32:17 +02:00
} else if ( errCode == "EADDRNOTAVAIL" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Address is not available on this machine." ) ;
2023-07-29 20:32:17 +02:00
} else if ( errCode == "EACCES" ) {
2023-07-29 20:44:13 +02:00
serverconsole . locerrmessage ( "Permission denied. You may not have sufficient privileges to access the requested address." ) ;
} else if ( errCode == "EAFNOSUPPORT" ) {
serverconsole . locerrmessage ( "Address family not supported. The address family (IPv4 or IPv6) of the requested address is not supported." ) ;
} else if ( errCode == "EALREADY" ) {
serverconsole . locerrmessage ( "Operation already in progress. The server is already in the process of establishing a connection on the requested address." ) ;
} else if ( errCode == "ECONNABORTED" ) {
serverconsole . locerrmessage ( "Connection aborted. The connection to the server was terminated abruptly." ) ;
} else if ( errCode == "ECONNREFUSED" ) {
serverconsole . locerrmessage ( "Connection refused. The server refused the connection attempt." ) ;
} else if ( errCode == "ECONNRESET" ) {
serverconsole . locerrmessage ( "Connection reset by peer. The connection to the server was reset by the remote host." ) ;
} else if ( errCode == "EDESTADDRREQ" ) {
serverconsole . locerrmessage ( "Destination address required. The destination address must be specified." ) ;
} else if ( errCode == "ENETDOWN" ) {
serverconsole . locerrmessage ( "Network is down. The network interface used for the connection is not available." ) ;
} else if ( errCode == "ENETUNREACH" ) {
serverconsole . locerrmessage ( "Network is unreachable. The network destination is not reachable from this host." ) ;
} else if ( errCode == "ENOBUFS" ) {
serverconsole . locerrmessage ( "No buffer space available. Insufficient buffer space is available for the server to process the request." ) ;
} else if ( errCode == "ENOTSOCK" ) {
serverconsole . locerrmessage ( "Not a socket. The file descriptor provided is not a valid socket." ) ;
} else if ( errCode == "EPROTO" ) {
serverconsole . locerrmessage ( "Protocol error. An unspecified protocol error occurred." ) ;
} else if ( errCode == "EPROTONOSUPPORT" ) {
serverconsole . locerrmessage ( "Protocol not supported. The requested network protocol is not supported." ) ;
} else if ( errCode == "ETIMEDOUT" ) {
serverconsole . locerrmessage ( "Connection timed out. The server did not respond within the specified timeout period." ) ;
2023-09-02 18:15:00 +02:00
} else if ( errCode == "ENOTFOUND" ) {
serverconsole . locerrmessage ( "Domain name doesn't exist (invalid IP address?)." ) ;
} else if ( errCode == "EINVAL" ) {
serverconsole . locerrmessage ( "Invalid argument (invalid IP address?)." ) ;
2023-07-29 20:44:13 +02:00
} else {
serverconsole . locerrmessage ( "There was an unknown error with the server." ) ;
2023-07-29 20:32:17 +02:00
}
serverconsole . locmessage ( tries + " attempts left." ) ;
}
2023-08-12 13:23:59 +02:00
if ( msg . length >= 9 && msg . indexOf ( "\x12ERRCRASH" ) == 0 ) {
var errno = errors [ msg . substr ( 9 ) ] ;
2023-12-03 13:58:35 +01:00
if ( errno ) {
2023-08-12 13:23:59 +02:00
process . exit ( errno ) ;
} else {
process . exit ( 1 ) ;
}
}
2023-07-29 20:32:17 +02:00
} ) ;
2023-08-12 12:35:46 +02:00
2023-08-09 21:09:23 +02:00
// Hangup check and restart
2023-07-29 20:32:17 +02:00
setInterval ( function ( ) {
if ( ! closedMaster && ! exiting ) {
var chksocket = { } ;
if ( secure && disableNonEncryptedServer ) {
chksocket = https . get ( {
2023-09-02 18:15:00 +02:00
hostname : ( typeof sport == "number" && sListenAddress ) ? sListenAddress : "localhost" ,
2023-07-29 20:44:13 +02:00
port : ( typeof sport == "number" ) ? sport : undefined ,
socketPath : ( typeof sport == "number" ) ? undefined : sport ,
2023-07-29 20:32:17 +02:00
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" )
} ,
2023-08-09 23:03:16 +02:00
timeout : 1620 ,
2023-07-29 20:32:17 +02:00
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 ) {
2023-09-03 11:08:16 +02:00
// It doesn't support through Unix sockets or Windows named pipes
2023-12-03 13:58:35 +01:00
var address = ( ( typeof port == "number" && listenAddress ) ? listenAddress : "localhost" ) . replace ( /\/@/g , "" ) ;
if ( address . indexOf ( ":" ) > - 1 ) {
2023-09-02 18:15:00 +02:00
address = "[" + address + "]" ;
}
var connection = http2 . connect ( "http://" + address + ":" + port . toString ( ) ) ;
2023-07-29 20:32:17 +02:00
connection . on ( "error" , function ( ) {
if ( ! exiting ) {
if ( ! crashed ) SVRJSFork ( ) ;
else crashed = false ;
}
} ) ;
2023-08-09 23:03:16 +02:00
connection . setTimeout ( 1620 , function ( ) {
2023-07-29 20:32:17 +02:00
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 ( {
2023-09-02 18:15:00 +02:00
hostname : ( typeof port == "number" && listenAddress ) ? listenAddress : "localhost" ,
2023-07-29 20:44:13 +02:00
port : ( typeof port == "number" ) ? port : undefined ,
socketPath : ( typeof port == "number" ) ? undefined : port ,
2023-07-29 20:32:17 +02:00
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" )
} ,
2023-08-09 23:03:16 +02:00
timeout : 1620
2023-07-29 20:32:17 +02:00
} , 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 ;
} ) ;
}
}
2023-08-09 23:03:16 +02:00
} , 4550 ) ;
2023-08-12 12:35:46 +02:00
2023-08-09 21:09:23 +02:00
// Termination of unused good workers
2023-12-03 13:58:35 +01:00
if ( ! disableUnusedWorkerTermination && cluster . isPrimary !== undefined ) {
2023-08-09 21:09:23 +02:00
setTimeout ( function ( ) {
setInterval ( function ( ) {
2023-08-09 21:58:21 +02:00
if ( ! closedMaster && ! exiting ) {
var allClusters = Object . keys ( cluster . workers ) ;
2023-08-09 22:37:53 +02:00
var minClusters = 0 ;
2023-08-09 23:03:16 +02:00
minClusters = Math . ceil ( cpus * 0.625 ) ;
2023-12-03 13:58:35 +01:00
if ( minClusters < 2 ) minClusters = 2 ;
2023-08-09 21:58:21 +02:00
var goodWorkers = [ ] ;
2023-12-03 13:58:35 +01:00
2023-08-09 21:58:21 +02:00
function checkWorker ( callback , _id ) {
2023-12-03 13:58:35 +01:00
if ( typeof _id === "undefined" ) _id = 0 ;
if ( _id >= allClusters . length ) {
2023-08-09 21:58:21 +02:00
callback ( ) ;
return ;
2023-08-09 21:09:23 +02:00
}
try {
2023-08-09 21:58:21 +02:00
if ( cluster . workers [ allClusters [ _id ] ] ) {
2023-08-09 21:09:23 +02:00
isWorkerHungUpBuff = true ;
2023-08-09 21:58:21 +02:00
cluster . workers [ allClusters [ _id ] ] . on ( "message" , msgListener ) ;
cluster . workers [ allClusters [ _id ] ] . send ( "\x14KILLPING" ) ;
2023-08-29 15:03:13 +02:00
setTimeout ( function ( ) {
2023-08-09 21:58:21 +02:00
if ( isWorkerHungUpBuff ) {
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-08-09 21:58:21 +02:00
} else {
goodWorkers . push ( allClusters [ _id ] ) ;
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-08-09 21:58:21 +02:00
}
} , 250 ) ;
} else {
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-08-09 21:09:23 +02:00
}
} catch ( err ) {
2023-08-09 21:58:21 +02:00
if ( cluster . workers [ allClusters [ _id ] ] ) {
cluster . workers [ allClusters [ _id ] ] . removeAllListeners ( "message" ) ;
cluster . workers [ allClusters [ _id ] ] . on ( "message" , bruteForceListenerWrapper ( cluster . workers [ allClusters [ _id ] ] ) ) ;
cluster . workers [ allClusters [ _id ] ] . on ( "message" , listenConnListener ) ;
2023-08-09 21:09:23 +02:00
}
2023-12-03 13:58:35 +01:00
checkWorker ( callback , _id + 1 ) ;
2023-08-29 15:03:13 +02:00
}
2023-08-09 21:09:23 +02:00
}
2023-08-29 15:03:13 +02:00
checkWorker ( function ( ) {
2023-08-09 21:58:21 +02:00
if ( goodWorkers . length > minClusters ) {
var wN = Math . floor ( Math . random ( ) * goodWorkers . length ) ;
if ( wN == goodWorkers . length ) return ;
try {
if ( cluster . workers [ goodWorkers [ wN ] ] ) {
isWorkerHungUpBuff = true ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , msgListener ) ;
cluster . workers [ goodWorkers [ wN ] ] . send ( "\x14KILLREQ" ) ;
}
} catch ( err ) {
if ( cluster . workers [ goodWorkers [ wN ] ] ) {
cluster . workers [ goodWorkers [ wN ] ] . removeAllListeners ( "message" ) ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , bruteForceListenerWrapper ( cluster . workers [ goodWorkers [ wN ] ] ) ) ;
cluster . workers [ goodWorkers [ wN ] ] . on ( "message" , listenConnListener ) ;
}
2023-11-12 19:52:59 +01:00
serverconsole . locwarnmessage ( "There was a problem while terminating unused worker process. Reason: " + err . message ) ;
2023-08-09 21:58:21 +02:00
}
}
} ) ;
}
2023-08-19 21:19:18 +02:00
} , 300000 ) ;
2023-08-09 22:37:53 +02:00
} , 2000 ) ;
2023-08-09 21:09:23 +02:00
}
2023-07-29 20:32:17 +02:00
}
}
}
}
2023-09-03 11:08:16 +02:00
// Save configuration file
2023-07-29 20:32:17 +02:00
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 ;
2023-09-09 00:36:24 +02:00
if ( configJSONobj . enableRemoteLogBrowsing === undefined ) configJSONobj . enableRemoteLogBrowsing = false ;
2023-07-29 20:32:17 +02:00
if ( configJSONobj . exposeServerVersion === undefined ) configJSONobj . exposeServerVersion = true ;
2023-09-02 09:01:25 +02:00
if ( configJSONobj . disableServerSideScriptExpose === undefined ) configJSONobj . disableServerSideScriptExpose = true ;
2023-07-29 20:32:17 +02:00
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 ;
2023-07-29 20:44:13 +02:00
if ( configJSONobj . enableETag === undefined ) configJSONobj . enableETag = true ;
2023-08-12 13:37:06 +02:00
if ( configJSONobj . disableUnusedWorkerTermination === undefined ) configJSONobj . disableUnusedWorkerTermination = false ;
2023-08-18 23:29:18 +02:00
if ( configJSONobj . rewriteDirtyURLs === undefined ) configJSONobj . rewriteDirtyURLs = false ;
2023-08-31 22:47:07 +02:00
if ( configJSONobj . errorPages === undefined ) configJSONobj . errorPages = [ ] ;
2023-09-02 12:57:19 +02:00
if ( configJSONobj . useWebRootServerSideScript === undefined ) configJSONobj . useWebRootServerSideScript = true ;
2023-09-05 00:05:20 +02:00
if ( configJSONobj . exposeModsInErrorPages === undefined ) configJSONobj . exposeModsInErrorPages = true ;
2023-12-03 11:55:19 +01:00
if ( configJSONobj . disableTrailingSlashRedirects === undefined ) configJSONobj . disableTrailingSlashRedirects = false ;
2023-12-03 12:11:15 +01:00
if ( configJSONobj . environmentVariables === undefined ) configJSONobj . environmentVariables = { } ;
2023-12-03 12:02:49 +01:00
var configString = JSON . stringify ( configJSONobj , null , 2 ) + "\n" ;
2023-07-29 20:32:17 +02:00
fs . writeFileSync ( _ _dirname + "/config.json" , configString ) ;
break ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
if ( i >= 2 ) throw err ;
2023-07-29 20:32:17 +02:00
var now = Date . now ( ) ;
while ( Date . now ( ) - now < 2 ) ;
}
}
}
2023-09-03 11:08:16 +02:00
// Process event listeners
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary || cluster . isPrimary === undefined ) {
2023-08-02 23:54:07 +02:00
process . on ( "uncaughtException" , function ( err ) {
2023-09-03 11:08:16 +02:00
// CRASH HANDLER
2023-07-29 20:32:17 +02:00
serverconsole . locerrmessage ( "SVR.JS master process just crashed!!!" ) ;
serverconsole . locerrmessage ( "Stack:" ) ;
2023-08-02 23:54:07 +02:00
serverconsole . locerrmessage ( generateErrorStack ( err ) ) ;
process . exit ( err . errno ) ;
2023-07-29 20:32:17 +02:00
} ) ;
2023-08-02 23:54:07 +02:00
process . on ( "unhandledRejection" , function ( err ) {
2023-09-03 11:08:16 +02:00
// CRASH HANDLER
2023-07-29 20:32:17 +02:00
serverconsole . locerrmessage ( "SVR.JS master process just crashed!!!" ) ;
serverconsole . locerrmessage ( "Stack:" ) ;
2023-08-02 23:54:07 +02:00
serverconsole . locerrmessage ( err . stack ? generateErrorStack ( err ) : String ( err ) ) ;
process . exit ( err . errno ) ;
2023-07-29 20:32:17 +02:00
} ) ;
process . on ( "exit" , function ( code ) {
try {
2023-12-03 13:58:35 +01:00
if ( ! configJSONRErr && ! configJSONPErr ) {
2023-09-02 20:27:27 +02:00
saveConfig ( ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-11-12 19:52:59 +01:00
serverconsole . locwarnmessage ( "There was a problem while saving configuration file. Reason: " + err . message ) ;
2023-07-29 20:32:17 +02:00
}
try {
deleteFolderRecursive ( _ _dirname + "/temp" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Error!
2023-07-29 20:32:17 +02:00
}
try {
fs . mkdirSync ( _ _dirname + "/temp" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Error!
2023-07-29 20:32:17 +02:00
}
2023-09-10 19:03:28 +02:00
if ( process . isBun && process . versions . bun && process . versions . bun [ 0 ] == "0" ) {
2023-07-29 20:32:17 +02:00
try {
2023-09-03 11:08:16 +02:00
fs . writeFileSync ( _ _dirname + "/temp/serverSideScript.js" , "// Placeholder server-side JavaScript to workaround Bun bug.\r\n" ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Error!
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
}
serverconsole . locmessage ( "Server closed with exit code: " + code ) ;
} ) ;
process . on ( "warning" , function ( warning ) {
serverconsole . locwarnmessage ( warning . message ) ;
if ( generateErrorStack ( warning ) ) {
2023-07-29 20:32:17 +02:00
serverconsole . locwarnmessage ( "Stack:" ) ;
serverconsole . locwarnmessage ( generateErrorStack ( warning ) ) ;
}
} ) ;
process . on ( "SIGINT" , function ( ) {
2023-07-29 20:44:13 +02:00
reallyExiting = true ;
2023-08-09 18:01:36 +02:00
if ( cluster . isPrimary !== undefined ) {
2023-07-29 20:32:17 +02:00
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" ) ;
}
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-09-03 11:08:16 +02:00
// Worker will crash with EPIPE anyway.
2023-07-29 20:32:17 +02:00
}
}
}
serverconsole . locmessage ( "Server terminated using SIGINT" ) ;
process . exit ( ) ;
} ) ;
} else {
2023-08-02 23:54:07 +02:00
process . on ( "uncaughtException" , function ( err ) {
2023-09-03 11:08:16 +02:00
// CRASH HANDLER
2023-07-29 20:32:17 +02:00
serverconsole . locerrmessage ( "SVR.JS worker just crashed!!!" ) ;
serverconsole . locerrmessage ( "Stack:" ) ;
2023-08-02 23:54:07 +02:00
serverconsole . locerrmessage ( generateErrorStack ( err ) ) ;
process . exit ( err . errno ) ;
2023-07-29 20:32:17 +02:00
} ) ;
2023-08-02 23:54:07 +02:00
process . on ( "unhandledRejection" , function ( err ) {
2023-09-03 11:08:16 +02:00
// CRASH HANDLER
2023-07-29 20:32:17 +02:00
serverconsole . locerrmessage ( "SVR.JS worker just crashed!!!" ) ;
serverconsole . locerrmessage ( "Stack:" ) ;
2023-08-02 23:54:07 +02:00
serverconsole . locerrmessage ( err . stack ? generateErrorStack ( err ) : String ( err ) ) ;
process . exit ( err . errno ) ;
2023-07-29 20:32:17 +02:00
} ) ;
process . on ( "warning" , function ( warning ) {
serverconsole . locwarnmessage ( warning . message ) ;
if ( warning . stack ) {
serverconsole . locwarnmessage ( "Stack:" ) ;
serverconsole . locwarnmessage ( generateErrorStack ( warning ) ) ;
}
} ) ;
}
2023-09-03 11:08:16 +02:00
// Start SVR.JS!
2023-07-29 20:32:17 +02:00
try {
start ( true ) ;
2023-08-02 23:54:07 +02:00
} catch ( err ) {
2023-07-29 20:32:17 +02:00
serverconsole . locerrmessage ( "There was a problem starting SVR.JS!!!" ) ;
serverconsole . locerrmessage ( "Stack:" ) ;
2023-08-02 23:54:07 +02:00
serverconsole . locerrmessage ( generateErrorStack ( err ) ) ;
2023-12-03 13:58:35 +01:00
setTimeout ( function ( ) {
2023-09-10 10:14:24 +02:00
process . exit ( err . errno ? err . errno : 1 ) ;
} , 10 ) ;
2023-07-29 20:32:17 +02:00
}
2023-07-29 20:44:13 +02:00
//////////////////////////////////
//// THE END! ////
//// WARNING: THE CODE HAS ////
//// 5000+ LINES! ////
//////////////////////////////////