/
antinode.js
253 lines (228 loc) · 8.15 KB
/
antinode.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
var http = require('http'),
fs = require('fs'),
pathlib = require('path'),
uri = require('url'),
mime = require('./content-type'),
log = require('./log'),
package = JSON.parse(fs.readFileSync(__dirname+'/../package.json', 'utf8')),
sys = require('sys'),
Script = process.binding('evals').Script;
exports.default_settings = {
"timeout_milliseconds": 1000 * 30,
"hosts" : {},
"port" : 8080, /* a port that you don't need root to bind to */
"default_host" : {
"root" : process.cwd()
},
"log_level" : log.levels.DEBUG
};
exports.log_levels = log.levels;
var settings;
var server;
/* require() all the scripts at the start, so there's no
* waiting for in the middle of a request */
function load_hostspecific_handlers() {
for (var host in settings.hosts) {
var script = settings.hosts[host]['handler'];
if (script !== undefined && typeof script === 'string') {
/* remove filename extension */
var require_name = script.match(/(.*)\..*/)[1];
settings.hosts[host].handler = require(require_name);
}
}
}
/* call the module_init method if exists on each registered module.
allows modules to hook in to the server startup event. */
function handlers_init() {
for(var host in settings.hosts) {
if(settings.hosts[host].handler && settings.hosts[host].handler.handler_init) {
settings.hosts[host].handler.handler_init();
}
}
}
exports.start = function(custom_settings, callback) {
settings = custom_settings || {};
settings.__proto__ = exports.default_settings;
load_hostspecific_handlers();
log.level = settings.log_level;
log.info( "Starting server on port", settings.port);
server = http.createServer(function(req,resp) {
log.debug("Request from", req.connection.remoteAddress, "for", req.url);
log.debug(JSON.stringify(req.headers));
var url = uri.parse(req.url);
//if the parsed url doesn't have a pathname, default to '/'
var pathname = (url.pathname || '/');
var clean_pathname = pathname.
replace(/\.\.\//g,''). //disallow parent directory access
replace(/\%20/g,' '); //convert spaces
function select_vhost() {
if (req.headers.host) {
var hostname = req.headers.host.split(':')[0]; //remove port
return settings.hosts[hostname] || settings.default_host;
} else {
return settings.default_host;
}
}
var vhost = select_vhost(req.headers.host);
if (vhost.handler && vhost.handler.handle) {
var action = vhost.handler.handle(req,resp);
if(action && typeof action === 'function') {
if(vhost.handler.handler_environment){
action.apply(vhost.handler.handler_environment(req, resp))
}
else {
action(req, resp);
}
return;
}
}
var path = pathlib.join(vhost.root, clean_pathname);
if (path.match(/\.sjs$/)) {
execute_sjs(path, req, resp);
} else {
serve_static_file(path, req, resp);
}
});
server.listen(settings.port);
handlers_init();
server.addListener('listening', function() {
if (callback) callback();
});
server.addListener('connection', function(connection) {
connection.setTimeout(settings.timeout_milliseconds);
connection.addListener('timeout', function() {
log.debug("Connection from",connection.remoteAddress,"timed out. Closing it...");
connection.destroy();
});
});
};
exports.stop = function(callback) {
if (server) {
if (callback) server.addListener('close', callback);
server.close();
}
};
function serve_static_file(path, req, resp) {
function send_headers(httpstatus, length, content_type, modified_time) {
var headers = {
"Server": "Antinode/"+package.version+" Node.js/"+process.version,
"Date": (new Date()).toUTCString()
};
if (length) {
headers["Content-Length"] = length;
}
if (content_type) {
headers["Content-Type"] = content_type || "application/octet-stream";
}
if (modified_time) {
headers["Last-Modified"] = modified_time.toUTCString();
}
resp.writeHead(httpstatus, headers);
log.info(req.connection.remoteAddress,req.method,path,httpstatus,length);
}
fs.stat(path, function (err, stats) {
if (err) {
// ENOENT is normal on 'file not found'
if (err.errno != process.ENOENT) {
// any other error is abnormal - log it
log.error("fs.stat(",path,") failed: ", err);
}
return file_not_found();
}
if (stats.isDirectory()) {
return serve_static_file(pathlib.join(path, "index.html"), req, resp);
}
if (!stats.isFile()) {
return file_not_found();
} else {
var if_modified_since = req.headers['if-modified-since'];
if (if_modified_since) {
var req_date = new Date(if_modified_since);
if (stats.mtime <= req_date && req_date <= Date.now()) {
return not_modified();
}
else stream_file(path, stats);
} else if (req.method == 'HEAD') {
send_headers(200, stats.size, mime.mime_type(path), stats.mtime);
resp.end('');
} else {
return stream_file(path, stats);
}
}
});
function stream_file(file, stats) {
try {
var readStream = fs.createReadStream(file);
}
catch (err) {
log.debug("fs.createReadStream(",file,") error: ",sys.inspect(err,true));
return file_not_found();
}
send_headers(200, stats.size, mime.mime_type(file), stats.mtime);
sys.pump(readStream, resp, function() {
log.debug('pumped',file);
});
req.connection.addListener('timeout', function() {
/* dont destroy it when the fd's already closed */
if (readStream.readable) {
log.debug('timed out. destroying file read stream');
readStream.destroy();
}
});
readStream.addListener('fd', function(fd) {
log.debug("opened",path,"on fd",fd);
});
readStream.addListener('error', function (err) {
log.error('error reading',file,sys.inspect(err));
resp.end('');
});
resp.addListener('error', function (err) {
log.error('error writing',file,sys.inspect(err));
readStream.destroy();
});
}
function not_modified() {
// no need to send content length or type
log.debug("304 for resource ", path);
send_headers(304);
resp.end('');
}
function file_not_found() {
log.debug("404 opening path: '"+path+"'");
var body = "404: " + req.url + " not found.\n";
send_headers(404,body.length,"text/plain");
if (req.method != 'HEAD') {
resp.end(body, 'utf-8');
}
}
function server_error(message) {
log.error(message);
send_headers(500, message.length, "text/plain");
if (req.method !== 'HEAD') {
resp.end(message,'utf-8');
}
}
}
function execute_sjs(path, req, resp) {
fs.readFile(path, 'utf8', function(err, script) {
try {
if (err) throw err;
var sandbox = {
log: log,
require: require,
__filename: path,
__dirname: pathlib.dirname(path)
};
Script.runInNewContext(script, sandbox, path);
sandbox.handle(req, resp);
}
catch (e) {
resp.writeHead(500,{'Content-Type':'text/plain'});
resp.end("Error executing server script "+path+": "+e);
}
});
}
function close(fd) {
fs.close(fd);
log.debug("closed fd",fd);
}