node-http-server

Subversion Repositories:
Compare Path: Rev
With Path: Rev
?path1? @ 34  →  ?path2? @ 35
/src/cache.js
@@ -0,0 +1,149 @@
#!/usr/bin/env node
 
/*************************************************************************/
/* Copyright (C) 2017 Wizardry and Steamworks - License: GNU GPLv3 */
/*************************************************************************/
 
const fs = require('fs');
const stream = require('stream');
const util = require('util');
const tz = require('moment-timezone');
const forge = require('node-forge');
const EventEmitter = require('events').EventEmitter;
 
// Cache constructor.
function Cache(config, client, request, response) {
// Create events emitters for logging and data.
EventEmitter.call(this);
 
// Pass through objects needed for caching.
this.config = config;
this.client = client;
this.request = request;
this.response = response;
};
 
// Cache handling.
Cache.prototype.process = function(resource, input, type) {
EventEmitter.call(this);
const self = this;
 
fs.stat(resource, (error, stats) => {
var expires = 0;
Object.keys(self.config.site.cache).forEach((key) => {
self.config.site.cache[key].forEach((expire) => {
if (expire.test(resource)) {
expires = key;
}
});
});
 
switch (self.request.httpVersion) {
case '1.1': // HTTP 1.1
self.response.setHeader('Cache-Control',
"max-age=" + expires + ", public"
);
const sha1 = forge.md.sha1.create();
const data = new stream.Readable({
objectMode: true,
read(size) {}
});
input
.on('data', (chunk) => {
sha1.update(chunk);
data.push(chunk);
})
.on('end', () => {
const etag = sha1.digest().toHex();
 
// Set the ETag for the resource.
self.response.setHeader('ETag', etag);
 
const ifNoneMatch = Object
.getOwnPropertyNames(self.request.headers)
.filter((header) => header.toUpperCase() ===
'If-None-Match'.toUpperCase());
 
const ifModifiedSince = Object
.getOwnPropertyNames(self.request.headers)
.filter((header) => header.toUpperCase() ===
'If-Modified-Since'.toUpperCase());
 
if ((ifNoneMatch.length !== 0 &&
self.request.headers[ifNoneMatch].toUpperCase() === etag.toUpperCase()) ||
(ifModifiedSince.length !== 0 &&
tz(self.request.headers[ifModifiedSince]).tz('UTC') < tz(stat.mtime).tz('UTC'))) {
// Send a cache hit response.
self.emit('log', {
message: 'Client: ' +
self.client.address + ':' +
self.client.port +
' cached resource: ' +
resource,
severity: 'info'
});
self.emit('data', {
status: 304,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: type
});
return;
}
 
// Send the resource.
self.emit('log', {
message: 'Client: ' +
self.client.address + ':' +
self.client.port +
' sent resource: ' +
resource,
severity: 'info'
});
data.push(null);
self.emit('data', {
status: 200,
data: data,
type: type
});
});
 
return;
default:
self.response.setHeader('Last-Modified',
tz(stats.mtime)
.tz('UTC')
.format("ddd, DD MMM YYYY HH:mm:ss z")
);
self.response.setHeader('Expires',
tz()
.tz('UTC')
.add(expires, 'seconds')
.format("ddd, DD MMM YYYY HH:mm:ss z")
);
// Send the resource.
self.emit('log', {
message: 'Client: ' +
self.client.address + ':' +
self.client.port +
' sent resource: ' +
resource,
severity: 'info'
});
self.emit('data', {
status: 200,
data: input,
type: type
});
break;
}
});
 
return this;
};
 
util.inherits(Cache, EventEmitter);
module.exports = Cache;
/src/certs.js
@@ -5,7 +5,7 @@
/*************************************************************************/
 
const forge = require('node-forge');
const moment = require('moment');
const tz = require('moment-timezone');
 
module.exports = {
// Generate certificates on the fly using incremental serials.
@@ -20,11 +20,11 @@
const cert = forge
.pki
.createCertificate();
cert.serialNumber = moment().format('x');
cert.serialNumber = tz().tz('UTC').format('x');
cert.publicKey = keys.publicKey;
cert
.validity
.notBefore = moment().toDate();
.notBefore = tz().tz('UTC').toDate();
cert
.validity
.notAfter
/src/handler.js
@@ -13,386 +13,368 @@
const util = require('util');
const EventEmitter = require('events').EventEmitter;
 
// Checks whether userPath is a child of rootPath.
function isRooted(userPath, rootPath, separator, callback) {
userPath = userPath.split(separator).filter(Boolean);
rootPath = rootPath.split(separator).filter(Boolean);
callback(userPath.length >= rootPath.length &&
rootPath.every((e, i) => e === userPath[i]));
}
// Local imports.
const Cache = require(
path
.resolve(
path.dirname(require.main.filename),
'src',
'cache'
)
);
const was = require(
path
.resolve(
path.dirname(require.main.filename),
'src',
'was'
)
);
 
// Serves files.
function files(self, config, file, client) {
// Check if the file is accessible.
fs.access(file, fs.constants.R_OK, (error) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' requesting inaccessible path: ' +
file,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' sent file: ' +
file,
severity: 'info'
});
self.emit('data', {
status: 200,
data: fs
.createReadStream(file),
type: mime
.lookup(file)
});
});
function files(self, config, file, client, cache) {
// Check if the file is accessible.
fs.access(file, fs.constants.R_OK, (error) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' requesting inaccessible path: ' +
file,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
cache.process(file, fs.createReadStream(file), mime.lookup(file))
.on('data', (result) => self.emit('data', result))
.on('log', (data) => self.emit('log', data));
});
}
 
// Serves a directory listing or the document index in case it exists.
function index(self, config, directory, href, client) {
const root = path.resolve(directory, config.site.index);
fs.stat(root, (error, stats) => {
if (error) {
if (config.site.indexing
.some((directory) =>
directory.toUpperCase() === href.toUpperCase())) {
fs.readdir(directory, (error, paths) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' could not access directory: ' +
directory,
severity: 'warning'
});
self.emit('data', {
status: 500,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' accessed directory listing: ' +
directory,
severity: 'info'
});
self.emit('data', {
status: 200,
data: new stream.Readable({
read(size) {
this.push(JSON.stringify(paths));
this.push(null);
}
}),
type: 'application/json'
});
});
return;
}
// Could not access directory index file and directory listing not allowed.
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' no index file found and accessing forbiden index: ' +
href,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
function index(self, config, directory, href, client, cache) {
const root = path.resolve(directory, config.site.index);
fs.stat(root, (error, stats) => {
if (error) {
if (config.site.indexing
.some((directory) =>
directory.toUpperCase() === href.toUpperCase())) {
fs.readdir(directory, (error, paths) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' could not access directory: ' +
directory,
severity: 'warning'
});
self.emit('data', {
status: 500,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
cache.process(directory, new stream.Readable({
read(size) {
this.push(JSON.stringify(paths));
this.push(null);
}
}), 'application/json')
.on('data', (result) => self.emit('data', result))
.on('log', (data) => self.emit('log', data));
});
return;
}
// Could not access directory index file and directory listing not allowed.
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' no index file found and accessing forbiden index: ' +
href,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
// Serve the document index.
fs.access(root, fs.constants.R_OK, (error) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' unable to access path: ' +
directory,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' sent file: ' +
root,
severity: 'info'
});
self.emit('data', {
status: 200,
data: fs.createReadStream(root),
type: mime.lookup(root)
});
});
});
// Serve the document index.
fs.access(root, fs.constants.R_OK, (error) => {
if (error) {
self.emit('log', {
message: 'Client: ' +
client.address + ':' +
client.port +
' unable to access path: ' +
directory,
severity: 'warning'
});
self.emit('data', {
status: 403,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
cache.process(root, fs.createReadStream(root), mime.lookup(root))
.on('data', (result) => self.emit('data', result))
.on('log', (data) => self.emit('log', data));
});
});
}
 
// Determines whether the requested filesystem request path is a directory or a file.
function serve(self, config, local, href, address) {
fs.stat(local, (error, stats) => {
// Document does not exist.
if (error) {
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' accessing non-existent document: ' +
local,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
function serve(self, config, local, href, address, cache) {
fs.stat(local, (error, stats) => {
// Document does not exist.
if (error) {
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' accessing non-existent document: ' +
local,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
if (stats.isDirectory()) {
// Directory is requested so provide directory indexes.
index(self, config, local, href, address);
return;
}
if (stats.isFile()) {
const file = path.parse(local).base;
if (stats.isDirectory()) {
// Directory is requested so provide directory indexes.
index(self, config, local, href, address, cache);
return;
}
if (stats.isFile()) {
const file = path.parse(local).base;
 
// If the file matches the reject list or is not in the accept list,
// then there is no file to serve.
if (config.site.reject.some((expression) => expression.test(file)) ||
!config.site.accept.some((expression) => expression.test(file))) {
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' requested disallowed file: ' +
file,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
// If the file matches the reject list or is not in the accept list,
// then there is no file to serve.
if (config.site.reject.some((expression) => expression.test(file)) ||
!config.site.accept.some((expression) => expression.test(file))) {
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' requested disallowed file: ' +
file,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
// A file was requested so provide the file.
files(self, config, local, address);
}
});
// A file was requested so provide the file.
files(self, config, local, address, cache);
}
});
}
 
// Constructor.
function Handler() {
// Create events emitters for logging and data.
EventEmitter.call(this);
// Create events emitters for logging and data.
EventEmitter.call(this);
};
 
// Process a request.
Handler.prototype.process = function(config, request, response, root) {
EventEmitter.call(this);
var self = this;
EventEmitter.call(this);
var self = this;
 
// Get client details.
const address = request.socket.address();
// Get requested URL.
const requestURL = url.parse(
request.url, true
);
// Get client details.
const address = request.socket.address();
// Get requested URL.
const requestURL = url.parse(
request.url, true
);
 
// Perform URL re-writes.
Object.keys(config.site.rewrite).forEach((key, index) => {
if (config.site.rewrite[key].test(requestURL.path)) {
const originalPath = requestURL.path;
requestURL.path = requestURL
.path
.replace(
config.site.rewrite[key], key
);
requestURL.pathname = url.parse(
requestURL
.pathname
.replace(
config.site.rewrite[key], key
),
true
)
.pathname;
self.emit('log', {
message: 'Rewrite path: ' +
originalPath +
' to: ' +
requestURL.path,
severity: 'info'
});
}
});
// Perform URL re-writes.
Object.keys(config.site.rewrite).forEach((key, index) => {
if (config.site.rewrite[key].test(requestURL.path)) {
const originalPath = requestURL.path;
requestURL.path = requestURL
.path
.replace(
config.site.rewrite[key], key
);
requestURL.pathname = url.parse(
requestURL
.pathname
.replace(
config.site.rewrite[key], key
),
true
)
.pathname;
self.emit('log', {
message: 'Rewrite path: ' +
originalPath +
' to: ' +
requestURL.path,
severity: 'info'
});
}
});
 
const trimmedPath = requestURL
.pathname
.split('/')
.filter(Boolean)
.join('/');
const requestPath = trimmedPath === '/' ?
path.join(root, trimmedPath) :
path.resolve(root, trimmedPath);
const trimmedPath = requestURL
.pathname
.split('/')
.filter(Boolean)
.join('/');
const requestPath = trimmedPath === '/' ?
path.join(root, trimmedPath) :
path.resolve(root, trimmedPath);
 
fs.realpath(requestPath, (error, resolvedPath) => {
// If the path does not exist, then return early.
if (error) {
self.emit('log', {
message: 'Unknown path requested: ' +
address.address + ':' +
address.port +
' requesting: ' +
requestURL.pathname,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
// Check for path traversals early on and bail if the requested path does not
// lie within the specified document root.
isRooted(resolvedPath, root, path.sep, (rooted) => {
if (!rooted) {
self.emit('log', {
message: 'Attempted path traversal: ' +
address.address + ':' +
address.port +
' requesting: ' +
requestURL.pathname,
severity: 'warning'
});
self.emit('done', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
fs.realpath(requestPath, (error, resolvedPath) => {
// If the path does not exist, then return early.
if (error) {
self.emit('log', {
message: 'Unknown path requested: ' +
address.address + ':' +
address.port +
' requesting: ' +
requestURL.pathname,
severity: 'warning'
});
self.emit('data', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
// If authentication is required for this path then perform authentication.
if (config.auth.locations.some(
(authPath) => authPath.toUpperCase() === requestURL.pathname.toUpperCase())) {
// Create digest authentication.
const authentication = auth.digest({
realm: config.auth.realm,
file: path.resolve(
path.dirname(require.main.filename),
config.auth.digest
)
});
// Requested location requires authentication.
authentication.check(request, response, (request, response) => {
self.emit('log', {
message: 'Authenticated client: ' +
address.address + ':' +
address.port +
' accessing: ' +
requestURL.pathname,
severity: 'info'
});
process.nextTick(() =>
serve(self,
config,
requestPath,
requestURL.pathname,
address
)
);
});
return;
}
// Check for path traversals early on and bail if the requested path does not
// lie within the specified document root.
was.isRooted(resolvedPath, root, path.sep, (rooted) => {
if (!rooted) {
self.emit('log', {
message: 'Attempted path traversal: ' +
address.address + ':' +
address.port +
' requesting: ' +
requestURL.pathname,
severity: 'warning'
});
self.emit('done', {
status: 404,
data: new stream.Readable({
read(size) {
this.push(null);
}
}),
type: 'text/plain'
});
return;
}
 
// If no authentication is required then serve the request.
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' accessing: ' +
requestURL.pathname,
severity: 'info'
});
process.nextTick(() =>
serve(self,
config,
requestPath,
requestURL.pathname,
address
)
);
});
});
return this;
// If authentication is required for this path then perform authentication.
if (config.auth.locations.some(
(authPath) => authPath.toUpperCase() === requestURL.pathname.toUpperCase())) {
// Create digest authentication.
const authentication = auth.digest({
realm: config.auth.realm,
file: path.resolve(
path.dirname(require.main.filename),
config.auth.digest
)
});
// Requested location requires authentication.
authentication.check(request, response, (request, response) => {
self.emit('log', {
message: 'Authenticated client: ' +
address.address + ':' +
address.port +
' accessing: ' +
requestURL.pathname,
severity: 'info'
});
process.nextTick(() =>
serve(self,
config,
requestPath,
requestURL.pathname,
address,
new Cache(config, address, request, response)
)
);
});
return;
}
 
// If no authentication is required then serve the request.
self.emit('log', {
message: 'Client: ' +
address.address + ':' +
address.port +
' accessing: ' +
requestURL.pathname,
severity: 'info'
});
process.nextTick(() =>
serve(self,
config,
requestPath,
requestURL.pathname,
address,
new Cache(config, address, request, response)
)
);
});
});
 
return this;
};
 
util.inherits(Handler, EventEmitter);
util.inherits(Cache, EventEmitter);
module.exports = Handler;
/src/was.js
@@ -0,0 +1,17 @@
#!/usr/bin/env node
 
/*************************************************************************/
/* Copyright (C) 2017 Wizardry and Steamworks - License: GNU GPLv3 */
/*************************************************************************/
 
// Checks whether userPath is a child of rootPath.
var was = {
isRooted: function(userPath, rootPath, separator, callback) {
userPath = userPath.split(separator).filter(Boolean);
rootPath = rootPath.split(separator).filter(Boolean);
callback(userPath.length >= rootPath.length &&
rootPath.every((e, i) => e === userPath[i]));
}
}
 
module.exports = was;