/
server.d
2408 lines (2007 loc) · 77.6 KB
/
server.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
A HTTP 1.1/1.0 server implementation.
Copyright: © 2012-2017 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig, Jan Krüger, Ilya Shipunov
*/
module vibe.http.server;
public import vibe.core.net;
public import vibe.http.common;
public import vibe.http.session;
import vibe.core.file;
import vibe.core.log;
import vibe.data.json;
import vibe.http.dist;
import vibe.http.log;
import vibe.inet.message;
import vibe.inet.url;
import vibe.inet.webform;
import vibe.internal.interfaceproxy : InterfaceProxy;
import vibe.stream.counting;
import vibe.stream.operations;
import vibe.stream.tls;
import vibe.stream.wrapper : ConnectionProxyStream, createConnectionProxyStream, createConnectionProxyStreamFL;
import vibe.stream.zlib;
import vibe.textfilter.urlencode;
import vibe.utils.array;
import vibe.internal.allocator;
import vibe.internal.freelistref;
import vibe.utils.string;
import core.atomic;
import core.vararg;
import diet.traits : SafeFilterCallback, dietTraits;
import std.algorithm : canFind;
import std.array;
import std.conv;
import std.datetime;
import std.encoding : sanitize;
import std.exception;
import std.format;
import std.functional : toDelegate;
import std.string;
import std.traits : ReturnType;
import std.typecons;
import std.uri;
version (VibeNoSSL) version = HaveNoTLS;
else version (Have_botan) {}
else version (Have_openssl) {}
else version = HaveNoTLS;
/**************************************************************************************************/
/* Public functions */
/**************************************************************************************************/
/**
Starts a HTTP server listening on the specified port.
request_handler will be called for each HTTP request that is made. The
res parameter of the callback then has to be filled with the response
data.
request_handler can be either HTTPServerRequestDelegate/HTTPServerRequestFunction
or a class/struct with a member function 'handleRequest' that has the same
signature.
Note that if the application has been started with the --disthost command line
switch, listenHTTP() will automatically listen on the specified VibeDist host
instead of locally. This allows for a seamless switch from single-host to
multi-host scenarios without changing the code. If you need to listen locally,
use listenHTTPPlain() instead.
Params:
settings = Customizes the HTTP servers functionality (host string or HTTPServerSettings object)
request_handler = This callback is invoked for each incoming request and is responsible
for generating the response.
Returns:
A handle is returned that can be used to stop listening for further HTTP
requests with the supplied settings. Another call to `listenHTTP` can be
used afterwards to start listening again.
*/
HTTPListener listenHTTP(Settings)(Settings _settings, HTTPServerRequestDelegate request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
// auto-construct HTTPServerSettings
static if (is(Settings == string))
auto settings = new HTTPServerSettings(_settings);
else
alias settings = _settings;
enforce(settings.bindAddresses.length, "Must provide at least one bind address for a HTTP server.");
// if a VibeDist host was specified on the command line, register there instead of listening
// directly.
if (s_distHost.length && !settings.disableDistHost) {
return listenHTTPDist(settings, request_handler, s_distHost, s_distPort);
} else {
return listenHTTPPlain(settings, request_handler);
}
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestFunction request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, () @trusted { return toDelegate(request_handler); } ());
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestHandler request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, &request_handler.handleRequest);
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestDelegateS request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, cast(HTTPServerRequestDelegate)request_handler);
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestFunctionS request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, () @trusted { return toDelegate(request_handler); } ());
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, HTTPServerRequestHandlerS request_handler)
@safe
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, &request_handler.handleRequest);
}
/// Scheduled for deprecation - use a `@safe` callback instead.
HTTPListener listenHTTP(Settings)(Settings settings, void delegate(HTTPServerRequest, HTTPServerResponse) @system request_handler)
@system
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, (req, res) @trusted => request_handler(req, res));
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, void function(HTTPServerRequest, HTTPServerResponse) @system request_handler)
@system
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, (req, res) @trusted => request_handler(req, res));
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, void delegate(scope HTTPServerRequest, scope HTTPServerResponse) @system request_handler)
@system
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, (scope req, scope res) @trusted => request_handler(req, res));
}
/// ditto
HTTPListener listenHTTP(Settings)(Settings settings, void function(scope HTTPServerRequest, scope HTTPServerResponse) @system request_handler)
@system
if (is(Settings == string) || is(Settings == HTTPServerSettings)) {
return listenHTTP(settings, (scope req, scope res) @trusted => request_handler(req, res));
}
unittest
{
void test()
{
static void testSafeFunction(HTTPServerRequest req, HTTPServerResponse res) @safe {}
listenHTTP("0.0.0.0:8080", &testSafeFunction);
listenHTTP(":8080", new class HTTPServerRequestHandler {
void handleRequest(HTTPServerRequest req, HTTPServerResponse res) @safe {}
});
listenHTTP(":8080", (req, res) {});
static void testSafeFunctionS(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
listenHTTP(":8080", &testSafeFunctionS);
void testSafeDelegateS(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
listenHTTP(":8080", &testSafeDelegateS);
listenHTTP(":8080", new class HTTPServerRequestHandler {
void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe {}
});
listenHTTP(":8080", (scope req, scope res) {});
}
}
/** Treats an existing connection as an HTTP connection and processes incoming
requests.
After all requests have been processed, the connection will be closed and
the function returns to the caller.
Params:
connections = The stream to treat as an incoming HTTP client connection.
context = Information about the incoming listener and available
virtual hosts
*/
void handleHTTPConnection(TCPConnection connection, HTTPServerContext context)
@safe {
InterfaceProxy!Stream http_stream;
http_stream = connection;
scope (exit) connection.close();
// Set NODELAY to true, to avoid delays caused by sending the response
// header and body in separate chunks. Note that to avoid other performance
// issues (caused by tiny packets), this requires using an output buffer in
// the event driver, which is the case at least for the default libevent
// based driver.
connection.tcpNoDelay = true;
version(HaveNoTLS) {} else {
TLSStreamType tls_stream;
}
if (!connection.waitForData(10.seconds())) {
logDebug("Client didn't send the initial request in a timely manner. Closing connection.");
return;
}
// If this is a HTTPS server, initiate TLS
if (context.tlsContext) {
version (HaveNoTLS) assert(false, "No TLS support compiled in.");
else {
logDebug("Accept TLS connection: %s", context.tlsContext.kind);
// TODO: reverse DNS lookup for peer_name of the incoming connection for TLS client certificate verification purposes
tls_stream = createTLSStreamFL(http_stream, context.tlsContext, TLSStreamState.accepting, null, connection.remoteAddress);
http_stream = tls_stream;
}
}
while (!connection.empty) {
HTTPServerSettings settings;
bool keep_alive;
version(HaveNoTLS) {} else {
// handle oderly TLS shutdowns
if (tls_stream && tls_stream.empty) break;
}
() @trusted {
import vibe.internal.utilallocator: RegionListAllocator;
version (VibeManualMemoryManagement)
scope request_allocator = new RegionListAllocator!(shared(Mallocator), false)(1024, Mallocator.instance);
else
scope request_allocator = new RegionListAllocator!(shared(GCAllocator), true)(1024, GCAllocator.instance);
handleRequest(http_stream, connection, context, settings, keep_alive, request_allocator);
} ();
if (!keep_alive) { logTrace("No keep-alive - disconnecting client."); break; }
logTrace("Waiting for next request...");
// wait for another possible request on a keep-alive connection
if (!connection.waitForData(settings.keepAliveTimeout)) {
if (!connection.connected) logTrace("Client disconnected.");
else logDebug("Keep-alive connection timed out!");
break;
}
}
logTrace("Done handling connection.");
}
/**
Provides a HTTP request handler that responds with a static Diet template.
*/
@property HTTPServerRequestDelegateS staticTemplate(string template_file)()
{
return (scope HTTPServerRequest req, scope HTTPServerResponse res){
res.render!(template_file, req);
};
}
/**
Provides a HTTP request handler that responds with a static redirection to the specified URL.
Params:
url = The URL to redirect to
status = Redirection status to use $(LPAREN)by default this is $(D HTTPStatus.found)$(RPAREN).
Returns:
Returns a $(D HTTPServerRequestDelegate) that performs the redirect
*/
HTTPServerRequestDelegate staticRedirect(string url, HTTPStatus status = HTTPStatus.found)
@safe {
return (HTTPServerRequest req, HTTPServerResponse res){
res.redirect(url, status);
};
}
/// ditto
HTTPServerRequestDelegate staticRedirect(URL url, HTTPStatus status = HTTPStatus.found)
@safe {
return (HTTPServerRequest req, HTTPServerResponse res){
res.redirect(url, status);
};
}
///
unittest {
import vibe.http.router;
void test()
{
auto router = new URLRouter;
router.get("/old_url", staticRedirect("http://example.org/new_url", HTTPStatus.movedPermanently));
listenHTTP(new HTTPServerSettings, router);
}
}
/**
Sets a VibeDist host to register with.
*/
void setVibeDistHost(string host, ushort port)
@safe {
s_distHost = host;
s_distPort = port;
}
/**
Renders the given Diet template and makes all ALIASES available to the template.
You can call this function as a pseudo-member of `HTTPServerResponse` using
D's uniform function call syntax.
See_also: `diet.html.compileHTMLDietFile`
Examples:
---
string title = "Hello, World!";
int pageNumber = 1;
res.render!("mytemplate.dt", title, pageNumber);
---
*/
@property void render(string template_file, ALIASES...)(HTTPServerResponse res)
{
res.contentType = "text/html; charset=UTF-8";
version (VibeUseOldDiet)
pragma(msg, "VibeUseOldDiet is not supported anymore. Please undefine in the package recipe.");
import vibe.stream.wrapper : streamOutputRange;
import diet.html : compileHTMLDietFile;
auto output = streamOutputRange!1024(res.bodyWriter);
compileHTMLDietFile!(template_file, ALIASES, DefaultDietFilters)(output);
}
/**
Provides the default `css`, `javascript`, `markdown` and `htmlescape` filters
*/
@dietTraits
struct DefaultDietFilters {
import diet.html : HTMLOutputStyle;
import diet.traits : SafeFilterCallback;
import std.string : splitLines;
version (VibeOutputCompactHTML) enum HTMLOutputStyle htmlOutputStyle = HTMLOutputStyle.compact;
else enum HTMLOutputStyle htmlOutputStyle = HTMLOutputStyle.pretty;
static string filterCss(I)(I text, size_t indent = 0)
{
auto lines = splitLines(text);
string indent_string = "\n";
while (indent-- > 0) indent_string ~= '\t';
string ret = indent_string~"<style type=\"text/css\"><!--";
indent_string = indent_string ~ '\t';
foreach (ln; lines) ret ~= indent_string ~ ln;
indent_string = indent_string[0 .. $-1];
ret ~= indent_string ~ "--></style>";
return ret;
}
static string filterJavascript(I)(I text, size_t indent = 0)
{
auto lines = splitLines(text);
string indent_string = "\n";
while (indent-- > 0) indent_string ~= '\t';
string ret = indent_string~"<script type=\"application/javascript\">";
ret ~= indent_string~'\t' ~ "//<![CDATA[";
foreach (ln; lines) ret ~= indent_string ~ '\t' ~ ln;
ret ~= indent_string ~ '\t' ~ "//]]>" ~ indent_string ~ "</script>";
return ret;
}
static string filterMarkdown(I)(I text)
{
import vibe.textfilter.markdown : markdown = filterMarkdown;
// TODO: indent
return markdown(text);
}
static string filterHtmlescape(I)(I text)
{
import vibe.textfilter.html : htmlEscape;
// TODO: indent
return htmlEscape(text);
}
static this()
{
filters["css"] = (input, scope output) { output(filterCss(input)); };
filters["javascript"] = (input, scope output) { output(filterJavascript(input)); };
filters["markdown"] = (input, scope output) { output(filterMarkdown(() @trusted { return cast(string)input; } ())); };
filters["htmlescape"] = (input, scope output) { output(filterHtmlescape(input)); };
}
static SafeFilterCallback[string] filters;
}
unittest {
static string compile(string diet)() {
import std.array : appender;
import std.string : strip;
import diet.html : compileHTMLDietString;
auto dst = appender!string;
dst.compileHTMLDietString!(diet, DefaultDietFilters);
return strip(cast(string)(dst.data));
}
assert(compile!":css .test" == "<style type=\"text/css\"><!--\n\t.test\n--></style>");
assert(compile!":javascript test();" == "<script type=\"application/javascript\">\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
assert(compile!":markdown **test**" == "<p><strong>test</strong>\n</p>");
assert(compile!":htmlescape <test>" == "<test>");
assert(compile!":css !{\".test\"}" == "<style type=\"text/css\"><!--\n\t.test\n--></style>");
assert(compile!":javascript !{\"test();\"}" == "<script type=\"application/javascript\">\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
assert(compile!":markdown !{\"**test**\"}" == "<p><strong>test</strong>\n</p>");
assert(compile!":htmlescape !{\"<test>\"}" == "<test>");
assert(compile!":javascript\n\ttest();" == "<script type=\"application/javascript\">\n\t//<![CDATA[\n\ttest();\n\t//]]>\n</script>");
}
/**
Creates a HTTPServerRequest suitable for writing unit tests.
*/
HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method = HTTPMethod.GET, InputStream data = null)
@safe {
InetHeaderMap headers;
return createTestHTTPServerRequest(url, method, headers, data);
}
/// ditto
HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method, InetHeaderMap headers, InputStream data = null)
@safe {
auto tls = url.schema == "https";
auto ret = new HTTPServerRequest(Clock.currTime(UTC()), url.port ? url.port : tls ? 443 : 80);
ret.requestPath = url.path;
ret.queryString = url.queryString;
ret.username = url.username;
ret.password = url.password;
ret.requestURI = url.localURI;
ret.method = method;
ret.tls = tls;
ret.headers = headers;
ret.bodyReader = data;
return ret;
}
/**
Creates a HTTPServerResponse suitable for writing unit tests.
*/
HTTPServerResponse createTestHTTPServerResponse(OutputStream data_sink = null, SessionStore session_store = null)
@safe {
import vibe.stream.wrapper;
HTTPServerSettings settings;
if (session_store) {
settings = new HTTPServerSettings;
settings.sessionStore = session_store;
}
if (!data_sink) data_sink = new NullOutputStream;
auto stream = createProxyStream(Stream.init, data_sink);
auto ret = new HTTPServerResponse(stream, null, settings, () @trusted { return vibeThreadAllocator(); } ());
return ret;
}
/**************************************************************************************************/
/* Public types */
/**************************************************************************************************/
/// Delegate based request handler
alias HTTPServerRequestDelegate = void delegate(HTTPServerRequest req, HTTPServerResponse res) @safe;
/// Static function based request handler
alias HTTPServerRequestFunction = void function(HTTPServerRequest req, HTTPServerResponse res) @safe;
/// Interface for class based request handlers
interface HTTPServerRequestHandler {
/// Handles incoming HTTP requests
void handleRequest(HTTPServerRequest req, HTTPServerResponse res) @safe ;
}
/// Delegate based request handler with scoped parameters
alias HTTPServerRequestDelegateS = void delegate(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
/// Static function based request handler with scoped parameters
alias HTTPServerRequestFunctionS = void function(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
/// Interface for class based request handlers with scoped parameters
interface HTTPServerRequestHandlerS {
/// Handles incoming HTTP requests
void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe;
}
unittest {
static assert(is(HTTPServerRequestDelegateS : HTTPServerRequestDelegate));
static assert(is(HTTPServerRequestFunctionS : HTTPServerRequestFunction));
}
/// Aggregates all information about an HTTP error status.
final class HTTPServerErrorInfo {
/// The HTTP status code
int code;
/// The error message
string message;
/// Extended error message with debug information such as a stack trace
string debugMessage;
/// The error exception, if any
Throwable exception;
}
/// Delegate type used for user defined error page generator callbacks.
alias HTTPServerErrorPageHandler = void delegate(HTTPServerRequest req, HTTPServerResponse res, HTTPServerErrorInfo error) @safe;
private enum HTTPServerOptionImpl {
none = 0,
errorStackTraces = 1<<7,
reusePort = 1<<8,
distribute = 1<<9, // deprecated
reuseAddress = 1<<10
}
// TODO: Should be turned back into an enum once the deprecated symbols can be removed
/**
Specifies optional features of the HTTP server.
Disabling unneeded features can speed up the server or reduce its memory usage.
Note that the options `parseFormBody`, `parseJsonBody` and `parseMultiPartBody`
will also drain the `HTTPServerRequest.bodyReader` stream whenever a request
body with form or JSON data is encountered.
*/
struct HTTPServerOption {
static enum none = HTTPServerOptionImpl.none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum parseURL = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum parseQueryString = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum parseFormBody = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum parseJsonBody = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum parseMultiPartBody = none;
/** Deprecated: Distributes request processing among worker threads
Note that this functionality assumes that the request handler
is implemented in a thread-safe way. However, the D type system
is bypassed, so that no static verification takes place.
For this reason, it is recommended to instead use
`vibe.core.core.runWorkerTaskDist` and call `listenHTTP`
from each task/thread individually. If the `reusePort` option
is set, then all threads will be able to listen on the same port,
with the operating system distributing the incoming connections.
If possible, instead of threads, the use of separate processes
is more robust and often faster. The `reusePort` option works
the same way in this scenario.
*/
deprecated("Use runWorkerTaskDist or start threads separately. It will be removed in 0.9.")
static enum distribute = HTTPServerOptionImpl.distribute;
/** Enables stack traces (`HTTPServerErrorInfo.debugMessage`).
Note that generating the stack traces are generally a costly
operation that should usually be avoided in production
environments. It can also reveal internal information about
the application, such as function addresses, which can
help an attacker to abuse possible security holes.
*/
static enum errorStackTraces = HTTPServerOptionImpl.errorStackTraces;
/// Enable port reuse in `listenTCP()`
static enum reusePort = HTTPServerOptionImpl.reusePort;
/// Enable address reuse in `listenTCP()`
static enum reuseAddress = HTTPServerOptionImpl.reuseAddress;
/** The default set of options.
Includes all parsing options, as well as the `errorStackTraces`
option if the code is compiled in debug mode.
*/
static enum defaults = () { debug return HTTPServerOptionImpl.errorStackTraces; else return HTTPServerOptionImpl.reuseAddress; } ().HTTPServerOption;
deprecated("None has been renamed to none.")
static enum None = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseURL = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseQueryString = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseFormBody = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseJsonBody = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseMultiPartBody = none;
deprecated("This is done lazily. It will be removed in 0.9.")
static enum ParseCookies = none;
HTTPServerOptionImpl x;
alias x this;
}
/**
Contains all settings for configuring a basic HTTP server.
The defaults are sufficient for most normal uses.
*/
final class HTTPServerSettings {
/** The port on which the HTTP server is listening.
The default value is 80. If you are running a TLS enabled server you may want to set this
to 443 instead.
Using a value of `0` instructs the server to use any available port on
the given `bindAddresses` the actual addresses and ports can then be
queried with `TCPListener.bindAddresses`.
*/
ushort port = 80;
/** The interfaces on which the HTTP server is listening.
By default, the server will listen on all IPv4 and IPv6 interfaces.
*/
string[] bindAddresses = ["::", "0.0.0.0"];
/** Determines the server host name.
If multiple servers are listening on the same port, the host name will determine which one
gets a request.
*/
string hostName;
/** Configures optional features of the HTTP server
Disabling unneeded features can improve performance or reduce the server
load in case of invalid or unwanted requests (DoS). By default,
HTTPServerOption.defaults is used.
*/
HTTPServerOptionImpl options = HTTPServerOption.defaults;
/** Time of a request after which the connection is closed with an error; not supported yet
The default limit of 0 means that the request time is not limited.
*/
Duration maxRequestTime = 0.seconds;
/** Maximum time between two request on a keep-alive connection
The default value is 10 seconds.
*/
Duration keepAliveTimeout = 10.seconds;
/// Maximum number of transferred bytes per request after which the connection is closed with
/// an error
ulong maxRequestSize = 2097152;
/// Maximum number of transferred bytes for the request header. This includes the request line
/// the url and all headers.
ulong maxRequestHeaderSize = 8192;
/// Sets a custom handler for displaying error pages for HTTP errors
@property HTTPServerErrorPageHandler errorPageHandler() @safe { return errorPageHandler_; }
/// ditto
@property void errorPageHandler(HTTPServerErrorPageHandler del) @safe { errorPageHandler_ = del; }
/// Scheduled for deprecation - use a `@safe` callback instead.
@property void errorPageHandler(void delegate(HTTPServerRequest, HTTPServerResponse, HTTPServerErrorInfo) @system del)
@system {
this.errorPageHandler = (req, res, err) @trusted { del(req, res, err); };
}
private HTTPServerErrorPageHandler errorPageHandler_ = null;
/// If set, a HTTPS server will be started instead of plain HTTP.
TLSContext tlsContext;
/// Session management is enabled if a session store instance is provided
SessionStore sessionStore;
string sessionIdCookie = "vibe.session_id";
///
import vibe.core.core : vibeVersionString;
string serverString = "vibe.d/" ~ vibeVersionString;
/** Specifies the format used for the access log.
The log format is given using the Apache server syntax. By default NCSA combined is used.
---
"%h - %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\""
---
*/
string accessLogFormat = "%h - %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"";
/// Spefifies the name of a file to which access log messages are appended.
string accessLogFile = "";
/// If set, access log entries will be output to the console.
bool accessLogToConsole = false;
/** Specifies a custom access logger instance.
*/
HTTPLogger accessLogger;
/// Returns a duplicate of the settings object.
@property HTTPServerSettings dup()
@safe {
auto ret = new HTTPServerSettings;
foreach (mem; __traits(allMembers, HTTPServerSettings)) {
static if (mem == "sslContext") {}
else static if (mem == "bindAddresses") ret.bindAddresses = bindAddresses.dup;
else static if (__traits(compiles, __traits(getMember, ret, mem) = __traits(getMember, this, mem)))
__traits(getMember, ret, mem) = __traits(getMember, this, mem);
}
return ret;
}
/// Disable support for VibeDist and instead start listening immediately.
bool disableDistHost = false;
/** Responds to "Accept-Encoding" by using compression if possible.
Compression can also be manually enabled by setting the
"Content-Encoding" header of the HTTP response appropriately before
sending the response body.
This setting is disabled by default. Also note that there are still some
known issues with the GZIP compression code.
*/
bool useCompressionIfPossible = false;
/** Interval between WebSocket ping frames.
The default value is 60 seconds; set to Duration.zero to disable pings.
*/
Duration webSocketPingInterval = 60.seconds;
/** Constructs a new settings object with default values.
*/
this() @safe {}
/** Constructs a new settings object with a custom bind interface and/or port.
The syntax of `bind_string` is `[<IP address>][:<port>]`, where either of
the two parts can be left off. IPv6 addresses must be enclosed in square
brackets, as they would within a URL.
Throws:
An exception is thrown if `bind_string` is malformed.
*/
this(string bind_string)
@safe {
this();
if (bind_string.startsWith('[')) {
auto idx = bind_string.indexOf(']');
enforce(idx > 0, "Missing closing bracket for IPv6 address.");
bindAddresses = [bind_string[1 .. idx]];
bind_string = bind_string[idx+1 .. $];
enforce(bind_string.length == 0 || bind_string.startsWith(':'),
"Only a colon may follow the IPv6 address.");
}
auto idx = bind_string.indexOf(':');
if (idx < 0) {
if (bind_string.length > 0) bindAddresses = [bind_string];
} else {
if (idx > 0) bindAddresses = [bind_string[0 .. idx]];
port = bind_string[idx+1 .. $].to!ushort;
}
}
///
unittest {
auto s = new HTTPServerSettings(":8080");
assert(s.bindAddresses == ["::", "0.0.0.0"]); // default bind addresses
assert(s.port == 8080);
s = new HTTPServerSettings("123.123.123.123");
assert(s.bindAddresses == ["123.123.123.123"]);
assert(s.port == 80);
s = new HTTPServerSettings("[::1]:443");
assert(s.bindAddresses == ["::1"]);
assert(s.port == 443);
}
}
/**
Options altering how sessions are created.
Multiple values can be or'ed together.
See_Also: HTTPServerResponse.startSession
*/
enum SessionOption {
/// No options.
none = 0,
/** Instructs the browser to disallow accessing the session ID from JavaScript.
See_Also: Cookie.httpOnly
*/
httpOnly = 1<<0,
/** Instructs the browser to disallow sending the session ID over
unencrypted connections.
By default, the type of the connection on which the session is started
will be used to determine if secure or noSecure is used.
See_Also: noSecure, Cookie.secure
*/
secure = 1<<1,
/** Instructs the browser to allow sending the session ID over unencrypted
connections.
By default, the type of the connection on which the session is started
will be used to determine if secure or noSecure is used.
See_Also: secure, Cookie.secure
*/
noSecure = 1<<2
}
/**
Represents a HTTP request as received by the server side.
*/
final class HTTPServerRequest : HTTPRequest {
private {
SysTime m_timeCreated;
HTTPServerSettings m_settings;
ushort m_port;
string m_peer;
}
public {
/// The IP address of the client
@property string peer()
@safe nothrow {
if (!m_peer) {
version (Have_vibe_core) {} else scope (failure) assert(false);
// store the IP address (IPv4 addresses forwarded over IPv6 are stored in IPv4 format)
auto peer_address_string = this.clientAddress.toString();
if (peer_address_string.startsWith("::ffff:") && peer_address_string[7 .. $].indexOf(':') < 0)
m_peer = peer_address_string[7 .. $];
else m_peer = peer_address_string;
}
return m_peer;
}
/// ditto
NetworkAddress clientAddress;
/// Determines if the request should be logged to the access log file.
bool noLog;
/// Determines if the request was issued over an TLS encrypted channel.
bool tls;
/** Information about the TLS certificate provided by the client.
Remarks: This field is only set if `tls` is true, and the peer
presented a client certificate.
*/
TLSCertificateInformation clientCertificate;
/** Deprecated: The _path part of the URL.
Note that this function contains the decoded version of the
requested path, which can yield incorrect results if the path
contains URL encoded path separators. Use `requestPath` instead to
get an encoding-aware representation.
*/
string path() @safe {
if (_path.isNull) {
_path = urlDecode(requestPath.toString);
}
return _path.get;
}
private Nullable!string _path;
/** The path part of the requested URI.
*/
InetPath requestPath;
/** The user name part of the URL, if present.
*/
string username;
/** The _password part of the URL, if present.
*/
string password;
/** The _query string part of the URL.
*/
string queryString;
/** Contains the list of _cookies that are stored on the client.
Note that the a single cookie name may occur multiple times if multiple
cookies have that name but different paths or domains that all match
the request URI. By default, the first cookie will be returned, which is
the or one of the cookies with the closest path match.
*/
@property ref CookieValueMap cookies() @safe {
if (_cookies.isNull) {
_cookies = CookieValueMap.init;
if (auto pv = "cookie" in headers)
parseCookies(*pv, _cookies);
}
return _cookies.get;
}
private Nullable!CookieValueMap _cookies;
/** Contains all _form fields supplied using the _query string.
The fields are stored in the same order as they are received.
*/
@property ref FormFields query() @safe {
if (_query.isNull) {
_query = FormFields.init;
parseURLEncodedForm(queryString, _query);
}
return _query.get;
}
Nullable!FormFields _query;
import vibe.utils.dictionarylist;
/** A map of general parameters for the request.
This map is supposed to be used by middleware functionality to store
information for later stages. For example vibe.http.router.URLRouter uses this map
to store the value of any named placeholders.
*/
DictionaryList!(string, true, 8) params;
import std.variant : Variant;
/** A map of context items for the request.
This is especially useful for passing application specific data down
the chain of processors along with the request itself.
For example, a generic route may be defined to check user login status,
if the user is logged in, add a reference to user specific data to the
context.
This is implemented with `std.variant.Variant` to allow any type of data.
*/
DictionaryList!(Variant, true, 2) context;
/** Supplies the request body as a stream.
Note that when certain server options are set (such as
HTTPServerOption.parseJsonBody) and a matching request was sent,
the returned stream will be empty. If needed, remove those
options and do your own processing of the body when launching
the server. HTTPServerOption has a list of all options that affect
the request body.
*/
InputStream bodyReader;
/** Contains the parsed Json for a JSON request.
A JSON request must have the Content-Type "application/json" or "application/vnd.api+json".
*/
@property ref Json json() @safe {
if (_json.isNull) {
if (icmp2(contentType, "application/json") == 0 || icmp2(contentType, "application/vnd.api+json") == 0 ) {
auto bodyStr = bodyReader.readAllUTF8();
if (!bodyStr.empty) _json = parseJson(bodyStr);
else _json = Json.undefined;
} else {
_json = Json.undefined;
}
}
return _json.get;
}