server.d 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014
  1. /**
  2. A HTTP 1.1/1.0 server implementation.
  3. Copyright: © 2012-2017 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, Jan Krüger, Ilya Shipunov
  6. */
  7. module vibe.http.server;
  8. public import vibe.core.net;
  9. public import vibe.http.common;
  10. public import vibe.http.session;
  11. import vibe.container.internal.appender : FixedAppender;
  12. import vibe.container.internal.utilallocator;
  13. import vibe.core.file;
  14. import vibe.core.log;
  15. import vibe.data.json;
  16. import vibe.http.dist;
  17. import vibe.http.log;
  18. import vibe.inet.message;
  19. import vibe.inet.url;
  20. import vibe.inet.webform;
  21. import vibe.internal.interfaceproxy : InterfaceProxy;
  22. import vibe.stream.counting;
  23. import vibe.stream.operations;
  24. import vibe.stream.tls;
  25. import vibe.stream.wrapper : ConnectionProxyStream, createConnectionProxyStream, createConnectionProxyStreamFL;
  26. import vibe.textfilter.urlencode;
  27. import vibe.internal.freelistref;
  28. import vibe.internal.string : formatAlloc, icmp2;
  29. import core.atomic;
  30. import core.vararg;
  31. //import diet.traits : SafeFilterCallback, dietTraits;
  32. import std.algorithm : canFind, splitter;
  33. import std.array;
  34. import std.conv;
  35. import std.datetime;
  36. import std.encoding : sanitize;
  37. import std.exception;
  38. import std.format;
  39. import std.functional : toDelegate;
  40. import std.string;
  41. import std.traits : ReturnType;
  42. import std.typecons;
  43. import std.uri;
  44. version (VibeNoSSL) enum HaveNoTLS = true;
  45. else version (Have_botan) enum HaveNoTLS = false;
  46. else version (Have_openssl) enum HaveNoTLS = false;
  47. else enum HaveNoTLS = true;
  48. // rm - comment - diet-ng shit
  49. // https://github.com/rejectedsoftware/diet-ng/blob/v1.8.4/source/diet/traits.d#L159
  50. /**************************************************************************************************/
  51. /* Public functions */
  52. /**************************************************************************************************/
  53. /**
  54. Starts a HTTP server listening on the specified port.
  55. request_handler will be called for each HTTP request that is made. The
  56. res parameter of the callback then has to be filled with the response
  57. data.
  58. request_handler can be either HTTPServerRequestDelegate/HTTPServerRequestFunction
  59. or a class/struct with a member function 'handleRequest' that has the same
  60. signature.
  61. Note that if the application has been started with the --disthost command line
  62. switch, listenHTTP() will automatically listen on the specified VibeDist host
  63. instead of locally. This allows for a seamless switch from single-host to
  64. multi-host scenarios without changing the code. If you need to listen locally,
  65. use listenHTTPPlain() instead.
  66. Params:
  67. settings = Customizes the HTTP servers functionality (host string or HTTPServerSettings object)
  68. request_handler = This callback is invoked for each incoming request and is responsible
  69. for generating the response.
  70. Returns:
  71. A handle is returned that can be used to stop listening for further HTTP
  72. requests with the supplied settings. Another call to `listenHTTP` can be
  73. used afterwards to start listening again.
  74. */
  75. HTTPListener listenHTTP(Settings)(Settings _settings, HTTPServerRequestDelegate request_handler)
  76. @safe
  77. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  78. // auto-construct HTTPServerSettings
  79. static if (is(Settings == string))
  80. auto settings = new HTTPServerSettings(_settings);
  81. else
  82. alias settings = _settings;
  83. enforce(settings.bindAddresses.length, "Must provide at least one bind address for a HTTP server.");
  84. // if a VibeDist host was specified on the command line, register there instead of listening
  85. // directly.
  86. if (s_distHost.length && !settings.disableDistHost) {
  87. return listenHTTPDist(settings, request_handler, s_distHost, s_distPort);
  88. } else {
  89. return listenHTTPPlain(settings, request_handler);
  90. }
  91. }
  92. /// ditto
  93. HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestFunction request_handler)
  94. @safe
  95. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  96. return listenHTTP(settings, () @trusted { return toDelegate(request_handler); } ());
  97. }
  98. /// ditto
  99. HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestHandler request_handler)
  100. @safe
  101. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  102. return listenHTTP(settings, &request_handler.handleRequest);
  103. }
  104. /// ditto
  105. HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestDelegateS request_handler)
  106. @safe
  107. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  108. return listenHTTP(settings, cast(HTTPServerRequestDelegate)request_handler);
  109. }
  110. /// ditto
  111. HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestFunctionS request_handler)
  112. @safe
  113. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  114. return listenHTTP(settings, () @trusted { return toDelegate(request_handler); } ());
  115. }
  116. /// ditto
  117. HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestHandlerS request_handler)
  118. @safe
  119. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  120. return listenHTTP(settings, &request_handler.handleRequest);
  121. }
  122. /// Scheduled for deprecation - use a `@safe` callback instead.
  123. HTTPListener listenHTTP(Settings)(Settings settings, void delegate(HTTPServerRequest, HTTPServerResponse) @system request_handler)
  124. @system
  125. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  126. return listenHTTP(settings, (req, res) @trusted => request_handler(req, res));
  127. }
  128. /// ditto
  129. HTTPListener listenHTTP(Settings)(Settings settings, void function(HTTPServerRequest, HTTPServerResponse) @system request_handler)
  130. @system
  131. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  132. return listenHTTP(settings, (req, res) @trusted => request_handler(req, res));
  133. }
  134. /// ditto
  135. HTTPListener listenHTTP(Settings)(Settings settings, void delegate(scope HTTPServerRequest, scope HTTPServerResponse) @system request_handler)
  136. @system
  137. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  138. return listenHTTP(settings, (scope req, scope res) @trusted => request_handler(req, res));
  139. }
  140. /// ditto
  141. HTTPListener listenHTTP(Settings)(Settings settings, void function(scope HTTPServerRequest, scope HTTPServerResponse) @system request_handler)
  142. @system
  143. if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
  144. return listenHTTP(settings, (scope req, scope res) @trusted => request_handler(req, res));
  145. }
  146. unittest
  147. {
  148. void test()
  149. {
  150. static void testSafeFunction(HTTPServerRequest req, HTTPServerResponse res) @safe {}
  151. listenHTTP("0.0.0.0:8080", &testSafeFunction);
  152. listenHTTP(":8080", new class HTTPServerRequestHandler {
  153. void handleRequest(HTTPServerRequest req, HTTPServerResponse res) @safe {}
  154. });
  155. listenHTTP(":8080", (req, res) {});
  156. static void testSafeFunctionS(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
  157. listenHTTP(":8080", &testSafeFunctionS);
  158. void testSafeDelegateS(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
  159. listenHTTP(":8080", &testSafeDelegateS);
  160. listenHTTP(":8080", new class HTTPServerRequestHandler {
  161. void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
  162. });
  163. listenHTTP(":8080", (scope req, scope res) {});
  164. }
  165. }
  166. /** Treats an existing connection as an HTTP connection and processes incoming
  167. requests.
  168. After all requests have been processed, the connection will be closed and
  169. the function returns to the caller.
  170. Params:
  171. connection = The stream to treat as an incoming HTTP client connection.
  172. context = Information about the incoming listener and available
  173. virtual hosts
  174. */
  175. void handleHTTPConnection(TCPConnection connection, HTTPServerContext context)
  176. @safe {
  177. import vibe.http.internal.http1.server : handleHTTP1Connection;
  178. import vibe.http.internal.http2.server : handleHTTP2Connection;
  179. import vibe.http.internal.http2.settings : HTTP2ServerContext, HTTP2Settings;
  180. static if (HaveNoTLS) {
  181. alias TLSStreamType = Stream;
  182. } else {
  183. alias TLSStreamType = ReturnType!(createTLSStreamFL!(InterfaceProxy!Stream));
  184. }
  185. InterfaceProxy!Stream http_stream;
  186. http_stream = connection;
  187. scope (exit) connection.close();
  188. // check wether the client's address is banned
  189. foreach (ref virtual_host; context.m_virtualHosts)
  190. if ((virtual_host.settings.rejectConnectionPredicate !is null) &&
  191. virtual_host.settings.rejectConnectionPredicate(connection.remoteAddress()))
  192. return;
  193. // Set NODELAY to true, to avoid delays caused by sending the response
  194. // header and body in separate chunks. Note that to avoid other performance
  195. // issues (caused by tiny packets), this requires using an output buffer in
  196. // the event driver, which is the case at least for the legacy libevent
  197. // based driver.
  198. connection.tcpNoDelay = true;
  199. TLSStreamType tls_stream;
  200. if (!connection.waitForData(10.seconds())) {
  201. logDebug("Client didn't send the initial request in a timely manner. Closing connection.");
  202. return;
  203. }
  204. // If this is a HTTPS server, initiate TLS
  205. if (context.tlsContext) {
  206. static if (HaveNoTLS) assert(false, "No TLS support compiled in.");
  207. else {
  208. logDebug("Accept TLS connection: %s", context.tlsContext.kind);
  209. // TODO: reverse DNS lookup for peer_name of the incoming connection for TLS client certificate verification purposes
  210. tls_stream = createTLSStreamFL(http_stream, context.tlsContext, TLSStreamState.accepting, null, connection.remoteAddress);
  211. Nullable!string proto = tls_stream.alpn;
  212. if(!proto.isNull && proto == "h2" && (context.m_virtualHosts[0].settings.options & HTTPServerOption.enableHTTP2)) {
  213. logTrace("Using HTTP/2 as requested per ALPN");
  214. HTTP2Settings settings;
  215. auto h2context = new HTTP2ServerContext(context, settings);
  216. handleHTTP2Connection(tls_stream, connection, h2context);
  217. return;
  218. }
  219. http_stream = tls_stream;
  220. }
  221. }
  222. handleHTTP1Connection(connection, tls_stream, http_stream, context);
  223. logTrace("Done handling connection.");
  224. }
  225. /+
  226. /**
  227. Provides a HTTP request handler that responds with a static Diet template.
  228. */
  229. @property HTTPServerRequestDelegateS staticTemplate(string template_file)()
  230. {
  231. return (scope HTTPServerRequest req, scope HTTPServerResponse res){
  232. res.render!(template_file, req);
  233. };
  234. }
  235. +/
  236. /**
  237. Provides a HTTP request handler that responds with a static redirection to the specified URL.
  238. Params:
  239. url = The URL to redirect to
  240. status = Redirection status to use $(LPAREN)by default this is $(D HTTPStatus.found)$(RPAREN).
  241. Returns:
  242. Returns a $(D HTTPServerRequestDelegate) that performs the redirect
  243. */
  244. HTTPServerRequestDelegate staticRedirect(string url, HTTPStatus status = HTTPStatus.found)
  245. @safe {
  246. return (HTTPServerRequest req, HTTPServerResponse res){
  247. res.redirect(url, status);
  248. };
  249. }
  250. /// ditto
  251. HTTPServerRequestDelegate staticRedirect(URL url, HTTPStatus status = HTTPStatus.found)
  252. @safe {
  253. return (HTTPServerRequest req, HTTPServerResponse res){
  254. res.redirect(url, status);
  255. };
  256. }
  257. ///
  258. unittest {
  259. import vibe.http.router;
  260. void test()
  261. {
  262. auto router = new URLRouter;
  263. router.get("/old_url", staticRedirect("http://example.org/new_url", HTTPStatus.movedPermanently));
  264. listenHTTP(new HTTPServerSettings, router);
  265. }
  266. }
  267. /**
  268. Sets a VibeDist host to register with.
  269. */
  270. void setVibeDistHost(string host, ushort port)
  271. @safe {
  272. s_distHost = host;
  273. s_distPort = port;
  274. }
  275. /**
  276. Renders the given Diet template and makes all ALIASES available to the template.
  277. You can call this function as a pseudo-member of `HTTPServerResponse` using
  278. D's uniform function call syntax.
  279. See_also: `diet.html.compileHTMLDietFile`
  280. Examples:
  281. ---
  282. string title = "Hello, World!";
  283. int pageNumber = 1;
  284. res.render!("mytemplate.dt", title, pageNumber);
  285. ---
  286. */
  287. // comment cause no diet
  288. /+
  289. @property void render(string template_file, ALIASES...)(HTTPServerResponse res)
  290. {
  291. res.contentType = "text/html; charset=UTF-8";
  292. version (VibeUseOldDiet)
  293. pragma(msg, "VibeUseOldDiet is not supported anymore. Please undefine in the package recipe.");
  294. import vibe.stream.wrapper : streamOutputRange;
  295. //import diet.html : compileHTMLDietFile;
  296. auto output = streamOutputRange!1024(res.bodyWriter);
  297. compileHTMLDietFile!(template_file, ALIASES, DefaultDietFilters)(output);
  298. }
  299. /**
  300. Provides the default `css`, `javascript`, `markdown` and `htmlescape` filters
  301. */
  302. @dietTraits
  303. struct DefaultDietFilters {
  304. import diet.html : HTMLOutputStyle;
  305. //import diet.traits : SafeFilterCallback;
  306. import std.string : splitLines;
  307. version (VibeOutputCompactHTML) enum HTMLOutputStyle htmlOutputStyle = HTMLOutputStyle.compact;
  308. else enum HTMLOutputStyle htmlOutputStyle = HTMLOutputStyle.pretty;
  309. static string filterCss(I)(I text, size_t indent = 0)
  310. {
  311. auto lines = splitLines(text);
  312. string indent_string = "\n";
  313. while (indent-- > 0) indent_string ~= '\t';
  314. string ret = indent_string~"<style><!--";
  315. indent_string = indent_string ~ '\t';
  316. foreach (ln; lines) ret ~= indent_string ~ ln;
  317. indent_string = indent_string[0 .. $-1];
  318. ret ~= indent_string ~ "--></style>";
  319. return ret;
  320. }
  321. static string filterJavascript(I)(I text, size_t indent = 0)
  322. {
  323. auto lines = splitLines(text);
  324. string indent_string = "\n";
  325. while (indent-- > 0) indent_string ~= '\t';
  326. string ret = indent_string~"<script>";
  327. ret ~= indent_string~'\t' ~ "//<![CDATA[";
  328. foreach (ln; lines) ret ~= indent_string ~ '\t' ~ ln;
  329. ret ~= indent_string ~ '\t' ~ "//]]>" ~ indent_string ~ "</script>";
  330. return ret;
  331. }
  332. static string filterMarkdown(I)(I text)
  333. {
  334. import vibe.textfilter.markdown : markdown = filterMarkdown;
  335. // TODO: indent
  336. return markdown(text);
  337. }
  338. static string filterHtmlescape(I)(I text)
  339. {
  340. import vibe.textfilter.html : htmlEscape;
  341. // TODO: indent
  342. return htmlEscape(text);
  343. }
  344. static this()
  345. {
  346. filters["css"] = (in input, scope output) { output(filterCss(input)); };
  347. filters["javascript"] = (in input, scope output) { output(filterJavascript(input)); };
  348. filters["markdown"] = (in input, scope output) { output(filterMarkdown(() @trusted { return cast(string)input; } ())); };
  349. filters["htmlescape"] = (in input, scope output) { output(filterHtmlescape(input)); };
  350. }
  351. static SafeFilterCallback[string] filters;
  352. }
  353. unittest {
  354. static string compile(string diet)() {
  355. import std.array : appender;
  356. import std.string : strip;
  357. import diet.html : compileHTMLDietString;
  358. auto dst = appender!string;
  359. dst.compileHTMLDietString!(diet, DefaultDietFilters);
  360. return strip(cast(string)(dst.data));
  361. }
  362. assert(compile!":css .test" == "<style><!--\n\t.test\n--></style>");
  363. assert(compile!":javascript test();" == "<script>\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
  364. assert(compile!":markdown **test**" == "<p><strong>test</strong>\n</p>");
  365. assert(compile!":htmlescape <test>" == "&lt;test&gt;");
  366. assert(compile!":css !{\".test\"}" == "<style><!--\n\t.test\n--></style>");
  367. assert(compile!":javascript !{\"test();\"}" == "<script>\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
  368. assert(compile!":markdown !{\"**test**\"}" == "<p><strong>test</strong>\n</p>");
  369. assert(compile!":htmlescape !{\"<test>\"}" == "&lt;test&gt;");
  370. assert(compile!":javascript\n\ttest();" == "<script>\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
  371. }
  372. +/
  373. /**
  374. Creates a HTTPServerRequest suitable for writing unit tests.
  375. */
  376. HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method = HTTPMethod.GET, InputStream data = null)
  377. @safe {
  378. InetHeaderMap headers;
  379. return createTestHTTPServerRequest(url, method, headers, data);
  380. }
  381. /// ditto
  382. HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method, InetHeaderMap headers, InputStream data = null)
  383. @safe {
  384. auto tls = url.schema == "https";
  385. auto ret = new HTTPServerRequest(Clock.currTime(UTC()), url.port ? url.port : tls ? 443 : 80);
  386. ret.m_settings = new HTTPServerSettings;
  387. ret.requestPath = url.path;
  388. ret.queryString = url.queryString;
  389. ret.username = url.username;
  390. ret.password = url.password;
  391. ret.requestURI = url.localURI;
  392. ret.method = method;
  393. ret.tls = tls;
  394. ret.headers = headers;
  395. ret.bodyReader = data;
  396. return ret;
  397. }
  398. /**
  399. Creates a HTTPServerResponse suitable for writing unit tests.
  400. Params:
  401. data_sink = Optional output stream that captures the data that gets
  402. written to the response
  403. session_store = Optional session store to use when sessions are involved
  404. data_mode = If set to `TestHTTPResponseMode.bodyOnly`, only the body
  405. contents get written to `data_sink`. Otherwise the raw response
  406. including the HTTP header is written.
  407. */
  408. HTTPServerResponse createTestHTTPServerResponse(OutputStream data_sink = null,
  409. SessionStore session_store = null,
  410. TestHTTPResponseMode data_mode = TestHTTPResponseMode.plain)
  411. @safe {
  412. import vibe.stream.wrapper : createProxyStream;
  413. import vibe.http.internal.http1.server : HTTP1ServerExchange;
  414. HTTPServerSettings settings;
  415. if (session_store) {
  416. settings = new HTTPServerSettings;
  417. settings.sessionStore = session_store;
  418. }
  419. final class TestExchange : HTTP1ServerExchange {
  420. this(StreamProxy conn, OutputStream body_writer)
  421. {
  422. super(conn, ConnectionStreamProxy.init);
  423. m_bodyWriter = body_writer;
  424. }
  425. }
  426. StreamProxy outstr;
  427. if (data_sink && data_mode == TestHTTPResponseMode.plain)
  428. outstr = createProxyStream(Stream.init, data_sink);
  429. else outstr = createProxyStream(Stream.init, nullSink);
  430. auto exchange = new TestExchange(outstr, data_sink && data_mode == TestHTTPResponseMode.bodyOnly ? data_sink : null);
  431. auto ret = new HTTPServerResponse(exchange, settings, () @trusted { return vibeThreadAllocator(); } ());
  432. return ret;
  433. }
  434. /**************************************************************************************************/
  435. /* Public types */
  436. /**************************************************************************************************/
  437. /// Delegate based request handler
  438. alias HTTPServerRequestDelegate = void delegate(HTTPServerRequest req, HTTPServerResponse res) @safe;
  439. /// Static function based request handler
  440. alias HTTPServerRequestFunction = void function(HTTPServerRequest req, HTTPServerResponse res) @safe;
  441. /// Interface for class based request handlers
  442. interface HTTPServerRequestHandler {
  443. /// Handles incoming HTTP requests
  444. void handleRequest(HTTPServerRequest req, HTTPServerResponse res) @safe ;
  445. }
  446. /// Delegate based request handler with scoped parameters
  447. alias HTTPServerRequestDelegateS = void delegate(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
  448. /// Static function based request handler with scoped parameters
  449. alias HTTPServerRequestFunctionS = void function(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
  450. /// Interface for class based request handlers with scoped parameters
  451. interface HTTPServerRequestHandlerS {
  452. /// Handles incoming HTTP requests
  453. void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
  454. }
  455. unittest {
  456. static assert(is(HTTPServerRequestDelegateS : HTTPServerRequestDelegate));
  457. static assert(is(HTTPServerRequestFunctionS : HTTPServerRequestFunction));
  458. }
  459. /// Aggregates all information about an HTTP error status.
  460. final class HTTPServerErrorInfo {
  461. /// The HTTP status code
  462. int code;
  463. /// The error message
  464. string message;
  465. /// Extended error message with debug information such as a stack trace
  466. string debugMessage;
  467. /// The error exception, if any
  468. Throwable exception;
  469. }
  470. /// Delegate type used for user defined error page generator callbacks.
  471. alias HTTPServerErrorPageHandler = void delegate(HTTPServerRequest req, HTTPServerResponse res, HTTPServerErrorInfo error) @safe;
  472. enum TestHTTPResponseMode {
  473. plain,
  474. bodyOnly
  475. }
  476. /**
  477. Specifies optional features of the HTTP server.
  478. Disabling unneeded features can speed up the server or reduce its memory usage.
  479. Note that the options `parseFormBody`, `parseJsonBody` and `parseMultiPartBody`
  480. will also drain the `HTTPServerRequest.bodyReader` stream whenever a request
  481. body with form or JSON data is encountered.
  482. */
  483. enum HTTPServerOption {
  484. none = 0,
  485. /** Enables stack traces (`HTTPServerErrorInfo.debugMessage`).
  486. Note that generating the stack traces are generally a costly
  487. operation that should usually be avoided in production
  488. environments. It can also reveal internal information about
  489. the application, such as function addresses, which can
  490. help an attacker to abuse possible security holes.
  491. */
  492. errorStackTraces = 1<<7,
  493. /// Enable port reuse in `listenTCP()`
  494. reusePort = 1<<8,
  495. /// Enable address reuse in `listenTCP()`
  496. reuseAddress = 1<<10,
  497. /// Enable *experimental* HTTP/2 support
  498. enableHTTP2 = 1<<11,
  499. /** The default set of options.
  500. Includes all parsing options, as well as the `errorStackTraces`
  501. option if the code is compiled in debug mode.
  502. */
  503. defaults = () { auto ret = reuseAddress; debug ret |= errorStackTraces; return ret; } (),
  504. }
  505. /**
  506. Contains all settings for configuring a basic HTTP server.
  507. The defaults are sufficient for most normal uses.
  508. */
  509. final class HTTPServerSettings {
  510. /** The port on which the HTTP server is listening.
  511. The default value is 80. If you are running a TLS enabled server you may want to set this
  512. to 443 instead.
  513. Using a value of `0` instructs the server to use any available port on
  514. the given `bindAddresses` the actual addresses and ports can then be
  515. queried with `TCPListener.bindAddresses`.
  516. */
  517. ushort port = 80;
  518. /** The interfaces on which the HTTP server is listening.
  519. By default, the server will listen on all IPv4 and IPv6 interfaces.
  520. */
  521. string[] bindAddresses = ["::", "0.0.0.0"];
  522. /** Determines the server host name.
  523. If multiple servers are listening on the same port, the host name will determine which one
  524. gets a request.
  525. */
  526. string hostName;
  527. /** Provides a way to reject incoming connections as early as possible.
  528. Allows to ban and unban network addresses and reduce the impact of DOS
  529. attacks.
  530. If the callback returns `true` for a specific `NetworkAddress`,
  531. then all incoming requests from that address will be rejected.
  532. */
  533. RejectConnectionPredicate rejectConnectionPredicate;
  534. /** Configures optional features of the HTTP server
  535. Disabling unneeded features can improve performance or reduce the server
  536. load in case of invalid or unwanted requests (DoS). By default,
  537. HTTPServerOption.defaults is used.
  538. */
  539. HTTPServerOption options = HTTPServerOption.defaults;
  540. /** Time of a request after which the connection is closed with an error; not supported yet
  541. The default limit of 0 means that the request time is not limited.
  542. */
  543. Duration maxRequestTime = 0.seconds;
  544. /** Maximum time between two request on a keep-alive connection
  545. The default value is 10 seconds.
  546. */
  547. Duration keepAliveTimeout = 10.seconds;
  548. /// Maximum number of transferred bytes per request after which the connection is closed with
  549. /// an error
  550. ulong maxRequestSize = 2097152;
  551. /// Maximum number of transferred bytes for the request header. This includes the request line
  552. /// the url and all headers.
  553. ulong maxRequestHeaderSize = 8192;
  554. /// Maximum number of bytes in a single line in the request header.
  555. size_t maxRequestHeaderLineSize = 4096;
  556. /// Sets a custom handler for displaying error pages for HTTP errors
  557. @property HTTPServerErrorPageHandler errorPageHandler() @safe { return errorPageHandler_; }
  558. /// ditto
  559. @property void errorPageHandler(HTTPServerErrorPageHandler del) @safe { errorPageHandler_ = del; }
  560. /// Scheduled for deprecation - use a `@safe` callback instead.
  561. @property void errorPageHandler(void delegate(HTTPServerRequest, HTTPServerResponse, HTTPServerErrorInfo) @system del)
  562. @system {
  563. this.errorPageHandler = (req, res, err) @trusted { del(req, res, err); };
  564. }
  565. package HTTPServerErrorPageHandler errorPageHandler_ = null;
  566. /// If set, a HTTPS server will be started instead of plain HTTP.
  567. TLSContext tlsContext;
  568. /// Session management is enabled if a session store instance is provided
  569. SessionStore sessionStore;
  570. string sessionIdCookie = "vibe.session_id";
  571. /// Session options to use when initializing a new session.
  572. SessionOption sessionOptions = SessionOption.httpOnly;
  573. ///
  574. import vibe.core.core : vibeVersionString;
  575. string serverString = "vibe.d/" ~ vibeVersionString;
  576. /** Specifies the format used for the access log.
  577. The log format is given using the Apache server syntax. By default NCSA combined is used.
  578. ---
  579. "%h - %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\""
  580. ---
  581. */
  582. string accessLogFormat = "%h - %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"";
  583. /// Spefifies the name of a file to which access log messages are appended.
  584. string accessLogFile = "";
  585. /// If set, access log entries will be output to the console.
  586. bool accessLogToConsole = false;
  587. /** Specifies a custom access logger instance.
  588. */
  589. HTTPLogger accessLogger;
  590. /// Returns a duplicate of the settings object.
  591. @property HTTPServerSettings dup()
  592. @safe {
  593. auto ret = new HTTPServerSettings;
  594. foreach (mem; __traits(allMembers, HTTPServerSettings)) {
  595. static if (mem == "sslContext") {}
  596. else static if (mem == "bindAddresses") ret.bindAddresses = bindAddresses.dup;
  597. else static if (__traits(compiles, __traits(getMember, ret, mem) = __traits(getMember, this, mem)))
  598. __traits(getMember, ret, mem) = __traits(getMember, this, mem);
  599. }
  600. return ret;
  601. }
  602. /// Disable support for VibeDist and instead start listening immediately.
  603. bool disableDistHost = false;
  604. /** Responds to "Accept-Encoding" by using compression if possible.
  605. Compression can also be manually enabled by setting the
  606. "Content-Encoding" header of the HTTP response appropriately before
  607. sending the response body.
  608. This setting is disabled by default. Also note that there are still some
  609. known issues with the GZIP compression code.
  610. */
  611. bool useCompressionIfPossible = false;
  612. /** Interval between WebSocket ping frames.
  613. The default value is 60 seconds; set to Duration.zero to disable pings.
  614. */
  615. Duration webSocketPingInterval = 60.seconds;
  616. /** Constructs a new settings object with default values.
  617. */
  618. this() @safe {}
  619. /** Constructs a new settings object with a custom bind interface and/or port.
  620. The syntax of `bind_string` is `[<IP address>][:<port>]`, where either of
  621. the two parts can be left off. IPv6 addresses must be enclosed in square
  622. brackets, as they would within a URL.
  623. Throws:
  624. An exception is thrown if `bind_string` is malformed.
  625. */
  626. this(string bind_string)
  627. @safe {
  628. this();
  629. if (bind_string.startsWith('[')) {
  630. auto idx = bind_string.indexOf(']');
  631. enforce(idx > 0, "Missing closing bracket for IPv6 address.");
  632. bindAddresses = [bind_string[1 .. idx]];
  633. bind_string = bind_string[idx+1 .. $];
  634. enforce(bind_string.length == 0 || bind_string.startsWith(':'),
  635. "Only a colon may follow the IPv6 address.");
  636. }
  637. auto idx = bind_string.indexOf(':');
  638. if (idx < 0) {
  639. if (bind_string.length > 0) bindAddresses = [bind_string];
  640. } else {
  641. if (idx > 0) bindAddresses = [bind_string[0 .. idx]];
  642. port = bind_string[idx+1 .. $].to!ushort;
  643. }
  644. }
  645. ///
  646. unittest {
  647. auto s = new HTTPServerSettings(":8080");
  648. assert(s.bindAddresses == ["::", "0.0.0.0"]); // default bind addresses
  649. assert(s.port == 8080);
  650. s = new HTTPServerSettings("123.123.123.123");
  651. assert(s.bindAddresses == ["123.123.123.123"]);
  652. assert(s.port == 80);
  653. s = new HTTPServerSettings("[::1]:443");
  654. assert(s.bindAddresses == ["::1"]);
  655. assert(s.port == 443);
  656. }
  657. }
  658. /// Callback type used to determine whether to reject incoming connections
  659. alias RejectConnectionPredicate = bool delegate (in NetworkAddress) @safe nothrow;
  660. /**
  661. Options altering how sessions are created.
  662. Multiple values can be or'ed together.
  663. See_Also: HTTPServerResponse.startSession
  664. */
  665. enum SessionOption {
  666. /// No options.
  667. none = 0,
  668. /** Instructs the browser to disallow accessing the session ID from JavaScript.
  669. See_Also: Cookie.httpOnly
  670. */
  671. httpOnly = 1<<0,
  672. /** Instructs the browser to disallow sending the session ID over
  673. unencrypted connections.
  674. By default, the type of the connection on which the session is started
  675. will be used to determine if secure or noSecure is used.
  676. See_Also: noSecure, Cookie.secure
  677. */
  678. secure = 1<<1,
  679. /** Instructs the browser to allow sending the session ID over unencrypted
  680. connections.
  681. By default, the type of the connection on which the session is started
  682. will be used to determine if secure or noSecure is used.
  683. See_Also: secure, Cookie.secure
  684. */
  685. noSecure = 1<<2,
  686. /**
  687. Instructs the browser to allow sending this cookie along with cross-site requests.
  688. By default, the protection is `strict`. This flag allows to set it to `lax`.
  689. The strict value will prevent the cookie from being sent by the browser
  690. to the target site in all cross-site browsing context,
  691. even when following a regular link.
  692. */
  693. noSameSiteStrict = 1<<3,
  694. }
  695. /**
  696. Represents a HTTP request as received by the server side.
  697. */
  698. final class HTTPServerRequest : HTTPRequest {
  699. import std.variant : Variant;
  700. import vibe.container.dictionarylist : DictionaryList;
  701. package {
  702. SysTime m_timeCreated;
  703. HTTPServerSettings m_settings;
  704. ushort m_port;
  705. string m_peer;
  706. // lazily parsed request components
  707. Nullable!string m_path;
  708. Nullable!CookieValueMap m_cookies;
  709. Nullable!FormFields m_query;
  710. Nullable!Json m_json;
  711. Nullable!FormFields m_form;
  712. FilePartFormFields m_files;
  713. }
  714. /// The IP address of the client
  715. NetworkAddress clientAddress;
  716. /// Determines if the request should be logged to the access log file.
  717. bool noLog;
  718. /// Determines if the request was issued over an TLS encrypted channel.
  719. bool tls;
  720. /** Information about the TLS certificate provided by the client.
  721. Remarks: This field is only set if `tls` is true, and the peer
  722. presented a client certificate.
  723. */
  724. TLSCertificateInformation clientCertificate;
  725. /** The path part of the requested URI.
  726. */
  727. InetPath requestPath;
  728. /** The user name part of the URL, if present.
  729. */
  730. string username;
  731. /** The _password part of the URL, if present.
  732. */
  733. string password;
  734. /** The _query string part of the URL.
  735. */
  736. string queryString;
  737. /** A map of general parameters for the request.
  738. This map is supposed to be used by middleware functionality to store
  739. information for later stages. For example vibe.http.router.URLRouter uses this map
  740. to store the value of any named placeholders.
  741. */
  742. DictionaryList!(string, true, 8) params;
  743. /** A map of context items for the request.
  744. This is especially useful for passing application specific data down
  745. the chain of processors along with the request itself.
  746. For example, a generic route may be defined to check user login status,
  747. if the user is logged in, add a reference to user specific data to the
  748. context.
  749. This is implemented with `std.variant.Variant` to allow any type of data.
  750. */
  751. DictionaryList!(Variant, true, 2) context;
  752. /** Supplies the request body as a stream.
  753. Note that when certain server options are set (such as
  754. HTTPServerOption.parseJsonBody) and a matching request was sent,
  755. the returned stream will be empty. If needed, remove those
  756. options and do your own processing of the body when launching
  757. the server. HTTPServerOption has a list of all options that affect
  758. the request body.
  759. */
  760. InputStream bodyReader;
  761. /** The current Session object.
  762. This field is set if HTTPServerResponse.startSession() has been called
  763. on a previous response and if the client has sent back the matching
  764. cookie.
  765. Remarks: Requires the HTTPServerOption.parseCookies option.
  766. */
  767. Session session;
  768. this(SysTime time, ushort port)
  769. @safe scope {
  770. m_timeCreated = time.toUTC();
  771. m_port = port;
  772. }
  773. /// The IP address of the client in string form
  774. @property string peer()
  775. @safe nothrow scope {
  776. if (!m_peer) {
  777. version (Have_vibe_core) {} else scope (failure) assert(false);
  778. // store the IP address (IPv4 addresses forwarded over IPv6 are stored in IPv4 format)
  779. auto peer_address_string = this.clientAddress.toString();
  780. if (peer_address_string.startsWith("::ffff:") && peer_address_string[7 .. $].indexOf(':') < 0)
  781. m_peer = peer_address_string[7 .. $];
  782. else m_peer = peer_address_string;
  783. }
  784. return m_peer;
  785. }
  786. /** The _path part of the URL.
  787. Note that this function contains the decoded version of the
  788. requested path, which can yield incorrect results if the path
  789. contains URL encoded path separators. Use `requestPath` instead to
  790. get an encoding-aware representation.
  791. */
  792. deprecated("Use .requestPath instead")
  793. string path()
  794. @safe scope {
  795. if (m_path.isNull)
  796. m_path = urlDecode(requestPath.toString);
  797. return m_path.get;
  798. }
  799. /** Contains the list of cookies that are stored on the client.
  800. Note that the a single cookie name may occur multiple times if multiple
  801. cookies have that name but different paths or domains that all match
  802. the request URI. By default, the first cookie will be returned, which is
  803. the or one of the cookies with the closest path match.
  804. */
  805. @property ref CookieValueMap cookies()
  806. @safe return {
  807. if (m_cookies.isNull) {
  808. m_cookies = CookieValueMap.init;
  809. if (auto pv = "cookie" in headers)
  810. parseCookies(*pv, m_cookies.get);
  811. }
  812. return m_cookies.get;
  813. }
  814. /** Contains all _form fields supplied using the _query string.
  815. The fields are stored in the same order as they are received.
  816. */
  817. @property ref FormFields query()
  818. @safe return {
  819. if (m_query.isNull) {
  820. m_query = FormFields.init;
  821. parseURLEncodedForm(queryString, m_query.get);
  822. }
  823. return m_query.get;
  824. }
  825. /** Contains the parsed Json for a JSON request.
  826. A JSON request must have the Content-Type "application/json" or "application/vnd.api+json".
  827. */
  828. @property ref Json json()
  829. @safe return {
  830. if (m_json.isNull) {
  831. auto splitter = contentType.splitter(';');
  832. auto ctype = splitter.empty ? "" : splitter.front;
  833. if (icmp2(ctype, "application/json") == 0 || icmp2(ctype, "application/vnd.api+json") == 0) {
  834. auto bodyStr = bodyReader.readAllUTF8();
  835. if (!bodyStr.empty) m_json = parseJson(bodyStr);
  836. else m_json = Json.undefined;
  837. } else {
  838. m_json = Json.undefined;
  839. }
  840. }
  841. return m_json.get;
  842. }
  843. /// Get the json body when there is no content-type header
  844. unittest {
  845. assert(createTestHTTPServerRequest(URL("http://localhost/")).json.type == Json.Type.undefined);
  846. }
  847. /** Contains the parsed parameters of a HTML POST _form request.
  848. The fields are stored in the same order as they are received.
  849. Remarks:
  850. A form request must either have the Content-Type
  851. "application/x-www-form-urlencoded" or "multipart/form-data".
  852. */
  853. @property ref FormFields form()
  854. @safe return {
  855. if (m_form.isNull)
  856. parseFormAndFiles();
  857. return m_form.get;
  858. }
  859. /** Contains information about any uploaded file for a HTML _form request.
  860. */
  861. @property ref FilePartFormFields files()
  862. @safe return {
  863. // m_form and m_files are parsed in one step
  864. if (m_form.isNull) {
  865. parseFormAndFiles();
  866. assert(!m_form.isNull);
  867. }
  868. return m_files;
  869. }
  870. /** Time when this request started processing.
  871. */
  872. @property SysTime timeCreated() const @safe scope { return m_timeCreated; }
  873. /** The full URL that corresponds to this request.
  874. The host URL includes the protocol, host and optionally the user
  875. and password that was used for this request. This field is useful to
  876. construct self referencing URLs.
  877. Note that the port is currently not set, so that this only works if
  878. the standard port is used.
  879. */
  880. @property URL fullURL()
  881. const @safe scope {
  882. URL url;
  883. auto xfh = this.headers.get("X-Forwarded-Host");
  884. auto xfp = this.headers.get("X-Forwarded-Port");
  885. auto xfpr = this.headers.get("X-Forwarded-Proto");
  886. // Set URL host segment.
  887. if (xfh.length) {
  888. url.host = xfh;
  889. } else if (!this.host.empty) {
  890. url.host = this.host;
  891. } else if (!m_settings.hostName.empty) {
  892. url.host = m_settings.hostName;
  893. } else {
  894. url.host = m_settings.bindAddresses[0];
  895. }
  896. // Set URL schema segment.
  897. if (xfpr.length) {
  898. url.schema = xfpr;
  899. } else if (this.tls) {
  900. url.schema = "https";
  901. } else {
  902. url.schema = "http";
  903. }
  904. // Set URL port segment.
  905. if (xfp.length) {
  906. try {
  907. url.port = xfp.to!ushort;
  908. } catch (ConvException) {
  909. // TODO : Consider responding with a 400/etc. error from here.
  910. logWarn("X-Forwarded-Port header was not valid port (%s)", xfp);
  911. }
  912. } else if (!xfh) {
  913. if (url.schema == "https") {
  914. if (m_port != 443U) url.port = m_port;
  915. } else {
  916. if (m_port != 80U) url.port = m_port;
  917. }
  918. }
  919. if (url.host.startsWith('[')) { // handle IPv6 address
  920. auto idx = url.host.indexOf(']');
  921. if (idx >= 0 && idx+1 < url.host.length && url.host[idx+1] == ':')
  922. url.host = url.host[1 .. idx];
  923. } else { // handle normal host names or IPv4 address
  924. auto idx = url.host.indexOf(':');
  925. if (idx >= 0) url.host = url.host[0 .. idx];
  926. }
  927. url.username = this.username;
  928. url.password = this.password;
  929. url.localURI = this.requestURI;
  930. return url;
  931. }
  932. /** The relative path to the root folder.
  933. Using this function instead of absolute URLs for embedded links can be
  934. useful to avoid dead link when the site is piped through a
  935. reverse-proxy.
  936. The returned string always ends with a slash.
  937. */
  938. @property string rootDir()
  939. const @safe scope {
  940. import std.algorithm.searching : count;
  941. import std.range : empty;
  942. auto depth = requestPath.bySegment.count!(s => !s.name.empty);
  943. if (depth > 0 && !requestPath.endsWithSlash) depth--;
  944. return depth == 0 ? "./" : replicate("../", depth);
  945. }
  946. unittest {
  947. assert(createTestHTTPServerRequest(URL("http://localhost/")).rootDir == "./");
  948. assert(createTestHTTPServerRequest(URL("http://localhost/foo")).rootDir == "./");
  949. assert(createTestHTTPServerRequest(URL("http://localhost/foo/")).rootDir == "../");
  950. assert(createTestHTTPServerRequest(URL("http://localhost/foo/bar")).rootDir == "../");
  951. assert(createTestHTTPServerRequest(URL("http://localhost")).rootDir == "./");
  952. }
  953. /** The settings of the server serving this request.
  954. */
  955. package @property const(HTTPServerSettings) serverSettings()
  956. const @safe scope {
  957. return m_settings;
  958. }
  959. private void parseFormAndFiles()
  960. @safe scope {
  961. m_form = FormFields.init;
  962. parseFormData(m_form.get, m_files, headers.get("Content-Type", ""), bodyReader, m_settings.maxRequestHeaderLineSize);
  963. }
  964. }
  965. /**
  966. Represents a HTTP response as sent from the server side.
  967. */
  968. final class HTTPServerResponse : HTTPResponse {
  969. alias Allocator = typeof(vibeThreadAllocator());
  970. package {
  971. HTTPServerExchange m_exchange;
  972. Allocator m_requestAlloc;
  973. HTTPServerSettings m_settings;
  974. Session m_session;
  975. bool m_tls;
  976. SysTime m_timeFinalized;
  977. }
  978. static if (!is(Stream == StreamProxy)) {
  979. deprecated("Use the constructor taking a HTTPServerExchange argument instead")
  980. this(Stream conn, ConnectionStream raw_connection, HTTPServerSettings settings, Allocator req_alloc)
  981. @safe scope {
  982. this(StreamProxy(conn), InterfaceProxy!ConnectionStream(raw_connection), settings, req_alloc);
  983. }
  984. }
  985. deprecated("Use the constructor taking a HTTPServerExchange argument instead")
  986. this(StreamProxy conn, ConnectionStreamProxy raw_connection, HTTPServerSettings settings, Allocator req_alloc)
  987. @safe scope {
  988. import vibe.http.internal.http1.server : HTTP1ServerExchange;
  989. this(new HTTP1ServerExchange(conn, raw_connection), settings, req_alloc);
  990. }
  991. this(HTTPServerExchange exchange, HTTPServerSettings settings, Allocator req_alloc)
  992. @safe {
  993. m_exchange = exchange;
  994. m_settings = settings;
  995. m_requestAlloc = req_alloc;
  996. }
  997. /** Sends a redirect request to the client.
  998. Params:
  999. url = The URL to redirect to
  1000. status = The HTTP redirect status (3xx) to send - by default this is $(D HTTPStatus.found)
  1001. */
  1002. void redirect(string url, int status = HTTPStatus.found)
  1003. @safe scope {
  1004. // Disallow any characters that may influence the header parsing
  1005. enforce(!url.representation.canFind!(ch => ch < 0x20),
  1006. "Control character in redirection URL.");
  1007. statusCode = status;
  1008. headers["Location"] = url;
  1009. writeBody("redirecting...");
  1010. }
  1011. /// ditto
  1012. void redirect(URL url, int status = HTTPStatus.found)
  1013. @safe scope {
  1014. redirect(url.toString(), status);
  1015. }
  1016. ///
  1017. @safe unittest {
  1018. import vibe.http.router;
  1019. void request_handler(HTTPServerRequest req, HTTPServerResponse res)
  1020. {
  1021. res.redirect("http://example.org/some_other_url");
  1022. }
  1023. void test()
  1024. {
  1025. auto router = new URLRouter;
  1026. router.get("/old_url", &request_handler);
  1027. listenHTTP(new HTTPServerSettings, router);
  1028. }
  1029. }
  1030. scope:
  1031. /** Returns the time at which the request was finalized.
  1032. Note that this field will only be set after `finalize` has been called.
  1033. */
  1034. @property SysTime timeFinalized() const @safe { return m_timeFinalized; }
  1035. /** Determines if the HTTP header has already been written.
  1036. */
  1037. @property bool headerWritten() const @safe { return m_exchange.headerWritten; }
  1038. /** Determines if the response does not need a body.
  1039. */
  1040. bool isHeadResponse() const @safe { return m_exchange.isHeadResponse; }
  1041. /** Determines if the response is sent over an encrypted connection.
  1042. */
  1043. bool tls() const @safe { return m_tls; }
  1044. /** Writes the entire response body at once.
  1045. Params:
  1046. data = The data to write as the body contents
  1047. status = Optional response status code to set
  1048. content_type = Optional content type to apply to the response.
  1049. If no content type is given and no "Content-Type" header is
  1050. set in the response, this will default to
  1051. `"application/octet-stream"`.
  1052. See_Also: `HTTPStatusCode`
  1053. */
  1054. void writeBody(in ubyte[] data, string content_type = null)
  1055. @safe {
  1056. if (content_type.length) headers["Content-Type"] = content_type;
  1057. else if ("Content-Type" !in headers) headers["Content-Type"] = "application/octet-stream";
  1058. headers["Content-Length"] = formatAlloc(m_requestAlloc, "%d", data.length);
  1059. bodyWriter.write(data);
  1060. }
  1061. /// ditto
  1062. void writeBody(in ubyte[] data, int status, string content_type = null)
  1063. @safe {
  1064. statusCode = status;
  1065. writeBody(data, content_type);
  1066. }
  1067. /// ditto
  1068. void writeBody(scope InputStream data, string content_type = null)
  1069. @safe {
  1070. if (content_type.length) headers["Content-Type"] = content_type;
  1071. else if ("Content-Type" !in headers) headers["Content-Type"] = "application/octet-stream";
  1072. data.pipe(bodyWriter);
  1073. }
  1074. /// ditto
  1075. void writeBody(scope InputStream data, int status, string content_type = null)
  1076. {
  1077. statusCode = status;
  1078. writeBody(data, content_type);
  1079. }
  1080. /** Writes the entire response body as a single string.
  1081. Params:
  1082. data = The string to write as the body contents
  1083. status = Optional response status code to set
  1084. content_type = Optional content type to apply to the response.
  1085. If no content type is given and no "Content-Type" header is
  1086. set in the response, this will default to
  1087. `"text/plain; charset=UTF-8"`.
  1088. See_Also: `HTTPStatusCode`
  1089. */
  1090. void writeBody(string data, string content_type = null)
  1091. @safe {
  1092. if (!content_type.length && "Content-Type" !in headers)
  1093. content_type = "text/plain; charset=UTF-8";
  1094. writeBody(cast(const(ubyte)[])data, content_type);
  1095. }
  1096. /// ditto
  1097. void writeBody(string data, int status, string content_type = null)
  1098. @safe {
  1099. statusCode = status;
  1100. writeBody(data, content_type);
  1101. }
  1102. /** Writes the whole response body at once, without doing any further encoding.
  1103. The caller has to make sure that the appropriate headers are set correctly
  1104. (i.e. Content-Type and Content-Encoding).
  1105. Note that the version taking a RandomAccessStream may perform additional
  1106. optimizations such as sending a file directly from the disk to the
  1107. network card using a DMA transfer.
  1108. */
  1109. void writeRawBody(RandomAccessStream)(RandomAccessStream stream) @safe
  1110. if (isRandomAccessStream!RandomAccessStream)
  1111. {
  1112. m_exchange.writeBody(this, RandomAccessStreamProxy(stream));
  1113. }
  1114. /// ditto
  1115. void writeRawBody(InputStream)(InputStream stream, size_t num_bytes = size_t.max) @safe
  1116. if (isInputStream!InputStream && !isRandomAccessStream!InputStream)
  1117. {
  1118. m_exchange.writeBody(this, InputStreamProxy(stream), num_bytes == 0 ? size_t.max : num_bytes);
  1119. }
  1120. /// ditto
  1121. void writeRawBody(RandomAccessStream)(RandomAccessStream stream, int status) @safe
  1122. if (isRandomAccessStream!RandomAccessStream)
  1123. {
  1124. statusCode = status;
  1125. writeRawBody(stream);
  1126. }
  1127. /// ditto
  1128. void writeRawBody(InputStream)(InputStream stream, int status, size_t num_bytes = 0) @safe
  1129. if (isInputStream!InputStream && !isRandomAccessStream!InputStream)
  1130. {
  1131. statusCode = status;
  1132. writeRawBody(stream, num_bytes);
  1133. }
  1134. /// Writes a JSON message with the specified status
  1135. void writeJsonBody(T)(T data, int status, bool allow_chunked = false)
  1136. {
  1137. statusCode = status;
  1138. writeJsonBody(data, allow_chunked);
  1139. }
  1140. /// ditto
  1141. void writeJsonBody(T)(T data, int status, string content_type, bool allow_chunked = false)
  1142. {
  1143. statusCode = status;
  1144. writeJsonBody(data, content_type, allow_chunked);
  1145. }
  1146. /// ditto
  1147. void writeJsonBody(T)(T data, string content_type, bool allow_chunked = false)
  1148. {
  1149. headers["Content-Type"] = content_type;
  1150. writeJsonBody(data, allow_chunked);
  1151. }
  1152. /// ditto
  1153. void writeJsonBody(T)(T data, bool allow_chunked = false)
  1154. {
  1155. doWriteJsonBody!(T, false)(data, allow_chunked);
  1156. }
  1157. /// ditto
  1158. void writePrettyJsonBody(T)(T data, bool allow_chunked = false)
  1159. {
  1160. doWriteJsonBody!(T, true)(data, allow_chunked);
  1161. }
  1162. private void doWriteJsonBody(T, bool PRETTY)(T data, bool allow_chunked = false)
  1163. {
  1164. import std.traits;
  1165. import vibe.stream.wrapper;
  1166. static if (!is(T == Json) && is(typeof(data.data())) && isArray!(typeof(data.data()))) {
  1167. static assert(!is(T == Appender!(typeof(data.data()))), "Passed an Appender!T to writeJsonBody - this is most probably not doing what's indended.");
  1168. }
  1169. if ("Content-Type" !in headers)
  1170. headers["Content-Type"] = "application/json; charset=UTF-8";
  1171. // set an explicit content-length field if chunked encoding is not allowed
  1172. if (!allow_chunked) {
  1173. import vibe.internal.rangeutil;
  1174. long length = 0;
  1175. auto counter = RangeCounter(() @trusted { return &length; } ());
  1176. static if (PRETTY) serializeToPrettyJson(counter, data);
  1177. else serializeToJson(counter, data);
  1178. headers["Content-Length"] = formatAlloc(m_requestAlloc, "%d", length);
  1179. }
  1180. auto rng = streamOutputRange!1024(bodyWriter);
  1181. static if (PRETTY) serializeToPrettyJson(() @trusted { return &rng; } (), data);
  1182. else serializeToJson(() @trusted { return &rng; } (), data);
  1183. }
  1184. /**
  1185. * Writes the response with no body.
  1186. *
  1187. * This method should be used in situations where no body is
  1188. * requested, such as a HEAD request. For an empty body, just use writeBody,
  1189. * as this method causes problems with some keep-alive connections.
  1190. */
  1191. void writeVoidBody()
  1192. @safe {
  1193. m_exchange.writeVoidBody(this);
  1194. }
  1195. /** A stream for writing the body of the HTTP response.
  1196. Note that after 'bodyWriter' has been accessed for the first time, it
  1197. is not allowed to change any header or the status code of the response.
  1198. */
  1199. @property InterfaceProxy!OutputStream bodyWriter()
  1200. @safe scope {
  1201. assert(!!m_exchange);
  1202. return m_exchange.bodyWriter(this);
  1203. }
  1204. /** Special method sending a SWITCHING_PROTOCOLS response to the client.
  1205. Notice: For the overload that returns a `ConnectionStream`, it must be
  1206. ensured that the returned instance doesn't outlive the request
  1207. handler callback.
  1208. Params:
  1209. protocol = The protocol set in the "Upgrade" header of the response.
  1210. Use an empty string to skip setting this field.
  1211. */
  1212. ConnectionStream switchProtocol(string protocol)
  1213. @safe {
  1214. return m_exchange.switchProtocol(this, protocol);
  1215. }
  1216. /// ditto
  1217. void switchProtocol(string protocol, scope void delegate(scope ConnectionStream) @safe del)
  1218. @safe {
  1219. m_exchange.switchProtocol(this, protocol, del);
  1220. }
  1221. /** Special method for handling CONNECT proxy tunnel
  1222. Notice: For the overload that returns a `ConnectionStream`, it must be
  1223. ensured that the returned instance doesn't outlive the request
  1224. handler callback.
  1225. */
  1226. ConnectionStream connectProxy()
  1227. @safe {
  1228. return m_exchange.connectProxy(this);
  1229. }
  1230. /// ditto
  1231. void connectProxy(scope void delegate(scope ConnectionStream) @safe del)
  1232. @safe {
  1233. m_exchange.connectProxy(this, del);
  1234. }
  1235. /** Sets the specified cookie value.
  1236. Params:
  1237. name = Name of the cookie
  1238. value = New cookie value - pass null to clear the cookie
  1239. path = Path (as seen by the client) of the directory tree in which the cookie is visible
  1240. encoding = Optional encoding (url, raw), default to URL encoding
  1241. */
  1242. Cookie setCookie(string name, string value, string path = "/", Cookie.Encoding encoding = Cookie.Encoding.url)
  1243. @safe {
  1244. auto cookie = new Cookie();
  1245. cookie.path = path;
  1246. cookie.setValue(value, encoding);
  1247. if (value is null) {
  1248. cookie.maxAge = 0;
  1249. cookie.expires = "Thu, 01 Jan 1970 00:00:00 GMT";
  1250. }
  1251. cookies[name] = cookie;
  1252. return cookie;
  1253. }
  1254. /**
  1255. Initiates a new session.
  1256. The session is stored in the SessionStore that was specified when
  1257. creating the server. Depending on this, the session can be persistent
  1258. or temporary and specific to this server instance.
  1259. */
  1260. Session startSession(string path = "/")
  1261. @safe {
  1262. return startSession(path, m_settings.sessionOptions);
  1263. }
  1264. /// ditto
  1265. Session startSession(string path, SessionOption options)
  1266. @safe {
  1267. assert(m_settings.sessionStore, "no session store set");
  1268. assert(!m_session, "Try to start a session, but already started one.");
  1269. bool secure;
  1270. if (options & SessionOption.secure) secure = true;
  1271. else if (options & SessionOption.noSecure) secure = false;
  1272. else secure = this.tls;
  1273. m_session = m_settings.sessionStore.create();
  1274. m_session.set("$sessionCookiePath", path);
  1275. m_session.set("$sessionCookieSecure", secure);
  1276. auto cookie = setCookie(m_settings.sessionIdCookie, m_session.id, path);
  1277. cookie.secure = secure;
  1278. cookie.httpOnly = (options & SessionOption.httpOnly) != 0;
  1279. cookie.sameSite = (options & SessionOption.noSameSiteStrict) ?
  1280. Cookie.SameSite.lax : Cookie.SameSite.strict;
  1281. return m_session;
  1282. }
  1283. /**
  1284. Terminates the current session (if any).
  1285. */
  1286. void terminateSession()
  1287. @safe {
  1288. if (!m_session) return;
  1289. auto cookie = setCookie(m_settings.sessionIdCookie, null, m_session.get!string("$sessionCookiePath"));
  1290. cookie.secure = m_session.get!bool("$sessionCookieSecure");
  1291. m_session.destroy();
  1292. m_session = Session.init;
  1293. }
  1294. @property ulong bytesWritten() @safe const { return m_exchange.bytesWritten; }
  1295. /**
  1296. Waits until either the connection closes, data arrives, or until the
  1297. given timeout is reached.
  1298. Returns:
  1299. $(D true) if the connection was closed and $(D false) if either the
  1300. timeout was reached, or if data has arrived for consumption.
  1301. See_Also: `connected`
  1302. */
  1303. bool waitForConnectionClose(Duration timeout = Duration.max)
  1304. @safe {
  1305. return m_exchange.waitForConnectionClose(timeout);
  1306. }
  1307. /**
  1308. Determines if the underlying connection is still alive.
  1309. Returns $(D true) if the remote peer is still connected and $(D false)
  1310. if the remote peer closed the connection.
  1311. See_Also: `waitForConnectionClose`
  1312. */
  1313. @property bool connected()
  1314. @safe const {
  1315. return m_exchange.connected;
  1316. }
  1317. /**
  1318. Finalizes the response. This is usually called automatically by the server.
  1319. This method can be called manually after writing the response to force
  1320. all network traffic associated with the current request to be finalized.
  1321. After the call returns, the `timeFinalized` property will be set.
  1322. */
  1323. void finalize()
  1324. @safe {
  1325. m_exchange.finalize(this);
  1326. }
  1327. }
  1328. interface HTTPServerExchange {
  1329. @safe:
  1330. @property bool isHeadResponse() const;
  1331. @property bool headerWritten() const;
  1332. @property ulong bytesWritten() const;
  1333. @property bool connected() const;
  1334. bool waitForConnectionClose(Duration timeout);
  1335. void writeBody(HTTPServerResponse res, RandomAccessStreamProxy streamx);
  1336. void writeBody(HTTPServerResponse res, InputStreamProxy stream, ulong num_bytes = ulong.max);
  1337. void writeVoidBody(HTTPServerResponse res);
  1338. OutputStreamProxy bodyWriter(HTTPServerResponse res);
  1339. ConnectionStream switchProtocol(HTTPServerResponse res, string protocol);
  1340. void switchProtocol(HTTPServerResponse res, string protocol, scope void delegate(scope ConnectionStream) @safe del);
  1341. ConnectionStream connectProxy(HTTPServerResponse res);
  1342. void connectProxy(HTTPServerResponse res, scope void delegate(scope ConnectionStream) @safe del);
  1343. void finalize(HTTPServerResponse res);
  1344. }
  1345. /**
  1346. Represents the request listener for a specific `listenHTTP` call.
  1347. This struct can be used to stop listening for HTTP requests at runtime.
  1348. */
  1349. struct HTTPListener {
  1350. private {
  1351. size_t[] m_virtualHostIDs;
  1352. }
  1353. private this(size_t[] ids) @safe { m_virtualHostIDs = ids; }
  1354. @property NetworkAddress[] bindAddresses()
  1355. @safe {
  1356. NetworkAddress[] ret;
  1357. foreach (l; s_listeners)
  1358. if (l.m_virtualHosts.canFind!(v => m_virtualHostIDs.canFind(v.id))) {
  1359. NetworkAddress a;
  1360. a = resolveHost(l.bindAddress);
  1361. a.port = l.bindPort;
  1362. ret ~= a;
  1363. }
  1364. return ret;
  1365. }
  1366. /** Stops handling HTTP requests and closes the TCP listening port if
  1367. possible.
  1368. */
  1369. void stopListening()
  1370. @safe {
  1371. import std.algorithm : countUntil;
  1372. foreach (vhid; m_virtualHostIDs) {
  1373. foreach (lidx, l; s_listeners) {
  1374. if (l.removeVirtualHost(vhid)) {
  1375. if (!l.hasVirtualHosts) {
  1376. l.m_listener.stopListening();
  1377. logInfo("Stopped to listen for HTTP%s requests on %s:%s", l.tlsContext ? "S": "", l.bindAddress, l.bindPort);
  1378. s_listeners = s_listeners[0 .. lidx] ~ s_listeners[lidx+1 .. $];
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. /** Represents a single HTTP server port.
  1387. This class defines the incoming interface, port, and TLS configuration of
  1388. the public server port. The public server port may differ from the local
  1389. one if a reverse proxy of some kind is facing the public internet and
  1390. forwards to this HTTP server.
  1391. Multiple virtual hosts can be configured to be served from the same port.
  1392. Their TLS settings must be compatible and each virtual host must have a
  1393. unique name.
  1394. */
  1395. final class HTTPServerContext {
  1396. package struct VirtualHost {
  1397. HTTPServerRequestDelegate requestHandler;
  1398. HTTPServerSettings settings;
  1399. HTTPLogger[] loggers;
  1400. size_t id;
  1401. }
  1402. package {
  1403. TCPListener m_listener;
  1404. VirtualHost[] m_virtualHosts;
  1405. string m_bindAddress;
  1406. ushort m_bindPort;
  1407. TLSContext m_tlsContext;
  1408. static size_t s_vhostIDCounter = 1;
  1409. }
  1410. @safe:
  1411. this(string bind_address, ushort bind_port)
  1412. {
  1413. m_bindAddress = bind_address;
  1414. m_bindPort = bind_port;
  1415. }
  1416. /** Returns the TLS context associated with the listener.
  1417. For non-HTTPS listeners, `null` will be returned. Otherwise, if only a
  1418. single virtual host has been added, the TLS context of that host's
  1419. settings is returned. For multiple virtual hosts, an SNI context is
  1420. returned, which forwards to the individual contexts based on the
  1421. requested host name.
  1422. */
  1423. @property TLSContext tlsContext() { return m_tlsContext; }
  1424. /// The local network interface IP address associated with this listener
  1425. @property string bindAddress() const { return m_bindAddress; }
  1426. /// The local port associated with this listener
  1427. @property ushort bindPort() const { return m_bindPort; }
  1428. /// Determines if any virtual hosts have been addded
  1429. @property bool hasVirtualHosts() const { return m_virtualHosts.length > 0; }
  1430. /** Adds a single virtual host.
  1431. Note that the port and bind address defined in `settings` must match the
  1432. ones for this listener. The `settings.host` field must be unique for
  1433. all virtual hosts.
  1434. Returns: Returns a unique ID for the new virtual host
  1435. */
  1436. size_t addVirtualHost(HTTPServerSettings settings, HTTPServerRequestDelegate request_handler)
  1437. {
  1438. assert(settings.port == 0 || settings.port == m_bindPort, "Virtual host settings do not match bind port.");
  1439. assert(settings.bindAddresses.canFind(m_bindAddress), "Virtual host settings do not match bind address.");
  1440. VirtualHost vhost;
  1441. vhost.id = s_vhostIDCounter++;
  1442. vhost.settings = settings;
  1443. vhost.requestHandler = request_handler;
  1444. if (settings.accessLogger) vhost.loggers ~= settings.accessLogger;
  1445. if (settings.accessLogToConsole)
  1446. vhost.loggers ~= new HTTPConsoleLogger(settings, settings.accessLogFormat);
  1447. if (settings.accessLogFile.length)
  1448. vhost.loggers ~= new HTTPFileLogger(settings, settings.accessLogFormat, settings.accessLogFile);
  1449. if (!m_virtualHosts.length) m_tlsContext = settings.tlsContext;
  1450. enforce((m_tlsContext !is null) == (settings.tlsContext !is null),
  1451. "Cannot mix HTTP and HTTPS virtual hosts within the same listener.");
  1452. if (m_tlsContext) addSNIHost(settings);
  1453. m_virtualHosts ~= vhost;
  1454. if (settings.hostName.length) {
  1455. auto proto = settings.tlsContext ? "https" : "http";
  1456. auto port = settings.tlsContext && settings.port == 443 || !settings.tlsContext && settings.port == 80 ? "" : ":" ~ settings.port.to!string;
  1457. logInfo("Added virtual host %s://%s:%s/ (%s)", proto, settings.hostName, m_bindPort, m_bindAddress);
  1458. }
  1459. return vhost.id;
  1460. }
  1461. /// Removes a previously added virtual host using its ID.
  1462. bool removeVirtualHost(size_t id)
  1463. {
  1464. import std.algorithm.searching : countUntil;
  1465. auto idx = m_virtualHosts.countUntil!(c => c.id == id);
  1466. if (idx < 0) return false;
  1467. auto ctx = m_virtualHosts[idx];
  1468. m_virtualHosts = m_virtualHosts[0 .. idx] ~ m_virtualHosts[idx+1 .. $];
  1469. return true;
  1470. }
  1471. private void addSNIHost(HTTPServerSettings settings)
  1472. {
  1473. if (settings.tlsContext !is m_tlsContext && m_tlsContext.kind != TLSContextKind.serverSNI) {
  1474. logDebug("Create SNI TLS context for %s, port %s", bindAddress, bindPort);
  1475. m_tlsContext = createTLSContext(TLSContextKind.serverSNI);
  1476. m_tlsContext.sniCallback = &onSNI;
  1477. }
  1478. foreach (ctx; m_virtualHosts) {
  1479. /*enforce(ctx.settings.hostName != settings.hostName,
  1480. "A server with the host name '"~settings.hostName~"' is already "
  1481. "listening on "~addr~":"~to!string(settings.port)~".");*/
  1482. }
  1483. }
  1484. private TLSContext onSNI(string servername)
  1485. {
  1486. foreach (vhost; m_virtualHosts)
  1487. if (vhost.settings.hostName.icmp(servername) == 0) {
  1488. logDebug("Found context for SNI host '%s'.", servername);
  1489. return vhost.settings.tlsContext;
  1490. }
  1491. logDebug("No context found for SNI host '%s'.", servername);
  1492. return null;
  1493. }
  1494. }
  1495. /**************************************************************************************************/
  1496. /* Private types */
  1497. /**************************************************************************************************/
  1498. package final class LimitedHTTPInputStream : LimitedInputStream {
  1499. @safe:
  1500. this(InterfaceProxy!InputStream stream, ulong byte_limit, bool silent_limit = false) {
  1501. super(stream, byte_limit, silent_limit, true);
  1502. }
  1503. override void onSizeLimitReached() {
  1504. throw new HTTPStatusException(HTTPStatus.requestEntityTooLarge);
  1505. }
  1506. }
  1507. package final class TimeoutHTTPInputStream : InputStream {
  1508. @safe:
  1509. private {
  1510. long m_timeref;
  1511. long m_timeleft;
  1512. InterfaceProxy!InputStream m_in;
  1513. }
  1514. this(InterfaceProxy!InputStream stream, Duration timeleft, SysTime reftime)
  1515. {
  1516. enforce(timeleft > 0.seconds, "Timeout required");
  1517. m_in = stream;
  1518. m_timeleft = timeleft.total!"hnsecs"();
  1519. m_timeref = reftime.stdTime();
  1520. }
  1521. @property bool empty() { enforce(m_in, "InputStream missing"); return m_in.empty(); }
  1522. @property ulong leastSize() { enforce(m_in, "InputStream missing"); return m_in.leastSize(); }
  1523. @property bool dataAvailableForRead() { enforce(m_in, "InputStream missing"); return m_in.dataAvailableForRead; }
  1524. const(ubyte)[] peek() { return m_in.peek(); }
  1525. size_t read(scope ubyte[] dst, IOMode mode)
  1526. {
  1527. enforce(m_in, "InputStream missing");
  1528. size_t nread = 0;
  1529. checkTimeout();
  1530. // FIXME: this should use ConnectionStream.waitForData to enforce the timeout during the
  1531. // read operation
  1532. return m_in.read(dst, mode);
  1533. }
  1534. alias read = InputStream.read;
  1535. private void checkTimeout()
  1536. @safe {
  1537. auto curr = Clock.currStdTime();
  1538. auto diff = curr - m_timeref;
  1539. if (diff > m_timeleft) throw new HTTPStatusException(HTTPStatus.requestTimeout);
  1540. m_timeleft -= diff;
  1541. m_timeref = curr;
  1542. }
  1543. }
  1544. /**************************************************************************************************/
  1545. /* Private functions */
  1546. /**************************************************************************************************/
  1547. private {
  1548. import core.sync.mutex;
  1549. shared string s_distHost;
  1550. shared ushort s_distPort = 11000;
  1551. HTTPServerContext[] s_listeners;
  1552. }
  1553. /**
  1554. [private] Starts a HTTP server listening on the specified port.
  1555. This is the same as listenHTTP() except that it does not use a VibeDist host for
  1556. remote listening, even if specified on the command line.
  1557. */
  1558. private HTTPListener listenHTTPPlain(HTTPServerSettings settings, HTTPServerRequestDelegate request_handler)
  1559. @safe {
  1560. import vibe.core.core : runWorkerTaskDist;
  1561. import std.algorithm : canFind, find;
  1562. static TCPListener doListen(HTTPServerContext listen_info, bool reusePort, bool reuseAddress, bool is_tls)
  1563. @safe {
  1564. try {
  1565. TCPListenOptions options = TCPListenOptions.defaults;
  1566. if(reuseAddress) options |= TCPListenOptions.reuseAddress; else options &= ~TCPListenOptions.reuseAddress;
  1567. if(reusePort) options |= TCPListenOptions.reusePort; else options &= ~TCPListenOptions.reusePort;
  1568. auto ret = listenTCP(listen_info.bindPort, (TCPConnection conn) nothrow @safe {
  1569. try handleHTTPConnection(conn, listen_info);
  1570. catch (Exception e) {
  1571. logError("HTTP connection handler has thrown at the peer %s: %s", conn.peerAddress, e.msg);
  1572. debug logDebug("Full error: %s", () @trusted { return e.toString().sanitize(); } ());
  1573. try conn.close();
  1574. catch (Exception e) logError("Failed to close connection: %s", e.msg);
  1575. }
  1576. }, listen_info.bindAddress, options);
  1577. // support port 0 meaning any available port
  1578. if (listen_info.bindPort == 0)
  1579. listen_info.m_bindPort = ret.bindAddress.port;
  1580. auto proto = is_tls ? "https" : "http";
  1581. auto urladdr = listen_info.bindAddress;
  1582. if (urladdr.canFind(':')) urladdr = "["~urladdr~"]";
  1583. logInfo("Listening for requests on %s://%s:%s/", proto, urladdr, listen_info.bindPort);
  1584. return ret;
  1585. } catch( Exception e ) {
  1586. logWarn("Failed to listen on %s:%s", listen_info.bindAddress, listen_info.bindPort);
  1587. return TCPListener.init;
  1588. }
  1589. }
  1590. size_t[] vid;
  1591. // Check for every bind address/port, if a new listening socket needs to be created and
  1592. // check for conflicting servers
  1593. foreach (addr; settings.bindAddresses) {
  1594. HTTPServerContext linfo;
  1595. auto l = s_listeners.find!(l => l.bindAddress == addr && l.bindPort == settings.port);
  1596. if (!l.empty) linfo = l.front;
  1597. else {
  1598. auto li = new HTTPServerContext(addr, settings.port);
  1599. if (auto tcp_lst = doListen(li,
  1600. (settings.options & HTTPServerOption.reusePort) != 0,
  1601. (settings.options & HTTPServerOption.reuseAddress) != 0,
  1602. settings.tlsContext !is null)) // DMD BUG 2043
  1603. {
  1604. li.m_listener = tcp_lst;
  1605. s_listeners ~= li;
  1606. linfo = li;
  1607. }
  1608. }
  1609. if (linfo) vid ~= linfo.addVirtualHost(settings, request_handler);
  1610. }
  1611. enforce(vid.length > 0, "Failed to listen for incoming HTTP connections on any of the supplied interfaces.");
  1612. return HTTPListener(vid);
  1613. }
  1614. private void parseCookies(string str, ref CookieValueMap cookies)
  1615. @safe {
  1616. import std.encoding : sanitize;
  1617. import std.array : split;
  1618. import std.string : strip;
  1619. import std.algorithm.iteration : map, filter, each;
  1620. import vibe.http.common : Cookie;
  1621. () @trusted { return str.sanitize; } ()
  1622. .split(";")
  1623. .map!(kv => kv.strip.split("="))
  1624. .filter!(kv => kv.length == 2) //ignore illegal cookies
  1625. .each!(kv => cookies.add(kv[0], kv[1], Cookie.Encoding.raw) );
  1626. }
  1627. unittest
  1628. {
  1629. auto cvm = CookieValueMap();
  1630. parseCookies("foo=bar;; baz=zinga; öö=üü ; møøse=was=sacked; onlyval1; =onlyval2; onlykey=", cvm);
  1631. assert(cvm["foo"] == "bar");
  1632. assert(cvm["baz"] == "zinga");
  1633. assert(cvm["öö"] == "üü");
  1634. assert( "møøse" ! in cvm); //illegal cookie gets ignored
  1635. assert( "onlyval1" ! in cvm); //illegal cookie gets ignored
  1636. assert(cvm["onlykey"] == "");
  1637. assert(cvm[""] == "onlyval2");
  1638. assert(cvm.length() == 5);
  1639. cvm = CookieValueMap();
  1640. parseCookies("", cvm);
  1641. assert(cvm.length() == 0);
  1642. cvm = CookieValueMap();
  1643. parseCookies(";;=", cvm);
  1644. assert(cvm.length() == 1);
  1645. assert(cvm[""] == "");
  1646. }
  1647. shared static this()
  1648. {
  1649. version (VibeNoDefaultArgs) {}
  1650. else {
  1651. string disthost = s_distHost;
  1652. ushort distport = s_distPort;
  1653. import vibe.core.args : readOption;
  1654. readOption("disthost|d", () @trusted { return &disthost; } (), "Sets the name of a vibedist server to use for load balancing.");
  1655. readOption("distport", () @trusted { return &distport; } (), "Sets the port used for load balancing.");
  1656. setVibeDistHost(disthost, distport);
  1657. }
  1658. }
  1659. version (VibeDebugCatchAll) package alias UncaughtException = Throwable;
  1660. else package alias UncaughtException = Exception;