This repository was archived by the owner on Jan 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
395 lines (329 loc) · 10.5 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"use strict";
/* globals global require process logDir htmlDocs logger Buffer __dirname */
// the ws and compression modules are from npm
// I think express is too?
const cluster = require('cluster');
const url = require('url');
const qs = require('querystring');
const http = require('http');
const https = require('https');
const WebSocket = require('ws');
const fs = require('fs');
const domain = require('domain');
const express = require('express');
const compression = require('compression');
const acceptedHosts = ["nishicode.com", "www.nishicode.com"];
//const crypto = require('crypto');
const badExtension = /\.php(?=\?|$)/;
const maxPost = 1e4;
let isValidHost = (host) => (host = host.split(':')[0], acceptedHosts.some(check => check === host));
/* function salter (text) {
if (!text) {
return 0;
}
let ret = 0;
for (let c = 0; c < text.length; c++) {
ret = ((ret << 1) | (ret >> 23)) & 0xFFFFFF;
ret ^= text.charCodeAt(c);
}
return ret.toString(16);
}
let passhash = (pass) => crypto.scryptSync(pass, salter(pass), 64).toString('base64'); */
Object.defineProperties(global, {
logDir: {
value: __dirname + '/logs',
writable: false,
},
htmlDocs: {
value: __dirname + '/html',
writable: false,
},
});
Object.defineProperties(global, {
require: {
value: require,
writable: false,
},
logger: {
value: (() => {
if (cluster.isMaster) {
return console;
}
let myout;
let myerr;
if (process.stdout.isTTY) {
myout = process.stdout;
myerr = process.stderr;
} else {
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
myout = fs.createWriteStream( logDir + '/CONSOLE', {flags: 'a'});
myerr = myout;
}
return new console.Console(myout, myerr);
})(),
writable: false,
},
});
const scripts = new class {
constructor () {
this.watch = {};
}
load (file) {
try {
file = require.resolve(file);
if (!this.watch[file]) {
logger.log('Loading script: ' + file);
this.watch[file] = fs.watch(file, {persistent: false}, () => {
try {
if (require.cache[file]) {
delete require.cache[file];
}
this.watch[file].close();
delete this.watch[file];
} catch (err) {
logger.log(err.stack);
}
});
}
return require(file);
} catch (err) {
logger.log(err.stack);
}
return null;
}
};
function scriptHandler (req, res, next) {
let q = url.parse(req.url, true);
let filepathbase = htmlDocs + decodeURI(q.pathname);
let postdata = [], postdatalen = 0;
if (!/\.sss$/i.test(filepathbase)) {
filepathbase += ".sss"; // I just use sss for 'server side script'
}
fs.access(filepathbase, fs.constants.R_OK, access_err => {
if (access_err) {
return next();
}
try {
let script = scripts.load(filepathbase), scriptInterface;
if (script) {
if (typeof script.request === 'function') {
req.on('data', (chunk) => {
postdatalen += chunk.length;
if (postdatalen > maxPost) {
res.status(413).end();
res.connection.destroy();
} else {
postdata.push(chunk);
}
});
req.on('end', () => {
new Promise((resolve, reject) => {
scriptInterface = {
responseCode: 200,
headers: {'Content-Type': 'text/plain'},
setCookie: {},
getPostData: () => Buffer.concat(postdata).toString(),
query: q.query,
method: req.method,
path: q.pathname,
resolve: resolve,
reject: reject,
cookie: (req.headers.cookie ? qs.parse(req.headers.cookie, ';') : {}),
};
script.request(scriptInterface, logger);
}).then(response => {
for (let k in scriptInterface.setCookie) {
res.setHeader('Set-Cookie', qs.escape(k) + "=" + qs.escape(scriptInterface.setCookie[k]));
}
res.writeHead(scriptInterface.responseCode, scriptInterface.headers);
if (response !== undefined && response !== null) {
res.end(response.toString(), 'binary');
} else {
res.end();
}
}).catch(err => {
for (let k in scriptInterface.setCookie) {
res.setHeader('Set-Cookie', qs.escape(k) + "=" + qs.escape(scriptInterface.setCookie[k]));
}
logger.log(`[${process.pid} @ ${new Date().toUTCString()}] ` + err.stack ? err.stack : err.toString());
res.writeHead(500, scriptInterface.headers);
if (err !== undefined && err !== null) {
res.end(err.stack ? err.stack : err.toString(), 'binary');
} else {
res.end();
}
});
});
} else {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('API Loaded Successfully!');
}
} else {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Error loading script!');
}
} catch (err) {
logger.log(err);
}
return next();
});
}
function scriptRouter (req, res, next) {
let d;
switch (req.method) {
case 'GET':
case 'POST':
case 'PUT':
case 'DELETE':
d = domain.create();
d.on('error', (err) => {
res.writeHead(500, {'Content-Type': 'text/plain'});
if (err) {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}] ` + err.stack ? err.stack : err.toString());
res.end(err.stack ? err.stack : err.toString(), 'binary');
} else {
res.end('Internal Server Error');
}
});
d.run(() => {
scriptHandler(req, res, next);
});
break;
default:
return next();
}
}
function checkDomain (req, res, next) {
let parts = req.headers.host.split('.');
if (parts.length < 3) {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}][${req.socket.remoteAddress}] ${req.method} ${JSON.stringify(req.headers.host)}${req.url}\t(forward to www)`);
res.writeHead(301, {Location: 'https://www.' + req.headers.host + req.url});
res.end();
return true;
}
return typeof next === 'function' ? next() : false;
}
function killRequest (req, res, next) {
logger.log('Checking: ' + req.headers.host);
if (req.headers.host && isValidHost(req.headers.host) && !badExtension.test(req.url)) {
return typeof next === 'function' ? next() : false;
}
logger.log(`[${process.pid} @ ${new Date().toUTCString()}][${req.socket.remoteAddress}] ${req.method} ${JSON.stringify(req.headers.host) || 'NOHOST'}${req.url}\t(killed)`);
let postdatalen = 0, postdata = [];
req.on('data', chunk => {
postdatalen += chunk.length;
if (postdatalen > maxPost) {
res.destroy();
}
postdata.push(chunk);
});
req.on('end', () => {
logger.log(`\n[${process.pid} @ ${new Date().toUTCString()}][${req.socket.remoteAddress}]\n### Headers ###: ${JSON.stringify(req.rawHeaders)}`);
if (postdata.length) {
logger.log('### DATA ###: ' + JSON.stringify(Buffer.concat(postdata).toString()));
}
logger.log('### END ###\n');
try {
res.writeHead(404, {
'Content-Type': 'text/html',
});
fs.createReadStream(__dirname + '/badreply.html').pipe(res);
} catch (err) {
logger.log(err);
}
});
return true;
}
function logRequest (req, res, next) {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}][${req.ip}] ${req.method} ${JSON.stringify(req.headers.host)}${req.url}\t(OK)`);
return next();
}
if (cluster.isMaster) { // master code
console.log('Spawning children...');
cluster.fork(); // only fork once, this just allows the server to keep itself alive
cluster.on('exit', (worker /*, code, signal */) => {
console.log(`[${process.pid} @ ${new Date().toUTCString()}] Child ${worker.process.pid} died!`);
cluster.fork(); // if server dies fork a new thread
});
} else { // child code
logger.log(`[${process.pid} @ ${new Date().toUTCString()}] Starting node HTTP Server (ARGV: ${JSON.stringify(process.argv)})`);
let httpPort = 80, httpsPort = 443;
process.argv.slice(2).forEach(arg => {
arg = arg.split(':');
let flag = arg.shift();
arg = arg.join(':');
switch (flag) {
case '--port':
httpPort = Math.max(80, arg | 0);
httpsPort = httpPort + 363;
break;
default:
logger.log('Unknown flag: ' + flag);
break;
}
});
logger.log(`Using ports: ${httpPort} and ${httpsPort}`);
process.on('exit', (code) => {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}] Exiting with code: ${code}\n`);
});
let msg404 = ["404 Not Found", "404 (That resource does not exist)", "404 (Check your URL)"];
// server setup
const server = express();
const staticOpts = { extensions: ['.html', '.htm', '.json'], maxAge: 600000 };
server.use(killRequest); // kill connection if host name is not specified
server.use(checkDomain); // redirects to www if no subdomain exists
server.use(logRequest); // logs incoming requests
server.use(compression());
server.use(scriptRouter);
server.use(express.static('html', staticOpts));
server.use(function (req, res) {
let msg = msg404[Math.floor(Math.random() * msg404.length)];
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(`<html><head><title>Not Found</title></head><body><h1>${msg}</h1></body></html>`);
});
server.use(function (error, req, res) {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end(`<html><head><title>Internal Server Error</title></head><body><h1>ERROR</h1></body></html>`);
});
let httpserver = https.createServer({
ca: fs.readFileSync(__dirname + '/server.ca-bundle'),
key: fs.readFileSync(__dirname + '/server.key'),
cert: fs.readFileSync(__dirname + '/server.crt')
}, server);
let wss = new WebSocket.Server({ server: httpserver });
wss.on('connection', (ws, req) => {
try {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}][${req.socket.remoteAddress}] ${req.method} ${JSON.stringify(req.headers.host)}${req.url}\t(websocket)`);
let q = url.parse(req.url, true);
let filepathbase = htmlDocs + decodeURI(q.pathname);
if (!/\.sss$/i.test(filepathbase)) {
filepathbase += ".sss";
}
let script = scripts.load(filepathbase);
if (script && typeof script.connect === 'function') {
ws.scriptPath = filepathbase;
if (script.connect(ws, wss, req)) {
return;
}
}
} catch (err) {
logger.log(err);
}
ws.terminate();
});
httpserver.listen(httpsPort);
// forward non-secure requests to https
http.createServer((req, res) => {
logger.log('Incoming request...');
if (!killRequest(req, res) && !checkDomain(req, res)) {
logger.log(`[${process.pid} @ ${new Date().toUTCString()}][${req.socket.remoteAddress}] ${req.method} ${JSON.stringify(req.headers.host)}${req.url}\t(forward to https)`);
let portlessHost = req.headers.host.split(':')[0];
res.writeHead(301, {Location: 'https://' + portlessHost + (httpsPort !== 443 ? ':' + httpsPort : '') + req.url});
res.end();
}
}).on("connection", (sock) => {
sock.setNoDelay(true);
}).listen(httpPort);
}