-
Notifications
You must be signed in to change notification settings - Fork 286
/
fileserver.d
656 lines (545 loc) · 19.4 KB
/
fileserver.d
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
/**
A static HTTP file server.
Copyright: © 2012-2015 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.http.fileserver;
import vibe.core.file;
import vibe.core.log;
import vibe.core.stream : RandomAccessStream, pipe;
import vibe.http.server;
import vibe.inet.message;
import vibe.inet.mimetypes;
import vibe.inet.url;
import vibe.internal.interfaceproxy;
import std.algorithm;
import std.conv;
import std.datetime;
import std.digest.md;
import std.exception;
import std.range : popFront, empty, drop;
import std.string;
@safe:
/**
Returns a request handler that serves files from the specified directory.
See `sendFile` for more information.
Params:
local_path = Path to the folder to serve files from.
settings = Optional settings object enabling customization of how
the files get served.
Returns:
A request delegate is returned, which is suitable for registering in
a `URLRouter` or for passing to `listenHTTP`.
See_Also: `serveStaticFile`, `sendFile`
*/
HTTPServerRequestDelegateS serveStaticFiles(NativePath local_path, HTTPFileServerSettings settings = null)
{
import std.range.primitives : front;
if (!settings) settings = new HTTPFileServerSettings;
if (!settings.serverPathPrefix.endsWith("/")) settings.serverPathPrefix ~= "/";
void callback(scope HTTPServerRequest req, scope HTTPServerResponse res)
@safe {
string srv_path;
if (auto pp = "pathMatch" in req.params) srv_path = *pp;
else if (req.path.length > 0) srv_path = req.path;
else srv_path = req.requestURL;
if (!srv_path.startsWith(settings.serverPathPrefix)) {
logDebug("path '%s' not starting with '%s'", srv_path, settings.serverPathPrefix);
return;
}
auto rel_path = srv_path[settings.serverPathPrefix.length .. $];
auto rpath = PosixPath(rel_path);
logTrace("Processing '%s'", srv_path);
rpath.normalize();
logDebug("Path '%s' -> '%s'", rel_path, rpath.toNativeString());
if (rpath.absolute) {
logDebug("Path is absolute, not responding");
return;
} else if (!rpath.empty && rpath.bySegment.front.name == "..")
return; // don't respond to relative paths outside of the root path
sendFileImpl(req, res, local_path ~ rpath, settings);
}
return &callback;
}
/// ditto
HTTPServerRequestDelegateS serveStaticFiles(string local_path, HTTPFileServerSettings settings = null)
{
return serveStaticFiles(NativePath(local_path), settings);
}
///
unittest {
import vibe.http.fileserver;
import vibe.http.router;
import vibe.http.server;
void setupServer()
{
auto router = new URLRouter;
// add other routes here
router.get("*", serveStaticFiles("public/"));
auto settings = new HTTPServerSettings;
listenHTTP(settings, router);
}
}
/** This example serves all files in the "public" sub directory
with an added prefix "static/" so that they don't interfere
with other registered routes.
*/
unittest {
import vibe.http.fileserver;
import vibe.http.router;
import vibe.http.server;
void setupRoutes()
{
auto router = new URLRouter;
// add other routes here
auto fsettings = new HTTPFileServerSettings;
fsettings.serverPathPrefix = "/static";
router.get("static/*", serveStaticFiles("public/", fsettings));
auto settings = new HTTPServerSettings;
listenHTTP(settings, router);
}
}
/**
Returns a request handler that serves a specific file on disk.
See `sendFile` for more information.
Params:
local_path = Path to the file to serve.
settings = Optional settings object enabling customization of how
the file gets served.
Returns:
A request delegate is returned, which is suitable for registering in
a `URLRouter` or for passing to `listenHTTP`.
See_Also: `serveStaticFiles`, `sendFile`
*/
HTTPServerRequestDelegateS serveStaticFile(NativePath local_path, HTTPFileServerSettings settings = null)
{
if (!settings) settings = new HTTPFileServerSettings;
assert(settings.serverPathPrefix == "/", "serverPathPrefix is not supported for single file serving.");
void callback(scope HTTPServerRequest req, scope HTTPServerResponse res)
{
sendFileImpl(req, res, local_path, settings);
}
return &callback;
}
/// ditto
HTTPServerRequestDelegateS serveStaticFile(string local_path, HTTPFileServerSettings settings = null)
{
return serveStaticFile(NativePath(local_path), settings);
}
/**
Sends a file to the given HTTP server response object.
When serving a file, certain request headers are supported to avoid sending
the file if the client has it already cached. These headers are
`"If-Modified-Since"` and `"If-None-Match"`. The client will be delivered
with the necessary `"Etag"` (generated from size and last modification time
of the file) and `"Last-Modified"` headers.
The cache control directives `"Expires"` and/or `"Cache-Control"` will also be
emitted if the `HTTPFileServerSettings.maxAge` field is set to a positive
duration and/or `HTTPFileServerSettings.cacheControl` has been set.
Finally, HEAD requests will automatically be handled without reading the
actual file contents. Am empty response body is written instead.
Params:
req = The incoming HTTP request - cache and modification headers of the
request can influence the generated response.
res = The response object to write to.
settings = Optional settings object enabling customization of how the
file gets served.
*/
void sendFile(scope HTTPServerRequest req, scope HTTPServerResponse res, NativePath path, HTTPFileServerSettings settings = null)
{
static HTTPFileServerSettings default_settings;
if (!settings) {
if (!default_settings) default_settings = new HTTPFileServerSettings;
settings = default_settings;
}
sendFileImpl(req, res, path, settings);
}
/**
Configuration options for the static file server.
*/
class HTTPFileServerSettings {
/// Prefix of the request path to strip before looking up files
string serverPathPrefix = "/";
/// Maximum cache age to report to the client (zero by default)
Duration maxAge = 0.seconds;
/** Cache control to control where cache can be saved, if at all, such as
proxies, the storage, etc.
Leave null or empty to not emit any cache control directives other than
max-age if maxAge is set.
Common values include: public for making a shared resource cachable across
multiple users or private for a response that should only be cached for a
single user.
See https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control
*/
string cacheControl = null;
/// General options
HTTPFileServerOption options = HTTPFileServerOption.defaults; /// additional options
/** Maps from encoding scheme (e.g. "gzip") to file extension.
If a request accepts a supported encoding scheme, then the file server
will look for a file with the extension as a suffix and, if that exists,
sends it as the encoded representation instead of sending the original
file.
Example:
---
settings.encodingFileExtension["gzip"] = ".gz";
---
*/
string[string] encodingFileExtension;
/**
Called just before headers and data are sent.
Allows headers to be customized, or other custom processing to be performed.
Note: Any changes you make to the response, physicalPath, or anything
else during this function will NOT be verified by Vibe.d for correctness.
Make sure any alterations you make are complete and correct according to HTTP spec.
*/
void delegate(scope HTTPServerRequest req, scope HTTPServerResponse res, ref string physicalPath) preWriteCallback = null;
this()
{
}
this(string path_prefix)
{
this();
serverPathPrefix = path_prefix;
}
}
/**
Additional options for the static file server.
*/
enum HTTPFileServerOption {
none = 0,
/// respond with 404 if a file was not found
failIfNotFound = 1 << 0,
/// serve index.html for directories
serveIndexHTML = 1 << 1,
/// default options are serveIndexHTML
defaults = serveIndexHTML,
}
private void sendFileImpl(scope HTTPServerRequest req, scope HTTPServerResponse res, NativePath path, HTTPFileServerSettings settings = null)
{
auto pathstr = path.toNativeString();
// return if the file does not exist
if (!existsFile(pathstr)){
if (settings.options & HTTPFileServerOption.failIfNotFound)
throw new HTTPStatusException(HTTPStatus.NotFound);
return;
}
FileInfo dirent;
try dirent = getFileInfo(pathstr);
catch(Exception){
throw new HTTPStatusException(HTTPStatus.InternalServerError, "Failed to get information for the file due to a file system error.");
}
if (dirent.isDirectory) {
if (settings.options & HTTPFileServerOption.serveIndexHTML)
return sendFileImpl(req, res, path ~ "index.html", settings);
logDebugV("Hit directory when serving files, ignoring: %s", pathstr);
if (settings.options & HTTPFileServerOption.failIfNotFound)
throw new HTTPStatusException(HTTPStatus.NotFound);
return;
}
if (handleCacheFile(req, res, dirent, settings.cacheControl, settings.maxAge)) {
return;
}
auto mimetype = res.headers.get("Content-Type", getMimeTypeForFile(pathstr));
// avoid double-compression
if ("Content-Encoding" in res.headers && isCompressedFormat(mimetype))
res.headers.remove("Content-Encoding");
if (!("Content-Type" in res.headers))
res.headers["Content-Type"] = mimetype;
res.headers.addField("Accept-Ranges", "bytes");
ulong rangeStart = 0;
ulong rangeEnd = 0;
auto prange = "Range" in req.headers;
if (prange) {
auto range = (*prange).chompPrefix("bytes=");
if (range.canFind(','))
throw new HTTPStatusException(HTTPStatus.notImplemented);
auto s = range.split("-");
if (s.length != 2)
throw new HTTPStatusException(HTTPStatus.badRequest);
// https://tools.ietf.org/html/rfc7233
// Range can be in form "-\d", "\d-" or "\d-\d"
try {
if (s[0].length) {
rangeStart = s[0].to!ulong;
rangeEnd = s[1].length ? s[1].to!ulong : dirent.size;
} else if (s[1].length) {
rangeEnd = dirent.size;
auto len = s[1].to!ulong;
if (len >= rangeEnd)
rangeStart = 0;
else
rangeStart = rangeEnd - len;
} else {
throw new HTTPStatusException(HTTPStatus.badRequest);
}
} catch (ConvException) {
throw new HTTPStatusException(HTTPStatus.badRequest);
}
if (rangeEnd > dirent.size)
rangeEnd = dirent.size;
if (rangeStart > rangeEnd)
rangeStart = rangeEnd;
if (rangeEnd)
rangeEnd--; // End is inclusive, so one less than length
// potential integer overflow with rangeEnd - rangeStart == size_t.max is intended. This only happens with empty files, the + 1 will then put it back to 0
res.headers["Content-Length"] = to!string(rangeEnd - rangeStart + 1);
res.headers["Content-Range"] = "bytes %s-%s/%s".format(rangeStart < rangeEnd ? rangeStart : rangeEnd, rangeEnd, dirent.size);
res.statusCode = HTTPStatus.partialContent;
} else
res.headers["Content-Length"] = dirent.size.to!string;
// check for already encoded file if configured
string encodedFilepath;
auto pce = "Content-Encoding" in res.headers;
if (pce) {
if (auto pfe = *pce in settings.encodingFileExtension) {
assert((*pfe).length > 0);
auto p = pathstr ~ *pfe;
if (existsFile(p))
encodedFilepath = p;
}
}
if (encodedFilepath.length) {
auto origLastModified = dirent.timeModified.toUTC();
try dirent = getFileInfo(encodedFilepath);
catch(Exception){
throw new HTTPStatusException(HTTPStatus.InternalServerError, "Failed to get information for the file due to a file system error.");
}
// encoded file must be younger than original else warn
if (dirent.timeModified.toUTC() >= origLastModified){
logTrace("Using already encoded file '%s' -> '%s'", path, encodedFilepath);
path = NativePath(encodedFilepath);
res.headers["Content-Length"] = to!string(dirent.size);
} else {
logWarn("Encoded file '%s' is older than the original '%s'. Ignoring it.", encodedFilepath, path);
encodedFilepath = null;
}
}
if(settings.preWriteCallback)
settings.preWriteCallback(req, res, pathstr);
// for HEAD responses, stop here
if( res.isHeadResponse() ){
res.writeVoidBody();
assert(res.headerWritten);
logDebug("sent file header %d, %s!", dirent.size, res.headers["Content-Type"]);
return;
}
// else write out the file contents
//logTrace("Open file '%s' -> '%s'", srv_path, pathstr);
FileStream fil;
try {
fil = openFile(path);
} catch( Exception e ){
// TODO: handle non-existant files differently than locked files?
logDebug("Failed to open file %s: %s", pathstr, () @trusted { return e.toString(); } ());
return;
}
scope(exit) fil.close();
if (prange) {
fil.seek(rangeStart);
fil.pipe(res.bodyWriter, rangeEnd - rangeStart + 1);
logTrace("partially sent file %d-%d, %s!", rangeStart, rangeEnd, res.headers["Content-Type"]);
} else {
if (pce && !encodedFilepath.length)
fil.pipe(res.bodyWriter);
else res.writeRawBody(fil);
logTrace("sent file %d, %s!", fil.size, res.headers["Content-Type"]);
}
}
/**
Calls $(D handleCache) with prefilled etag and lastModified value based on a file.
See_Also: handleCache
Returns: $(D true) if the cache was already handled and no further response must be sent or $(D false) if a response must be sent.
*/
bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
string file, string cache_control = null, Duration max_age = Duration.zero)
{
return handleCacheFile(req, res, NativePath(file), cache_control, max_age);
}
/// ditto
bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
NativePath file, string cache_control = null, Duration max_age = Duration.zero)
{
if (!existsFile(file)) {
return false;
}
FileInfo ent;
try {
ent = getFileInfo(file);
} catch (Exception) {
throw new HTTPStatusException(HTTPStatus.internalServerError,
"Failed to get information for the file due to a file system error.");
}
return handleCacheFile(req, res, ent, cache_control, max_age);
}
/// ditto
bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
FileInfo dirent, string cache_control = null, Duration max_age = Duration.zero)
{
import std.bitmanip : nativeToLittleEndian;
import std.digest.md : MD5, toHexString;
SysTime lastModified = dirent.timeModified;
ETag etag;
etag.weak = dirent.isDirectory;
MD5 md5;
md5.put(lastModified.stdTime.nativeToLittleEndian);
md5.put(dirent.size.nativeToLittleEndian);
etag.tag = toHexString(md5.finish())[].idup;
return handleCache(req, res, etag, lastModified, cache_control, max_age);
}
/**
Processes header tags in a request and writes responses given on requested cache status.
Returns: $(D true) if the cache was already handled and no further response must be sent or $(D false) if a response must be sent.
*/
bool handleCache(scope HTTPServerRequest req, scope HTTPServerResponse res, ETag etag,
SysTime last_modified, string cache_control = null, Duration max_age = Duration.zero)
{
// https://tools.ietf.org/html/rfc7232#section-4.1
// and
// https://tools.ietf.org/html/rfc7232#section-6
string lastModifiedString;
if (last_modified != SysTime.init) {
lastModifiedString = toRFC822DateTimeString(last_modified);
res.headers["Last-Modified"] = lastModifiedString;
}
if (etag != ETag.init) {
res.headers["Etag"] = etag.toString;
}
if (max_age > Duration.zero) {
res.headers["Expires"] = toRFC822DateTimeString(Clock.currTime(UTC()) + max_age);
}
if (cache_control.length) {
if (max_age > Duration.zero && !cache_control.canFind("max-age=")) {
res.headers["Cache-Control"] = cache_control
~ ", max-age=" ~ to!string(max_age.total!"seconds");
} else {
res.headers["Cache-Control"] = cache_control;
}
} else if (max_age > Duration.zero) {
res.headers["Cache-Control"] = text("max-age=", max_age.total!"seconds");
}
// https://tools.ietf.org/html/rfc7232#section-3.1
string ifMatch = req.headers.get("If-Match");
if (ifMatch.length) {
if (!cacheMatch(ifMatch, etag, false)) {
res.statusCode = HTTPStatus.preconditionFailed;
res.writeVoidBody();
return true;
}
}
// https://tools.ietf.org/html/rfc7232#section-3.2
string ifNoneMatch = req.headers.get("If-None-Match");
if (ifNoneMatch.length) {
if (cacheMatch(ifNoneMatch, etag, true)) {
if (req.method.among!(HTTPMethod.GET, HTTPMethod.HEAD))
res.statusCode = HTTPStatus.notModified;
else
res.statusCode = HTTPStatus.preconditionFailed;
res.writeVoidBody();
return true;
}
}
if (last_modified != SysTime.init) {
// https://tools.ietf.org/html/rfc7232#section-3.3
string ifModifiedSince = req.headers.get("If-Modified-Since");
if (ifModifiedSince.length) {
const check = lastModifiedString == ifModifiedSince ||
last_modified <= parseRFC822DateTimeString(ifModifiedSince);
if (check) {
res.statusCode = HTTPStatus.notModified;
res.writeVoidBody();
return true;
}
}
// https://tools.ietf.org/html/rfc7232#section-3.4
string ifUnmodifiedSince = req.headers.get("If-Unmodified-Since");
if (ifUnmodifiedSince.length) {
const check = lastModifiedString != ifUnmodifiedSince
|| last_modified > parseRFC822DateTimeString(ifUnmodifiedSince);
if (check) {
res.statusCode = HTTPStatus.preconditionFailed;
res.writeVoidBody();
return true;
}
}
}
return false;
}
/**
Represents an Entity-Tag value for use inside HTTP Cache headers.
Standards: https://tools.ietf.org/html/rfc7232#section-2.3
*/
struct ETag
{
bool weak;
string tag;
static ETag parse(string s)
{
enforce!ConvException(s.endsWith('"'));
if (s.startsWith(`W/"`)) {
ETag ret = { weak: true, tag: s[3 .. $ - 1] };
return ret;
} else if (s.startsWith('"')) {
ETag ret;
ret.tag = s[1 .. $ - 1];
return ret;
} else {
throw new ConvException(`ETag didn't start with W/" nor with " !`);
}
}
string toString() const @property
{
return text(weak ? `W/"` : `"`, tag, '"');
}
}
/**
Matches a given match expression with a specific ETag. Can allow or disallow weak ETags and supports multiple tags.
Standards: https://tools.ietf.org/html/rfc7232#section-2.3.2
*/
bool cacheMatch(string match, ETag etag, bool allow_weak)
{
if (match == "*") {
return true;
}
if ((etag.weak && !allow_weak) || !match.length) {
return false;
}
auto allBytes = match.representation;
for (auto range = allBytes; !range.empty; range.popFront)
{
auto start = range = range.find('"').drop(1);
range = range.find('"');
if (range.empty)
break;
const check = start[0 .. &range[0] - &start[0]];
const checkWeak = match[0 .. &start[0] - &allBytes[0]].endsWith(`W/"`);
if (allow_weak || !checkWeak) {
if (check == etag.tag) {
return true;
}
}
if (!(cast(string) range).stripLeft.startsWith(","))
break;
}
return false;
}
unittest
{
// from RFC 7232 Section 2.3.2
// +--------+--------+-------------------+-----------------+
// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
// +--------+--------+-------------------+-----------------+
// | W/"1" | W/"1" | no match | match |
// | W/"1" | W/"2" | no match | no match |
// | W/"1" | "1" | no match | match |
// | "1" | "1" | match | match |
// +--------+--------+-------------------+-----------------+
assert(!cacheMatch(`W/"1"`, ETag(true, "1"), false));
assert( cacheMatch(`W/"1"`, ETag(true, "1"), true));
assert(!cacheMatch(`W/"1"`, ETag(true, "2"), false));
assert(!cacheMatch(`W/"1"`, ETag(true, "2"), true));
assert(!cacheMatch(`W/"1"`, ETag(false, "1"), false));
assert( cacheMatch(`W/"1"`, ETag(false, "1"), true));
assert(cacheMatch(`"1"`, ETag(false, "1"), false));
assert(cacheMatch(`"1"`, ETag(false, "1"), true));
}