forked from jfhbrook/node-ecstatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecstatic.js
executable file
·298 lines (257 loc) · 8.83 KB
/
ecstatic.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
#! /usr/bin/env node
var path = require('path'),
fs = require('fs'),
url = require('url'),
mime = require('mime'),
urlJoin = require('url-join'),
showDir = require('./ecstatic/showdir'),
version = JSON.parse(
fs.readFileSync(__dirname + '/../package.json').toString()
).version,
status = require('./ecstatic/status-handlers'),
etag = require('./ecstatic/etag'),
optsParser = require('./ecstatic/opts');
var ecstatic = module.exports = function (dir, options) {
if (typeof dir !== 'string') {
options = dir;
dir = options.root;
}
var root = path.join(path.resolve(dir), '/'),
opts = optsParser(options),
cache = opts.cache,
autoIndex = opts.autoIndex,
baseDir = opts.baseDir,
defaultExt = opts.defaultExt,
handleError = opts.handleError,
serverHeader = opts.serverHeader;
opts.root = dir;
if (defaultExt && /^\./.test(defaultExt)) defaultExt = defaultExt.replace(/^\./, '');
// Support hashes and .types files in mimeTypes @since 0.8
if (opts.mimeTypes) {
if (typeof opts.mimeTypes === 'string') {
mime.load(opts.mimeTypes); // will throw if path is wrong as intended
} else if (typeof opts.mimeTypes === 'object') {
mime.define(opts.mimeTypes);
}
}
return function middleware (req, res, next) {
// Strip any null bytes from the url
while(req.url.indexOf('%00') !== -1) {
req.url = req.url.replace(/\%00/g, '');
}
// Figure out the path for the file from the given url
var parsed = url.parse(req.url);
try {
decodeURIComponent(req.url); // check validity of url
var pathname = decodePathname(parsed.pathname);
}
catch (err) {
return status[400](res, next, { error: err });
}
var file = path.normalize(
path.join(root,
path.relative(
path.join('/', baseDir),
pathname
)
)
),
gzipped = file + '.gz';
if(serverHeader !== false) {
// Set common headers.
res.setHeader('server', 'ecstatic-'+version);
}
// TODO: This check is broken, which causes the 403 on the
// expected 404.
if (file.slice(0, root.length) !== root) {
return status[403](res, next);
}
if (req.method && (req.method !== 'GET' && req.method !== 'HEAD' )) {
return status[405](res, next);
}
function statFile() {
fs.stat(file, function (err, stat) {
if (err && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
if (req.statusCode == 404) {
// This means we're already trying ./404.html and can not find it.
// So send plain text response with 404 status code
status[404](res, next);
}
else if (!path.extname(parsed.pathname).length && defaultExt) {
// If there is no file extension in the path and we have a default
// extension try filename and default extension combination before rendering 404.html.
middleware({
url: parsed.pathname + '.' + defaultExt + ((parsed.search)? parsed.search:'')
}, res, next);
}
else {
// Try to serve default ./404.html
middleware({
url: (handleError ? ('/' + path.join(baseDir, '404.' + defaultExt)) : req.url),
statusCode: 404
}, res, next);
}
}
else if (err) {
status[500](res, next, { error: err });
}
else if (stat.isDirectory()) {
// 302 to / if necessary
if (!parsed.pathname.match(/\/$/)) {
res.statusCode = 302;
res.setHeader('location', parsed.pathname + '/' +
(parsed.query? ('?' + parsed.query):'')
);
return res.end();
}
if (autoIndex) {
return middleware({
url: urlJoin(encodeURIComponent(pathname), '/index.' + defaultExt)
}, res, function (err) {
if (err) {
return status[500](res, next, { error: err });
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
return status[403](res, next);
});
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
status[404](res, next);
}
else {
serve(stat);
}
});
}
// Look for a gzipped file if this is turned on
if (opts.gzip && shouldCompress(req)) {
fs.stat(gzipped, function (err, stat) {
if (!err && stat.isFile()) {
file = gzipped;
return serve(stat);
} else {
statFile();
}
});
} else {
statFile();
}
function serve(stat) {
// Do a MIME lookup, fall back to octet-stream and handle gzip
// special case.
var defaultType = opts.contentType || 'application/octet-stream',
contentType = mime.lookup(file, defaultType),
charSet;
if (contentType) {
charSet = mime.charsets.lookup(contentType, 'utf-8');
if (charSet) {
contentType += '; charset=' + charSet;
}
}
if (path.extname(file) === '.gz') {
res.setHeader('Content-Encoding', 'gzip');
// strip gz ending and lookup mime type
contentType = mime.lookup(path.basename(file, ".gz"), defaultType);
}
var range = (req.headers && req.headers['range']);
if (range) {
var total = stat.size;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = Math.min(total-1, partialend ? parseInt(partialend, 10) : total-1);
var chunksize = (end-start)+1;
if (start > end || isNaN(start) || isNaN(end)) {
return status['416'](res, next);
}
var fstream = fs.createReadStream(file, {start: start, end: end});
fstream.on('error', function (err) {
status['500'](res, next, { error: err });
});
res.on('close', function () {
fstream.destroy();
});
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType
});
fstream.pipe(res);
return;
}
// TODO: Helper for this, with default headers.
res.setHeader('etag', etag(stat));
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);
// Return a 304 if necessary
if ( req.headers
&& (
(req.headers['if-none-match'] === etag(stat))
|| (new Date(Date.parse(req.headers['if-modified-since'])) >= stat.mtime)
)
) {
return status[304](res, next);
}
res.setHeader('content-length', stat.size);
res.setHeader('content-type', contentType);
// set the response statusCode if we have a request statusCode.
// This only can happen if we have a 404 with some kind of 404.html
// In all other cases where we have a file we serve the 200
res.statusCode = req.statusCode || 200;
if (req.method === "HEAD") {
return res.end();
}
var stream = fs.createReadStream(file);
stream.pipe(res);
stream.on('error', function (err) {
status['500'](res, next, { error: err });
});
}
};
};
ecstatic.version = version;
ecstatic.showDir = showDir;
// Check to see if we should try to compress a file with gzip.
function shouldCompress(req) {
var headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(",")
.some(function (el) {
return ['*','compress', 'gzip', 'deflate'].indexOf(el) != -1;
})
;
}
// See: https://github.com/jesusabdullah/node-ecstatic/issues/109
function decodePathname(pathname) {
var pieces = pathname.replace(/\\/g,"/").split('/');
return pieces.map(function (piece) {
piece = decodeURIComponent(piece);
if (process.platform === 'win32' && /\\/.test(piece)) {
throw new Error('Invalid forward slash character');
}
return piece;
}).join('/');
}
if (!module.parent) {
var http = require('http'),
opts = require('minimist')(process.argv.slice(2)),
port = opts.port || opts.p || 8000,
dir = opts.root || opts._[0] || process.cwd();
if (opts.help || opts.h) {
var u = console.error;
u('usage: ecstatic [dir] {options} --port PORT');
u('see https://npm.im/ecstatic for more docs');
return;
}
http.createServer(ecstatic(dir, opts))
.listen(port, function () {
console.log('ecstatic serving ' + dir + ' at http://0.0.0.0:' + port);
});
}