vibe.http.fileserver 0/159(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
/** 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.conv; import std.datetime; import std.digest.md; import std.string; import std.algorithm; @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 the path, size and last modification time of the file) and `"Last-Modified"` headers. The cache control directives `"Expires"` and `"Cache-Control"` will also be emitted if the `HTTPFileServerSettings.maxAge` field is set to a positive duration. 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 (24 hours by default) Duration maxAge;// = hours(24); /// 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() { // need to use the contructor because the Ubuntu 13.10 GDC cannot CTFE dur() maxAge = 24.hours; } 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; } auto lastModified = toRFC822DateTimeString(dirent.timeModified.toUTC()); // simple etag generation auto etag = "\"" ~ hexDigest!MD5(pathstr ~ ":" ~ lastModified ~ ":" ~ to!string(dirent.size)).idup ~ "\""; res.headers["Last-Modified"] = lastModified; res.headers["Etag"] = etag; if (settings.maxAge > seconds(0)) { auto expireTime = Clock.currTime(UTC()) + settings.maxAge; res.headers["Expires"] = toRFC822DateTimeString(expireTime); res.headers["Cache-Control"] = "max-age="~to!string(settings.maxAge.total!"seconds"); } if( auto pv = "If-Modified-Since" in req.headers ) { if( *pv == lastModified ) { res.statusCode = HTTPStatus.NotModified; res.writeVoidBody(); return; } } if( auto pv = "If-None-Match" in req.headers ) { if ( *pv == etag ) { res.statusCode = HTTPStatus.NotModified; res.writeVoidBody(); 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"]); } }