fileserver.d 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. /**
  2. A static HTTP file server.
  3. Copyright: © 2012-2015 Sönke Ludwig
  4. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  5. Authors: Sönke Ludwig
  6. */
  7. module vibe.http.fileserver;
  8. import vibe.core.file;
  9. import vibe.core.log;
  10. import vibe.core.stream : RandomAccessStream, pipe;
  11. import vibe.http.server;
  12. import vibe.inet.message;
  13. import vibe.inet.mimetypes;
  14. import vibe.inet.url;
  15. import vibe.internal.interfaceproxy;
  16. import std.ascii : isWhite;
  17. import std.algorithm;
  18. import std.conv;
  19. import std.datetime;
  20. import std.digest.md;
  21. import std.exception;
  22. import std.range : popFront, empty, drop;
  23. import std.string;
  24. import std.typecons : Flag, Yes, No;
  25. @safe:
  26. /**
  27. Returns a request handler that serves files from the specified directory.
  28. See `sendFile` for more information.
  29. Params:
  30. local_path = Path to the folder to serve files from.
  31. settings = Optional settings object enabling customization of how
  32. the files get served.
  33. Returns:
  34. A request delegate is returned, which is suitable for registering in
  35. a `URLRouter` or for passing to `listenHTTP`.
  36. See_Also: `serveStaticFile`, `sendFile`
  37. */
  38. HTTPServerRequestDelegateS serveStaticFiles(NativePath local_path, HTTPFileServerSettings settings = null)
  39. {
  40. import std.range.primitives : front;
  41. if (!settings) settings = new HTTPFileServerSettings;
  42. if (!settings.serverPathPrefix.endsWith("/")) settings.serverPathPrefix ~= "/";
  43. void callback(scope HTTPServerRequest req, scope HTTPServerResponse res)
  44. @safe {
  45. string srv_path;
  46. if (auto pp = "pathMatch" in req.params) srv_path = *pp;
  47. else if (req.requestPath != InetPath.init) srv_path = (cast(PosixPath)req.requestPath).toString();
  48. else srv_path = req.requestURL;
  49. if (!srv_path.startsWith(settings.serverPathPrefix)) {
  50. logDebug("path '%s' not starting with '%s'", srv_path, settings.serverPathPrefix);
  51. return;
  52. }
  53. auto rel_path = srv_path[settings.serverPathPrefix.length .. $];
  54. auto rpath = PosixPath(rel_path);
  55. logTrace("Processing '%s'", srv_path);
  56. rpath.normalize();
  57. logDebug("Path '%s' -> '%s'", rel_path, rpath.toNativeString());
  58. if (rpath.absolute) {
  59. logDebug("Path is absolute, not responding");
  60. return;
  61. } else if (!rpath.empty && rpath.bySegment.front.name == "..")
  62. return; // don't respond to relative paths outside of the root path
  63. sendFileImpl(req, res, local_path ~ rpath, settings);
  64. }
  65. return &callback;
  66. }
  67. /// ditto
  68. HTTPServerRequestDelegateS serveStaticFiles(string local_path, HTTPFileServerSettings settings = null)
  69. {
  70. return serveStaticFiles(NativePath(local_path), settings);
  71. }
  72. ///
  73. unittest {
  74. import vibe.http.fileserver;
  75. import vibe.http.router;
  76. import vibe.http.server;
  77. void setupServer()
  78. {
  79. auto router = new URLRouter;
  80. // add other routes here
  81. router.get("*", serveStaticFiles("public/"));
  82. auto settings = new HTTPServerSettings;
  83. listenHTTP(settings, router);
  84. }
  85. }
  86. /** This example serves all files in the "public" sub directory
  87. with an added prefix "static/" so that they don't interfere
  88. with other registered routes.
  89. */
  90. unittest {
  91. import vibe.http.fileserver;
  92. import vibe.http.router;
  93. import vibe.http.server;
  94. void setupRoutes()
  95. {
  96. auto router = new URLRouter;
  97. // add other routes here
  98. auto fsettings = new HTTPFileServerSettings;
  99. fsettings.serverPathPrefix = "/static";
  100. router.get("/static/*", serveStaticFiles("public/", fsettings));
  101. auto settings = new HTTPServerSettings;
  102. listenHTTP(settings, router);
  103. }
  104. }
  105. /**
  106. Returns a request handler that serves a specific file on disk.
  107. See `sendFile` for more information.
  108. Params:
  109. local_path = Path to the file to serve.
  110. settings = Optional settings object enabling customization of how
  111. the file gets served.
  112. Returns:
  113. A request delegate is returned, which is suitable for registering in
  114. a `URLRouter` or for passing to `listenHTTP`.
  115. See_Also: `serveStaticFiles`, `sendFile`
  116. */
  117. HTTPServerRequestDelegateS serveStaticFile(NativePath local_path, HTTPFileServerSettings settings = null)
  118. {
  119. if (!settings) settings = new HTTPFileServerSettings;
  120. assert(settings.serverPathPrefix == "/", "serverPathPrefix is not supported for single file serving.");
  121. void callback(scope HTTPServerRequest req, scope HTTPServerResponse res)
  122. {
  123. sendFileImpl(req, res, local_path, settings);
  124. }
  125. return &callback;
  126. }
  127. /// ditto
  128. HTTPServerRequestDelegateS serveStaticFile(string local_path, HTTPFileServerSettings settings = null)
  129. {
  130. return serveStaticFile(NativePath(local_path), settings);
  131. }
  132. /**
  133. Sends a file to the given HTTP server response object.
  134. When serving a file, certain request headers are supported to avoid sending
  135. the file if the client has it already cached. These headers are
  136. `"If-Modified-Since"` and `"If-None-Match"`. The client will be delivered
  137. with the necessary `"Etag"` (generated from size and last modification time
  138. of the file) and `"Last-Modified"` headers.
  139. The cache control directives `"Expires"` and/or `"Cache-Control"` will also be
  140. emitted if the `HTTPFileServerSettings.maxAge` field is set to a positive
  141. duration and/or `HTTPFileServerSettings.cacheControl` has been set.
  142. Finally, HEAD requests will automatically be handled without reading the
  143. actual file contents. Am empty response body is written instead.
  144. Params:
  145. req = The incoming HTTP request - cache and modification headers of the
  146. request can influence the generated response.
  147. res = The response object to write to.
  148. path = Path to the file to be sent.
  149. settings = Optional settings object enabling customization of how the
  150. file gets served.
  151. */
  152. void sendFile(scope HTTPServerRequest req, scope HTTPServerResponse res, NativePath path, HTTPFileServerSettings settings = null)
  153. {
  154. static HTTPFileServerSettings default_settings;
  155. if (!settings) {
  156. if (!default_settings) default_settings = new HTTPFileServerSettings;
  157. settings = default_settings;
  158. }
  159. sendFileImpl(req, res, path, settings);
  160. }
  161. /**
  162. Configuration options for the static file server.
  163. */
  164. class HTTPFileServerSettings {
  165. /// Prefix of the request path to strip before looking up files
  166. string serverPathPrefix = "/";
  167. /// Maximum cache age to report to the client (zero by default)
  168. Duration maxAge = 0.seconds;
  169. /** Cache control to control where cache can be saved, if at all, such as
  170. proxies, the storage, etc.
  171. Leave null or empty to not emit any cache control directives other than
  172. max-age if maxAge is set.
  173. Common values include: public for making a shared resource cachable across
  174. multiple users or private for a response that should only be cached for a
  175. single user.
  176. See https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control
  177. */
  178. string cacheControl = null;
  179. /// General options
  180. HTTPFileServerOption options = HTTPFileServerOption.defaults; /// additional options
  181. /** Maps from encoding scheme (e.g. "gzip") to file extension.
  182. If a request accepts a supported encoding scheme, then the file server
  183. will look for a file with the extension as a suffix and, if that exists,
  184. sends it as the encoded representation instead of sending the original
  185. file.
  186. Example:
  187. ---
  188. settings.encodingFileExtension["gzip"] = ".gz";
  189. ---
  190. */
  191. string[string] encodingFileExtension;
  192. /**
  193. Called just before headers and data are sent.
  194. Allows headers to be customized, or other custom processing to be performed.
  195. Note: Any changes you make to the response, physicalPath, or anything
  196. else during this function will NOT be verified by Vibe.d for correctness.
  197. Make sure any alterations you make are complete and correct according to HTTP spec.
  198. */
  199. void delegate(scope HTTPServerRequest req, scope HTTPServerResponse res, ref string physicalPath) preWriteCallback = null;
  200. this()
  201. {
  202. }
  203. this(string path_prefix)
  204. {
  205. this();
  206. serverPathPrefix = path_prefix;
  207. }
  208. }
  209. /**
  210. Additional options for the static file server.
  211. */
  212. enum HTTPFileServerOption {
  213. none = 0,
  214. /// respond with 404 if a file was not found
  215. failIfNotFound = 1 << 0,
  216. /// serve index.html for directories
  217. serveIndexHTML = 1 << 1,
  218. /// default options are serveIndexHTML
  219. defaults = serveIndexHTML,
  220. }
  221. private void sendFileImpl(scope HTTPServerRequest req, scope HTTPServerResponse res, NativePath path, HTTPFileServerSettings settings = null)
  222. {
  223. auto pathstr = path.toNativeString();
  224. // return if the file does not exist
  225. if (!existsFile(pathstr)){
  226. if (settings.options & HTTPFileServerOption.failIfNotFound)
  227. throw new HTTPStatusException(HTTPStatus.notFound);
  228. return;
  229. }
  230. FileInfo dirent;
  231. try dirent = getFileInfo(pathstr);
  232. catch(Exception){
  233. throw new HTTPStatusException(HTTPStatus.internalServerError, "Failed to get information for the file due to a file system error.");
  234. }
  235. if (dirent.isDirectory) {
  236. if (settings.options & HTTPFileServerOption.serveIndexHTML)
  237. return sendFileImpl(req, res, path ~ "index.html", settings);
  238. logDebugV("Hit directory when serving files, ignoring: %s", pathstr);
  239. if (settings.options & HTTPFileServerOption.failIfNotFound)
  240. throw new HTTPStatusException(HTTPStatus.notFound);
  241. return;
  242. }
  243. if (handleCacheFile(req, res, dirent, settings.cacheControl, settings.maxAge)) {
  244. return;
  245. }
  246. auto mimetype = res.headers.get("Content-Type", getMimeTypeForFile(pathstr));
  247. // avoid double-compression
  248. if ("Content-Encoding" in res.headers && isCompressedFormat(mimetype))
  249. res.headers.remove("Content-Encoding");
  250. if (!("Content-Type" in res.headers))
  251. res.headers["Content-Type"] = mimetype;
  252. res.headers.addField("Accept-Ranges", "bytes");
  253. RangeSpec range;
  254. if (auto prange = "Range" in req.headers) {
  255. range = parseRangeHeader(*prange, dirent.size, res);
  256. // 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
  257. res.headers["Content-Length"] = to!string(range.max - range.min);
  258. res.headers["Content-Range"] = "bytes %s-%s/%s".format(range.min, range.max - 1, dirent.size);
  259. res.statusCode = HTTPStatus.partialContent;
  260. } else res.headers["Content-Length"] = dirent.size.to!string;
  261. // check for already encoded file if configured
  262. string encodedFilepath;
  263. auto pce = "Content-Encoding" in res.headers;
  264. if (pce) {
  265. if (auto pfe = *pce in settings.encodingFileExtension) {
  266. assert((*pfe).length > 0);
  267. auto p = pathstr ~ *pfe;
  268. if (existsFile(p))
  269. encodedFilepath = p;
  270. }
  271. }
  272. if (encodedFilepath.length) {
  273. auto origLastModified = dirent.timeModified.toUTC();
  274. try dirent = getFileInfo(encodedFilepath);
  275. catch(Exception){
  276. throw new HTTPStatusException(HTTPStatus.internalServerError, "Failed to get information for the file due to a file system error.");
  277. }
  278. // encoded file must be younger than original else warn
  279. if (dirent.timeModified.toUTC() >= origLastModified){
  280. logTrace("Using already encoded file '%s' -> '%s'", path, encodedFilepath);
  281. path = NativePath(encodedFilepath);
  282. res.headers["Content-Length"] = to!string(dirent.size);
  283. } else {
  284. logWarn("Encoded file '%s' is older than the original '%s'. Ignoring it.", encodedFilepath, path);
  285. encodedFilepath = null;
  286. }
  287. }
  288. if(settings.preWriteCallback)
  289. settings.preWriteCallback(req, res, pathstr);
  290. // for HEAD responses, stop here
  291. if( res.isHeadResponse() ){
  292. res.writeVoidBody();
  293. assert(res.headerWritten);
  294. logDebug("sent file header %d, %s!", dirent.size, res.headers["Content-Type"]);
  295. return;
  296. }
  297. // else write out the file contents
  298. //logTrace("Open file '%s' -> '%s'", srv_path, pathstr);
  299. FileStream fil;
  300. try {
  301. fil = openFile(path);
  302. } catch( Exception e ){
  303. // TODO: handle non-existant files differently than locked files?
  304. logDebug("Failed to open file %s: %s", pathstr, () @trusted { return e.toString(); } ());
  305. return;
  306. }
  307. scope(exit) fil.close();
  308. if (range.max > range.min) {
  309. fil.seek(range.min);
  310. fil.pipe(res.bodyWriter, range.max - range.min);
  311. logTrace("partially sent file %d-%d, %s!", range.min, range.max - 1, res.headers["Content-Type"]);
  312. } else {
  313. if (pce && !encodedFilepath.length)
  314. fil.pipe(res.bodyWriter);
  315. else res.writeRawBody(fil);
  316. logTrace("sent file %d, %s!", fil.size, res.headers["Content-Type"]);
  317. }
  318. }
  319. /**
  320. Calls $(D handleCache) with prefilled etag and lastModified value based on a file.
  321. See_Also: handleCache
  322. 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.
  323. */
  324. bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
  325. string file, string cache_control = null, Duration max_age = Duration.zero)
  326. {
  327. return handleCacheFile(req, res, NativePath(file), cache_control, max_age);
  328. }
  329. /// ditto
  330. bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
  331. NativePath file, string cache_control = null, Duration max_age = Duration.zero)
  332. {
  333. if (!existsFile(file)) {
  334. return false;
  335. }
  336. FileInfo ent;
  337. try {
  338. ent = getFileInfo(file);
  339. } catch (Exception) {
  340. throw new HTTPStatusException(HTTPStatus.internalServerError,
  341. "Failed to get information for the file due to a file system error.");
  342. }
  343. return handleCacheFile(req, res, ent, cache_control, max_age);
  344. }
  345. /// ditto
  346. bool handleCacheFile(scope HTTPServerRequest req, scope HTTPServerResponse res,
  347. FileInfo dirent, string cache_control = null, Duration max_age = Duration.zero)
  348. {
  349. import std.bitmanip : nativeToLittleEndian;
  350. import std.digest.md : MD5, toHexString;
  351. SysTime lastModified = dirent.timeModified;
  352. const weak = cast(Flag!"weak") dirent.isDirectory;
  353. auto etag = ETag.md5(weak, lastModified.stdTime.nativeToLittleEndian, dirent.size.nativeToLittleEndian);
  354. return handleCache(req, res, etag, lastModified, cache_control, max_age);
  355. }
  356. /**
  357. Processes header tags in a request and writes responses given on requested cache status.
  358. Params:
  359. req = the client request used to determine cache control flow.
  360. res = the response to write cache headers to.
  361. etag = if set to anything except .init, adds a Etag header to the response and enables handling of If-Match and If-None-Match cache control request headers.
  362. last_modified = if set to anything except .init, adds a Last-Modified header to the response and enables handling of If-Modified-Since and If-Unmodified-Since cache control request headers.
  363. cache_control = if set, adds or modifies the Cache-Control header in the response to this string. Might get an additional max-age value appended if max_age is set.
  364. max_age = optional duration to set the Expires header and Cache-Control max-age part to. (if no existing `max-age=` part is given in the cache_control parameter)
  365. 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.
  366. */
  367. bool handleCache(scope HTTPServerRequest req, scope HTTPServerResponse res, ETag etag,
  368. SysTime last_modified, string cache_control = null, Duration max_age = Duration.zero)
  369. {
  370. // https://tools.ietf.org/html/rfc7232#section-4.1
  371. // and
  372. // https://tools.ietf.org/html/rfc7232#section-6
  373. string lastModifiedString;
  374. if (last_modified != SysTime.init) {
  375. lastModifiedString = toRFC822DateTimeString(last_modified);
  376. res.headers["Last-Modified"] = lastModifiedString;
  377. }
  378. if (etag != ETag.init) {
  379. res.headers["Etag"] = etag.toString;
  380. }
  381. if (max_age > Duration.zero) {
  382. res.headers["Expires"] = toRFC822DateTimeString(Clock.currTime(UTC()) + max_age);
  383. }
  384. if (cache_control.length) {
  385. if (max_age > Duration.zero && !cache_control.canFind("max-age=")) {
  386. res.headers["Cache-Control"] = cache_control
  387. ~ ", max-age=" ~ to!string(max_age.total!"seconds");
  388. } else {
  389. res.headers["Cache-Control"] = cache_control;
  390. }
  391. } else if (max_age > Duration.zero) {
  392. res.headers["Cache-Control"] = text("max-age=", max_age.total!"seconds");
  393. }
  394. // https://tools.ietf.org/html/rfc7232#section-3.1
  395. string ifMatch = req.headers.get("If-Match");
  396. if (ifMatch.length) {
  397. if (!cacheMatch(ifMatch, etag, No.allowWeak)) {
  398. res.statusCode = HTTPStatus.preconditionFailed;
  399. res.writeVoidBody();
  400. return true;
  401. }
  402. }
  403. else if (last_modified != SysTime.init) {
  404. // https://tools.ietf.org/html/rfc7232#section-3.4
  405. string ifUnmodifiedSince = req.headers.get("If-Unmodified-Since");
  406. if (ifUnmodifiedSince.length) {
  407. const check = lastModifiedString != ifUnmodifiedSince
  408. || last_modified > parseRFC822DateTimeString(ifUnmodifiedSince);
  409. if (check) {
  410. res.statusCode = HTTPStatus.preconditionFailed;
  411. res.writeVoidBody();
  412. return true;
  413. }
  414. }
  415. }
  416. // https://tools.ietf.org/html/rfc7232#section-3.2
  417. string ifNoneMatch = req.headers.get("If-None-Match");
  418. if (ifNoneMatch.length) {
  419. if (cacheMatch(ifNoneMatch, etag, Yes.allowWeak)) {
  420. if (req.method.among!(HTTPMethod.GET, HTTPMethod.HEAD))
  421. res.statusCode = HTTPStatus.notModified;
  422. else
  423. res.statusCode = HTTPStatus.preconditionFailed;
  424. res.writeVoidBody();
  425. return true;
  426. }
  427. }
  428. else if (last_modified != SysTime.init && req.method.among!(HTTPMethod.GET, HTTPMethod.HEAD)) {
  429. // https://tools.ietf.org/html/rfc7232#section-3.3
  430. string ifModifiedSince = req.headers.get("If-Modified-Since");
  431. if (ifModifiedSince.length) {
  432. const check = lastModifiedString == ifModifiedSince ||
  433. last_modified <= parseRFC822DateTimeString(ifModifiedSince);
  434. if (check) {
  435. res.statusCode = HTTPStatus.notModified;
  436. res.writeVoidBody();
  437. return true;
  438. }
  439. }
  440. }
  441. // TODO: support If-Range here
  442. return false;
  443. }
  444. /**
  445. Represents an Entity-Tag value for use inside HTTP Cache headers.
  446. Standards: https://tools.ietf.org/html/rfc7232#section-2.3
  447. */
  448. struct ETag
  449. {
  450. bool weak;
  451. string tag;
  452. static ETag parse(string s)
  453. {
  454. enforce!ConvException(s.endsWith('"'));
  455. if (s.startsWith(`W/"`)) {
  456. ETag ret = { weak: true, tag: s[3 .. $ - 1] };
  457. return ret;
  458. } else if (s.startsWith('"')) {
  459. ETag ret;
  460. ret.tag = s[1 .. $ - 1];
  461. return ret;
  462. } else {
  463. throw new ConvException(`ETag didn't start with W/" nor with " !`);
  464. }
  465. }
  466. string toString() const @property
  467. {
  468. return text(weak ? `W/"` : `"`, tag, '"');
  469. }
  470. /**
  471. Encodes the bytes with URL Base64 to a human readable string and returns an ETag struct wrapping it.
  472. */
  473. static ETag fromBytesBase64URLNoPadding(scope const(ubyte)[] bytes, Flag!"weak" weak = No.weak)
  474. {
  475. import std.base64 : Base64URLNoPadding;
  476. return ETag(weak, Base64URLNoPadding.encode(bytes).idup);
  477. }
  478. /**
  479. Hashes the input bytes with md5 and returns an URL Base64 encoded representation as ETag.
  480. */
  481. static ETag md5(T...)(Flag!"weak" weak, T data)
  482. {
  483. import std.digest.md : md5Of;
  484. return fromBytesBase64URLNoPadding(md5Of(data), weak);
  485. }
  486. }
  487. /**
  488. Matches a given match expression with a specific ETag. Can allow or disallow weak ETags and supports multiple tags.
  489. Standards: https://tools.ietf.org/html/rfc7232#section-2.3.2
  490. */
  491. bool cacheMatch(string match, ETag etag, Flag!"allowWeak" allow_weak)
  492. {
  493. if (match == "*") {
  494. return true;
  495. }
  496. if ((etag.weak && !allow_weak) || !match.length) {
  497. return false;
  498. }
  499. auto allBytes = match.representation;
  500. auto range = allBytes;
  501. while (!range.empty)
  502. {
  503. range = range.stripLeft!isWhite;
  504. bool isWeak = range.skipOver("W/");
  505. if (!range.skipOver('"'))
  506. return false; // malformed
  507. auto end = range.countUntil('"');
  508. if (end == -1)
  509. return false; // malformed
  510. const check = range[0 .. end];
  511. range = range[end .. $];
  512. if (allow_weak || !isWeak) {
  513. if (check == etag.tag) {
  514. return true;
  515. }
  516. }
  517. range.skipOver('"');
  518. range = range.stripLeft!isWhite;
  519. if (!range.skipOver(","))
  520. return false; // malformed
  521. }
  522. return false;
  523. }
  524. unittest
  525. {
  526. // from RFC 7232 Section 2.3.2
  527. // +--------+--------+-------------------+-----------------+
  528. // | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
  529. // +--------+--------+-------------------+-----------------+
  530. // | W/"1" | W/"1" | no match | match |
  531. // | W/"1" | W/"2" | no match | no match |
  532. // | W/"1" | "1" | no match | match |
  533. // | "1" | "1" | match | match |
  534. // +--------+--------+-------------------+-----------------+
  535. assert(!cacheMatch(`W/"1"`, ETag(Yes.weak, "1"), No.allowWeak));
  536. assert( cacheMatch(`W/"1"`, ETag(Yes.weak, "1"), Yes.allowWeak));
  537. assert(!cacheMatch(`W/"1"`, ETag(Yes.weak, "2"), No.allowWeak));
  538. assert(!cacheMatch(`W/"1"`, ETag(Yes.weak, "2"), Yes.allowWeak));
  539. assert(!cacheMatch(`W/"1"`, ETag(No.weak, "1"), No.allowWeak));
  540. assert( cacheMatch(`W/"1"`, ETag(No.weak, "1"), Yes.allowWeak));
  541. assert(cacheMatch(`"1"`, ETag(No.weak, "1"), No.allowWeak));
  542. assert(cacheMatch(`"1"`, ETag(No.weak, "1"), Yes.allowWeak));
  543. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "xyzzy"), No.allowWeak));
  544. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "xyzzy"), Yes.allowWeak));
  545. assert(!cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "xyzzz"), No.allowWeak));
  546. assert(!cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "xyzzz"), Yes.allowWeak));
  547. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "r2d2xxxx"), No.allowWeak));
  548. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "r2d2xxxx"), Yes.allowWeak));
  549. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "c3piozzzz"), No.allowWeak));
  550. assert(cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "c3piozzzz"), Yes.allowWeak));
  551. assert(!cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, ""), No.allowWeak));
  552. assert(!cacheMatch(`"xyzzy","r2d2xxxx", "c3piozzzz"`, ETag(No.weak, ""), Yes.allowWeak));
  553. assert(!cacheMatch(`"xyzzy",W/"r2d2xxxx", "c3piozzzz"`, ETag(Yes.weak, "r2d2xxxx"), No.allowWeak));
  554. assert( cacheMatch(`"xyzzy",W/"r2d2xxxx", "c3piozzzz"`, ETag(Yes.weak, "r2d2xxxx"), Yes.allowWeak));
  555. assert(!cacheMatch(`"xyzzy",W/"r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "r2d2xxxx"), No.allowWeak));
  556. assert( cacheMatch(`"xyzzy",W/"r2d2xxxx", "c3piozzzz"`, ETag(No.weak, "r2d2xxxx"), Yes.allowWeak));
  557. }
  558. private RangeSpec parseRangeHeader(string range_spec, ulong file_size, scope HTTPServerResponse res)
  559. {
  560. RangeSpec ret;
  561. auto range = range_spec.chompPrefix("bytes=");
  562. if (range.canFind(','))
  563. throw new HTTPStatusException(HTTPStatus.notImplemented);
  564. auto s = range.split("-");
  565. if (s.length != 2)
  566. throw new HTTPStatusException(HTTPStatus.badRequest);
  567. // https://tools.ietf.org/html/rfc7233
  568. // Range can be in form "-\d", "\d-" or "\d-\d"
  569. try {
  570. if (s[0].length) {
  571. ret.min = s[0].to!ulong;
  572. ret.max = s[1].length ? s[1].to!ulong + 1 : file_size;
  573. } else if (s[1].length) {
  574. ret.min = file_size - min(s[1].to!ulong, file_size);
  575. ret.max = file_size;
  576. } else {
  577. throw new HTTPStatusException(HTTPStatus.badRequest);
  578. }
  579. } catch (ConvException) {
  580. throw new HTTPStatusException(HTTPStatus.badRequest);
  581. }
  582. if (ret.max > file_size) ret.max = file_size;
  583. if (ret.min >= ret.max) {
  584. res.headers["Content-Range"] = "bytes */%s".format(file_size);
  585. throw new HTTPStatusException(HTTPStatus.rangeNotSatisfiable);
  586. }
  587. return ret;
  588. }
  589. unittest {
  590. auto res = createTestHTTPServerResponse();
  591. assertThrown(parseRangeHeader("bytes=2-1", 10, res));
  592. assertThrown(parseRangeHeader("bytes=10-10", 10, res));
  593. assertThrown(parseRangeHeader("bytes=0-0", 0, res));
  594. assert(parseRangeHeader("bytes=10-20", 100, res) == RangeSpec(10, 21));
  595. assert(parseRangeHeader("bytes=0-0", 1, res) == RangeSpec(0, 1));
  596. assert(parseRangeHeader("bytes=0-20", 2, res) == RangeSpec(0, 2));
  597. assert(parseRangeHeader("bytes=1-20", 2, res) == RangeSpec(1, 2));
  598. }
  599. private struct RangeSpec {
  600. ulong min, max;
  601. }