-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathst.js
671 lines (583 loc) · 16.6 KB
/
st.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
const mime = require('mime')
const path = require('path')
const url = require('url')
let fs
try {
fs = require('graceful-fs')
} catch (e) {
fs = require('fs')
}
const zlib = require('zlib')
const Neg = require('negotiator')
const http = require('http')
const AC = require('async-cache')
const FD = require('fd')
const bl = require('bl')
const { STATUS_CODES } = http
const defaultCacheOptions = {
fd: {
max: 1000,
maxAge: 1000 * 60 * 60
},
stat: {
max: 5000,
maxAge: 1000 * 60
},
content: {
max: 1024 * 1024 * 64,
length: (n) => n.length,
maxAge: 1000 * 60 * 10
},
index: {
max: 1024 * 8,
length: (n) => n.length,
maxAge: 1000 * 60 * 10
},
readdir: {
max: 1000,
length: (n) => n.length,
maxAge: 1000 * 60 * 10
}
}
// lru-cache doesn't like when max=0, so we just pretend
// everything is really big. kind of a kludge, but easiest way
// to get it done
const none = {
max: 1,
length: () => Infinity
}
const noCaching = {
fd: none,
stat: none,
index: none,
readdir: none,
content: none
}
function st (opt) {
let p, u
if (typeof opt === 'string') {
p = opt
opt = arguments[1]
if (typeof opt === 'string') {
u = opt
opt = arguments[2]
}
}
if (!opt) {
opt = {}
} else {
opt = Object.assign({}, opt)
}
if (!p) {
p = opt.path
}
if (typeof p !== 'string') {
throw new Error('no path specified')
}
p = path.resolve(p)
if (!u) {
u = opt.url
}
if (!u) {
u = ''
}
if (u.charAt(0) !== '/') {
u = '/' + u
}
opt.url = u
opt.path = p
const m = new Mount(opt)
const fn = m.serve.bind(m)
fn._this = m
return fn
}
class Mount {
constructor (opt) {
if (!opt) {
throw new Error('no options provided')
}
if (typeof opt !== 'object') {
throw new Error('invalid options')
}
if (!(this instanceof Mount)) {
return new Mount(opt)
}
this.opt = opt
this.url = opt.url
this.path = opt.path
this._index = opt.index === false
? false
: typeof opt.index === 'string'
? opt.index
: true
this.fdman = FD()
// cache basically everything
const c = this.getCacheOptions(opt)
this.cache = {
fd: AC(c.fd),
stat: AC(c.stat),
index: AC(c.index),
readdir: AC(c.readdir),
content: AC(c.content)
}
this._cacheControl =
c.content.maxAge === false
? undefined
: typeof c.content.cacheControl === 'string'
? c.content.cacheControl
: opt.cache === false
? 'no-cache'
: 'public, max-age=' + (c.content.maxAge / 1000)
}
getCacheOptions (opt) {
let o = opt.cache
const set = (key) => {
return o[key] === false
? Object.assign({}, none)
: Object.assign(Object.assign({}, d[key]), o[key])
}
if (o === false) {
o = noCaching
} else if (!o) {
o = {}
}
const d = defaultCacheOptions
// should really only ever set max and maxAge here.
// load and fd disposal is important to control.
const c = {
fd: set('fd'),
stat: set('stat'),
index: set('index'),
readdir: set('readdir'),
content: set('content')
}
c.fd.dispose = this.fdman.close.bind(this.fdman)
c.fd.load = this.fdman.open.bind(this.fdman)
c.stat.load = this._loadStat.bind(this)
c.index.load = this._loadIndex.bind(this)
c.readdir.load = this._loadReaddir.bind(this)
c.content.load = this._loadContent.bind(this)
return c
}
// get the path component from a URI
getUriPath (u) {
let p = url.parse(u).pathname // eslint-disable-line
// Encoded dots are dots
p = p.replace(/%2e/ig, '.')
// encoded slashes are /
p = p.replace(/%2f|%5c/ig, '/')
// back slashes are slashes
p = p.replace(/[/\\]/g, '/')
// Make sure it starts with a slash
p = p.replace(/^\//, '/')
if ((/[/\\]\.\.([/\\]|$)/).test(p)) {
// traversal urls not ever even slightly allowed. clearly shenanigans
// send a 403 on that noise, do not pass go, do not collect $200
return 403
}
u = path.normalize(p).replace(/\\/g, '/')
if (u.indexOf(this.url) !== 0) {
return false
}
try {
u = decodeURIComponent(u)
} catch (e) {
// if decodeURIComponent failed, we weren't given a valid URL to begin with.
return false
}
// /a/b/c mounted on /path/to/z/d/x
// /a/b/c/d --> /path/to/z/d/x/d
u = u.substr(this.url.length)
if (u.charAt(0) !== '/') {
u = '/' + u
}
return u
}
// get a path from a url
getPath (u) {
// trailing slash removal to fix Node.js v23 bug
// https://github.com/nodejs/node/pull/55527
// can be removed when this is resolved and released
return path.join(this.path, u.replace(/\/+$/, ''))
}
// get a url from a path
getUrl (p) {
p = path.resolve(p)
if (p.indexOf(this.path) !== 0) {
return false
}
p = path.join('/', p.substr(this.path.length))
const u = path.join(this.url, p).replace(/\\/g, '/')
return u
}
serve (req, res, next) {
if (req.method !== 'HEAD' && req.method !== 'GET') {
if (typeof next === 'function') {
next()
}
return false
}
// querystrings are of no concern to us
if (!req.sturl) {
req.sturl = this.getUriPath(req.url)
}
// don't allow dot-urls by default, unless explicitly allowed.
// If we got a 403, then it's explicitly forbidden.
if (req.sturl === 403 || (!this.opt.dot && (/(^|\/)\./).test(req.sturl))) {
res.statusCode = 403
res.end(STATUS_CODES[res.statusCode])
return true
}
// Falsey here means we got some kind of invalid path.
// Probably urlencoding we couldn't understand, or some
// other "not compatible with st, but maybe ok" thing.
if (typeof req.sturl !== 'string' || req.sturl === '') {
if (typeof next === 'function') {
next()
}
return false
}
const p = this.getPath(req.sturl)
// now we have a path. check for the fd.
this.cache.fd.get(p, (er, fd) => {
// inability to open is some kind of error, probably 404
// if we're in passthrough, AND got a next function, we can
// fall through to that. otherwise, we already returned true,
// send an error.
if (er) {
if (this.opt.passthrough === true && er.code === 'ENOENT' && next) {
return next()
}
return this.error(er, res)
}
// we may be about to use this, so don't let it be closed by cache purge
this.fdman.checkout(p, fd)
// a safe end() function that can be called multiple times but
// only perform a single checkin
const end = this.fdman.checkinfn(p, fd)
this.cache.stat.get(fd + ':' + p, (er, stat) => {
if (er) {
if (next && this.opt.passthrough === true && this._index === false) {
return next()
}
end()
return this.error(er, res)
}
const isDirectory = stat.isDirectory()
if (isDirectory) {
end() // we won't need this fd for a directory in any case
if (next && this.opt.passthrough === true && this._index === false) {
// this is done before if-modified-since and if-non-match checks so
// cached modified and etag values won't return 304's if we've since
// switched to !index. See Issue #51.
return next()
}
}
let ims = req.headers['if-modified-since']
if (ims) {
ims = new Date(ims).getTime()
}
if (ims && ims >= stat.mtime.getTime()) {
res.statusCode = 304
res.end()
return end()
}
const etag = getEtag(stat)
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304
res.end()
return end()
}
// only set headers once we're sure we'll be serving this request
if (!res.getHeader('cache-control') && this._cacheControl) {
res.setHeader('cache-control', this._cacheControl)
}
res.setHeader('last-modified', stat.mtime.toUTCString())
res.setHeader('etag', etag)
if (this.opt.cors) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Range')
}
return isDirectory
? this.index(p, req, res)
: this.file(p, fd, stat, etag, req, res, end)
})
})
return true
}
error (er, res) {
res.statusCode = typeof er === 'number'
? er
: er.code === 'ENOENT' || er.code === 'EISDIR'
? 404
: er.code === 'EPERM' || er.code === 'EACCES'
? 403
: 500
if (typeof res.error === 'function') {
// pattern of express and ErrorPage
return res.error(res.statusCode, er)
}
res.setHeader('content-type', 'text/plain')
res.end(STATUS_CODES[res.statusCode] + '\n')
}
index (p, req, res) {
if (this._index === true) {
return this.autoindex(p, req, res)
}
if (typeof this._index === 'string') {
if (!/\/$/.test(req.sturl)) {
req.sturl += '/'
}
req.sturl += this._index
return this.serve(req, res)
}
return this.error(404, res)
}
autoindex (p, req, res) {
if (!/\/$/.exec(req.sturl)) {
res.statusCode = 301
res.setHeader('location', req.sturl + '/')
res.end('Moved: ' + req.sturl + '/')
return
}
this.cache.index.get(p, (er, html) => {
if (er) {
return this.error(er, res)
}
res.statusCode = 200
res.setHeader('content-type', 'text/html')
res.setHeader('content-length', html.length)
res.end(html)
})
}
file (p, fd, stat, etag, req, res, end) {
const key = stat.size + ':' + etag
const mt = mime.getType(path.extname(p))
if (mt !== 'application/octet-stream') {
res.setHeader('content-type', mt)
}
// only use the content cache if it will actually fit there.
if (this.cache.content.has(key)) {
end()
this.cachedFile(p, stat, etag, req, res)
} else {
this.streamFile(p, fd, stat, etag, req, res, end)
}
}
cachedFile (p, stat, etag, req, res) {
const key = stat.size + ':' + etag
const gz = this.opt.gzip !== false && getGz(p, req)
this.cache.content.get(key, (er, content) => {
if (er) {
return this.error(er, res)
}
res.statusCode = 200
if (this.opt.cachedHeader) {
res.setHeader('x-from-cache', 'true')
}
if (gz && content.gz) {
res.setHeader('content-encoding', 'gzip')
res.setHeader('content-length', content.gz.length)
res.end(content.gz)
} else {
res.setHeader('content-length', content.length)
res.end(content)
}
})
}
streamFile (p, fd, stat, etag, req, res, end) {
const streamOpt = { fd: fd, start: 0, end: stat.size }
let stream = fs.createReadStream(p, streamOpt)
stream.destroy = () => {}
// gzip only if not explicitly turned off or client doesn't accept it
const gzOpt = this.opt.gzip !== false
const gz = gzOpt && getGz(p, req)
const cachable = this.cache.content._cache.max > stat.size
let gzstr
// need a gzipped version for the cache, so do it regardless of what the client wants
if (gz || (gzOpt && cachable)) {
gzstr = zlib.Gzip()
}
// too late to effectively handle any errors.
// just kill the connection if that happens.
stream.on('error', (e) => {
console.error('Error serving %s fd=%d\n%s', p, fd, e.stack || e.message)
res.socket.destroy()
end()
})
if (res.filter) {
stream = stream.pipe(res.filter)
}
res.statusCode = 200
if (gz) {
// we don't know how long it'll be, since it will be compressed.
res.setHeader('content-encoding', 'gzip')
stream.pipe(gzstr).pipe(res)
} else {
if (!res.filter) {
res.setHeader('content-length', stat.size)
}
stream.pipe(res)
if (gzstr) {
stream.pipe(gzstr)
} // for cache
}
stream.on('end', () => process.nextTick(end))
if (cachable) {
// collect it, and put it in the cache
let calls = 0
// called by bl() for both the raw stream and gzipped stream if we're
// caching gzipped data
const collectEnd = () => {
if (++calls === (gzOpt ? 2 : 1)) {
const content = bufs.slice()
content.gz = gzbufs && gzbufs.slice()
this.cache.content.set(key, content)
}
}
const key = stat.size + ':' + etag
const bufs = bl(collectEnd)
let gzbufs
stream.pipe(bufs)
if (gzstr) {
gzbufs = bl(collectEnd)
gzstr.pipe(gzbufs)
}
}
}
// cache-fillers
_loadIndex (p, cb) {
// truncate off the first bits
const url = p.substr(this.path.length).replace(/\\/g, '/')
const t = url
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
let str =
'<!doctype html>' +
'<html>' +
'<head><title>Index of ' + t + '</title></head>' +
'<body>' +
'<h1>Index of ' + t + '</h1>' +
'<hr><pre><a href="../">../</a>\n'
this.cache.readdir.get(p, (er, data) => {
if (er) {
return cb(er)
}
let nameLen = 0
let sizeLen = 0
Object.keys(data).map((f) => {
const d = data[f]
let name = f
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
if (d.size === '-') {
name += '/'
}
const showName = name.replace(/^(.{40}).{3,}$/, '$1..>')
const linkName = encodeURIComponent(name)
.replace(/%2e/ig, '.') // Encoded dots are dots
.replace(/%2f|%5c/ig, '/') // encoded slashes are /
.replace(/[/\\]/g, '/') // back slashes are slashes
nameLen = Math.max(nameLen, showName.length)
sizeLen = Math.max(sizeLen, ('' + d.size).length)
return ['<a href="' + linkName + '">' + showName + '</a>',
d.mtime, d.size, showName]
}).sort((a, b) => {
return a[2] === '-' && b[2] !== '-' // dirs first
? -1
: a[2] !== '-' && b[2] === '-'
? 1
: a[0].toLowerCase() < b[0].toLowerCase() // then alpha
? -1
: a[0].toLowerCase() > b[0].toLowerCase()
? 1
: 0
}).forEach((line) => {
const namePad = new Array(8 + nameLen - line[3].length).join(' ')
const sizePad = new Array(8 + sizeLen - ('' + line[2]).length).join(' ')
str += line[0] + namePad +
line[1].toISOString() +
sizePad + line[2] + '\n'
})
str += '</pre><hr></body></html>'
cb(null, Buffer.from(str))
})
}
_loadReaddir (p, cb) {
let len
let data
fs.readdir(p, (er, files) => {
if (er) {
return cb(er)
}
files = files.filter((f) => {
if (!this.opt.dot) {
return !/^\./.test(f)
} else {
return f !== '.' && f !== '..'
}
})
len = files.length
data = {}
files.forEach((file) => {
const pf = path.join(p, file)
this.cache.stat.get(pf, (er, stat) => {
if (er) {
return cb(er)
}
if (stat.isDirectory()) {
stat.size = '-'
}
data[file] = stat
next()
})
})
})
const next = () => {
if (--len === 0) {
cb(null, data)
}
}
}
_loadStat (key, cb) {
// key is either fd:path or just a path
const fdp = key.match(/^(\d+):(.*)/)
if (fdp) {
const fd = +fdp[1]
const p = fdp[2]
fs.fstat(fd, (er, stat) => {
if (er) {
return cb(er)
}
this.cache.stat.set(p, stat)
cb(null, stat)
})
} else {
fs.stat(key, cb)
}
}
_loadContent () {
// this function should never be called.
// we check if the thing is in the cache, and if not, stream it in
// manually. this.cache.content.get() should not ever happen.
throw new Error('This should not ever happen')
}
}
function getEtag (s) {
return '"' + s.dev + '-' + s.ino + '-' + s.mtime.getTime() + '"'
}
function getGz (p, req) {
let gz = false
if (!/\.t?gz$/.exec(p)) {
const neg = req.negotiator || new Neg(req)
gz = neg.preferredEncoding(['gzip', 'identity']) === 'gzip'
}
return gz
}
module.exports = st
module.exports.Mount = Mount