/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/handler.js |
@@ -13,16 +13,26 @@ |
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) { |
function files(self, config, file, client, cache) { |
// Check if the file is accessible. |
fs.access(file, fs.constants.R_OK, (error) => { |
if (error) { |
@@ -45,26 +55,15 @@ |
}); |
return; |
} |
self.emit('log', { |
message: 'Client: ' + |
client.address + ':' + |
client.port + |
' sent file: ' + |
file, |
severity: 'info' |
|
cache.process(file, fs.createReadStream(file), mime.lookup(file)) |
.on('data', (result) => self.emit('data', result)) |
.on('log', (data) => self.emit('log', data)); |
}); |
self.emit('data', { |
status: 200, |
data: fs |
.createReadStream(file), |
type: mime |
.lookup(file) |
}); |
}); |
} |
|
// Serves a directory listing or the document index in case it exists. |
function index(self, config, directory, href, client) { |
function index(self, config, directory, href, client, cache) { |
const root = path.resolve(directory, config.site.index); |
fs.stat(root, (error, stats) => { |
if (error) { |
@@ -92,25 +91,15 @@ |
}); |
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({ |
cache.process(directory, new stream.Readable({ |
read(size) { |
this.push(JSON.stringify(paths)); |
this.push(null); |
} |
}), |
type: 'application/json' |
}), '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. |
@@ -156,25 +145,15 @@ |
}); |
return; |
} |
self.emit('log', { |
message: 'Client: ' + |
client.address + ':' + |
client.port + |
' sent file: ' + |
root, |
severity: 'info' |
cache.process(root, fs.createReadStream(root), mime.lookup(root)) |
.on('data', (result) => self.emit('data', result)) |
.on('log', (data) => self.emit('log', data)); |
}); |
self.emit('data', { |
status: 200, |
data: fs.createReadStream(root), |
type: mime.lookup(root) |
}); |
}); |
}); |
} |
|
// Determines whether the requested filesystem request path is a directory or a file. |
function serve(self, config, local, href, address) { |
function serve(self, config, local, href, address, cache) { |
fs.stat(local, (error, stats) => { |
// Document does not exist. |
if (error) { |
@@ -200,7 +179,7 @@ |
|
if (stats.isDirectory()) { |
// Directory is requested so provide directory indexes. |
index(self, config, local, href, address); |
index(self, config, local, href, address, cache); |
return; |
} |
if (stats.isFile()) { |
@@ -231,7 +210,7 @@ |
} |
|
// A file was requested so provide the file. |
files(self, config, local, address); |
files(self, config, local, address, cache); |
} |
}); |
} |
@@ -316,7 +295,7 @@ |
|
// 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) => { |
was.isRooted(resolvedPath, root, path.sep, (rooted) => { |
if (!rooted) { |
self.emit('log', { |
message: 'Attempted path traversal: ' + |
@@ -364,7 +343,8 @@ |
config, |
requestPath, |
requestURL.pathname, |
address |
address, |
new Cache(config, address, request, response) |
) |
); |
}); |
@@ -385,7 +365,8 @@ |
config, |
requestPath, |
requestURL.pathname, |
address |
address, |
new Cache(config, address, request, response) |
) |
); |
}); |
@@ -395,4 +376,5 @@ |
}; |
|
util.inherits(Handler, EventEmitter); |
util.inherits(Cache, EventEmitter); |
module.exports = Handler; |