-
Notifications
You must be signed in to change notification settings - Fork 284
/
server.d
1560 lines (1288 loc) · 47.9 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-2013 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.stream.counting;
import vibe.stream.operations;
import vibe.stream.ssl;
import vibe.stream.wrapper : ConnectionProxyStream;
import vibe.stream.zlib;
import vibe.textfilter.urlencode;
import vibe.utils.array;
import vibe.utils.memory;
import vibe.utils.string;
import core.vararg;
import std.array;
import std.conv;
import std.datetime;
import std.encoding : sanitize;
import std.exception;
import std.format;
import std.functional;
import std.string;
import std.typecons;
import std.uri;
/**************************************************************************************************/
/* 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.
request_handler = This callback is invoked for each incoming request and is responsible
for generating the response.
*/
void listenHTTP(HTTPServerSettings settings, HTTPServerRequestDelegate request_handler)
{
enforce(settings.bindAddresses.length, "Must provide at least one bind address for a HTTP server.");
HTTPServerContext ctx;
ctx.settings = settings;
ctx.requestHandler = request_handler;
if (settings.accessLogToConsole)
ctx.loggers ~= new HTTPConsoleLogger(settings, settings.accessLogFormat);
if (settings.accessLogFile.length)
ctx.loggers ~= new HTTPFileLogger(settings, settings.accessLogFormat, settings.accessLogFile);
g_contexts ~= ctx;
// if a VibeDist host was specified on the command line, register there instead of listening
// directly.
if (s_distHost.length && !settings.disableDistHost) {
listenHTTPDist(settings, request_handler, s_distHost, s_distPort);
} else {
listenHTTPPlain(settings);
}
}
/// ditto
void listenHTTP(HTTPServerSettings settings, HTTPServerRequestFunction request_handler)
{
listenHTTP(settings, toDelegate(request_handler));
}
/// ditto
void listenHTTP(HTTPServerSettings settings, HTTPServerRequestHandler request_handler)
{
listenHTTP(settings, &request_handler.handleRequest);
}
/**
[private] Starts a HTTP server listening on the specified port.
This is the same as listenHTTP() except that it does not use a VibeDist host for
remote listening, even if specified on the command line.
*/
private void listenHTTPPlain(HTTPServerSettings settings)
{
import std.algorithm : canFind;
static bool doListen(HTTPServerSettings settings, HTTPServerListener listener, string addr)
{
try {
bool dist = (settings.options & HTTPServerOption.distribute) != 0;
listenTCP(settings.port, (TCPConnection conn){ handleHTTPConnection(conn, listener); }, addr, dist ? TCPListenOptions.distribute : TCPListenOptions.defaults);
logInfo("Listening for HTTP%s requests on %s:%s", settings.sslContext ? "S" : "", addr, settings.port);
return true;
} catch( Exception e ) {
logWarn("Failed to listen on %s:%s", addr, settings.port);
return false;
}
}
bool any_succeeded = false;
// Check for every bind address/port, if a new listening socket needs to be created and
// check for conflicting servers
foreach (addr; settings.bindAddresses) {
bool found_listener = false;
foreach (lst; g_listeners) {
if (lst.bindAddress == addr && lst.bindPort == settings.port) {
enforce(settings.sslContext is lst.sslContext,
"A HTTP server is already listening on "~addr~":"~to!string(settings.port)~
" but the SSL context differs.");
foreach (ctx; g_contexts) {
if (ctx.settings.port != settings.port) continue;
if (!ctx.settings.bindAddresses.canFind(addr)) continue;
/*enforce(ctx.settings.hostName != settings.hostName,
"A server with the host name '"~settings.hostName~"' is already "
"listening on "~addr~":"~to!string(settings.port)~".");*/
}
found_listener = true;
any_succeeded = true;
break;
}
}
if (!found_listener) {
auto listener = HTTPServerListener(addr, settings.port, settings.sslContext);
if (doListen(settings, listener, addr)) // DMD BUG 2043
{
any_succeeded = true;
g_listeners ~= listener;
}
}
}
enforce(any_succeeded, "Failed to listen for incoming HTTP connections on any of the supplied interfaces.");
}
/**
Provides a HTTP request handler that responds with a static Diet template.
*/
@property HTTPServerRequestDelegate staticTemplate(string template_file)()
{
import vibe.templ.diet;
return (HTTPServerRequest req, 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 (by default this is $(D HTTPStatus.found)
Returns:
Returns a $(D HTTPServerRequestDelegate) that performs the redirect
*/
HTTPServerRequestDelegate staticRedirect(string url, HTTPStatus status = HTTPStatus.found)
{
return (HTTPServerRequest req, HTTPServerResponse res){
res.redirect(url, status);
};
}
/// ditto
HTTPServerRequestDelegate staticRedirect(URL url, HTTPStatus status = HTTPStatus.found)
{
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)
{
s_distHost = host;
s_distPort = port;
}
/**
Renders the given template and makes all ALIASES available to the template.
This currently suffers from multiple DMD bugs - use renderCompat() instead for the time being.
You can call this function as a member of HTTPServerResponse using D's uniform function
call syntax.
Examples:
---
string title = "Hello, World!";
int pageNumber = 1;
res.render!("mytemplate.jd", title, pageNumber);
---
*/
@property void render(string template_file, ALIASES...)(HTTPServerResponse res)
{
import vibe.templ.diet;
res.headers["Content-Type"] = "text/html; charset=UTF-8";
parseDietFile!(template_file, ALIASES)(res.bodyWriter);
}
/**
Creates a HTTPServerRequest suitable for writing unit tests.
*/
HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method = HTTPMethod.GET, InputStream data = null)
{
InetHeaderMap headers;
return createTestHTTPServerRequest(url, method, headers, data);
}
/// ditto
HTTPServerRequest createTestHTTPServerRequest(URL url, HTTPMethod method, InetHeaderMap headers, InputStream data = null)
{
auto ssl = url.schema == "https";
auto ret = new HTTPServerRequest(Clock.currTime(UTC()), url.port ? url.port : ssl ? 443 : 80);
ret.path = url.pathString;
ret.queryString = url.queryString;
ret.username = url.username;
ret.password = url.password;
ret.requestURL = url.localURI;
ret.method = method;
ret.ssl = ssl;
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)
{
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 = new ProxyStream(null, data_sink);
auto ret = new HTTPServerResponse(stream, null, settings, defaultAllocator());
return ret;
}
/**************************************************************************************************/
/* Public types */
/**************************************************************************************************/
/// Delegate based request handler
alias HTTPServerRequestDelegate = void delegate(HTTPServerRequest req, HTTPServerResponse res);
/// Static function based request handler
alias HTTPServerRequestFunction = void function(HTTPServerRequest req, HTTPServerResponse res);
/// Interface for class based request handlers
interface HTTPServerRequestHandler {
/// Handles incoming HTTP requests
void handleRequest(HTTPServerRequest req, HTTPServerResponse res);
}
/// 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);
/**
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.
*/
enum HTTPServerOption {
none = 0,
/// Fills the .path, .queryString fields in the request
parseURL = 1<<0,
/// Fills the .query field in the request
parseQueryString = 1<<1 | parseURL,
/// Fills the .form field in the request
parseFormBody = 1<<2,
/// Fills the .json field in the request
parseJsonBody = 1<<3,
/// Enables use of the .nextPart() method in the request
parseMultiPartBody = 1<<4, // todo
/// Fills the .cookies field in the request
parseCookies = 1<<5,
/// Distributes request processing among worker threads
distribute = 1<<6,
/** 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.
*/
errorStackTraces = 1<<7,
/** The default set of options.
Includes all options, except for distribute.
*/
defaults =
parseURL |
parseQueryString |
parseFormBody |
parseJsonBody |
parseMultiPartBody |
parseCookies |
errorStackTraces,
/// deprecated
None = none,
/// deprecated
ParseURL = parseURL,
/// deprecated
ParseQueryString = parseQueryString,
/// deprecated
ParseFormBody = parseFormBody,
/// deprecated
ParseJsonBody = parseJsonBody,
/// deprecated
ParseMultiPartBody = parseMultiPartBody,
/// deprecated
ParseCookies = parseCookies
}
/**
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 SSL enabled server you may want to set this
to 443 instead.
*/
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.
*/
HTTPServerOption 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;// = dur!"seconds"(0);
/** Maximum time between two request on a keep-alive connection
The default value is 10 seconds.
*/
Duration keepAliveTimeout;// = dur!"seconds"(10);
/// Maximum number of transferred bytes per request after which the connection is closed with
/// an error; not supported yet
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
HTTPServerErrorPageHandler errorPageHandler = null;
/// If set, a HTTPS server will be started instead of plain HTTP.
SSLContext sslContext;
/// 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;
/// Returns a duplicate of the settings object.
@property HTTPServerSettings dup()
{
auto ret = new HTTPServerSettings;
foreach (mem; __traits(allMembers, HTTPServerSettings)) {
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;
this()
{
// need to use the contructor because the Ubuntu 13.10 GDC cannot CTFE dur()
maxRequestTime = 0.seconds;
keepAliveTimeout = 10.seconds;
}
}
/**
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;
FixedAppender!(string, 31) m_dateAppender;
HTTPServerSettings m_settings;
ushort m_port;
}
public {
/// The IP address of the client
string peer;
/// ditto
NetworkAddress clientAddress;
/// Determines if the request was issued over an SSL encrypted channel.
bool ssl;
/** The _path part of the URL.
Remarks: This field is only set if HTTPServerOption.parseURL is set.
*/
string path;
/** The user name part of the URL, if present.
Remarks: This field is only set if HTTPServerOption.parseURL is set.
*/
string username;
/** The _password part of the URL, if present.
Remarks: This field is only set if HTTPServerOption.parseURL is set.
*/
string password;
/** The _query string part of the URL.
Remarks: This field is only set if HTTPServerOption.parseURL is set.
*/
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.
Remarks: This field is only set if HTTPServerOption.parseCookies is set.
*/
CookieValueMap cookies;
/** Contains all _form fields supplied using the _query string.
Remarks: This field is only set if HTTPServerOption.parseQueryString is set.
*/
FormFields query;
/** 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.
*/
string[string] params;
/** 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.
Remarks:
This field is only set if HTTPServerOption.parseJsonBody is set.
A JSON request must have the Content-Type "application/json".
*/
Json json;
/** Contains the parsed parameters of a HTML POST _form request.
Remarks:
This field is only set if HTTPServerOption.parseFormBody is set.
A form request must either have the Content-Type
"application/x-www-form-urlencoded" or "multipart/form-data".
*/
FormFields form;
/** Contains information about any uploaded file for a HTML _form request.
Remarks:
This field is only set if HTTPServerOption.parseFormBody is set
and if the Content-Type is "multipart/form-data".
*/
FilePartFormFields files;
/** The current Session object.
This field is set if HTTPServerResponse.startSession() has been called
on a previous response and if the client has sent back the matching
cookie.
Remarks: Requires the HTTPServerOption.parseCookies option.
*/
Session session;
}
this(SysTime time, ushort port)
{
m_timeCreated = time.toUTC();
m_port = port;
writeRFC822DateTimeString(m_dateAppender, time);
this.headers["Date"] = m_dateAppender.data();
}
/** Time when this request started processing.
*/
@property inout(SysTime) timeCreated() inout { return m_timeCreated; }
/** The full URL that corresponds to this request.
The host URL includes the protocol, host and optionally the user
and password that was used for this request. This field is useful to
construct self referencing URLs.
Note that the port is currently not set, so that this only works if
the standard port is used.
*/
@property URL fullURL()
const {
URL url;
auto fh = this.headers.get("X-Forwarded-Host", "");
if (!fh.empty) {
url.schema = this.headers.get("X-Forwarded-Proto", "http");
url.host = fh;
} else {
if (!this.host.empty) url.host = this.host;
else if (!m_settings.hostName.empty) url.host = m_settings.hostName;
else url.host = m_settings.bindAddresses[0];
if (this.ssl) {
url.schema = "https";
if (m_port != 443) url.port = 443;
} else {
url.schema = "http";
if (m_port != 80) url.port = m_port;
}
}
url.host = url.host.split(":")[0];
url.username = this.username;
url.password = this.password;
url.path = Path(path);
url.queryString = queryString;
return url;
}
/** The relative path the the root folder.
Using this function instead of absolute URLs for embedded links can be
useful to avoid dead link when the site is piped through a
reverse-proxy.
The returned string always ends with a slash.
*/
@property string rootDir() const {
if (path.length == 0) return "./";
auto depth = count(path[1 .. $], '/');
return depth == 0 ? "./" : replicate("../", depth);
}
}
/**
Represents a HTTP response as sent from the server side.
*/
final class HTTPServerResponse : HTTPResponse {
private {
Stream m_conn;
ConnectionStream m_rawConnection;
OutputStream m_bodyWriter;
Allocator m_requestAlloc;
FreeListRef!ChunkedOutputStream m_chunkedBodyWriter;
FreeListRef!CountingOutputStream m_countingWriter;
FreeListRef!GzipOutputStream m_gzipOutputStream;
FreeListRef!DeflateOutputStream m_deflateOutputStream;
HTTPServerSettings m_settings;
Session m_session;
bool m_headerWritten = false;
bool m_isHeadResponse = false;
bool m_ssl;
SysTime m_timeFinalized;
}
this(Stream conn, ConnectionStream raw_connection, HTTPServerSettings settings, Allocator req_alloc)
{
m_conn = conn;
m_rawConnection = raw_connection;
m_countingWriter = FreeListRef!CountingOutputStream(conn);
m_settings = settings;
m_requestAlloc = req_alloc;
}
@property SysTime timeFinalized() { return m_timeFinalized; }
/** Determines if the HTTP header has already been written.
*/
@property bool headerWritten() const { return m_headerWritten; }
/** Determines if the response does not need a body.
*/
bool isHeadResponse() const { return m_isHeadResponse; }
/** Determines if the response is sent over an encrypted connection.
*/
bool ssl() const { return m_ssl; }
/// Writes the entire response body at once.
void writeBody(in ubyte[] data, string content_type = null)
{
if (content_type) headers["Content-Type"] = content_type;
headers["Content-Length"] = formatAlloc(m_requestAlloc, "%d", data.length);
bodyWriter.write(data);
}
/// ditto
void writeBody(string data, string content_type = "text/plain; charset=UTF-8")
{
writeBody(cast(ubyte[])data, content_type);
}
/** Writes the whole response body at once, without doing any further encoding.
The caller has to make sure that the appropriate headers are set correctly
(i.e. Content-Type and Content-Encoding).
Note that the version taking a RandomAccessStream may perform additional
optimizations such as sending a file directly from the disk to the
network card using a DMA transfer.
*/
void writeRawBody(RandomAccessStream stream)
{
assert(!m_headerWritten, "A body was already written!");
writeHeader();
if (m_isHeadResponse) return;
auto bytes = stream.size - stream.tell();
m_conn.write(stream);
m_countingWriter.increment(bytes);
}
/// ditto
void writeRawBody(InputStream stream, size_t num_bytes = 0)
{
assert(!m_headerWritten, "A body was already written!");
writeHeader();
if (m_isHeadResponse) return;
if (num_bytes > 0) {
m_conn.write(stream, num_bytes);
m_countingWriter.increment(num_bytes);
} else m_countingWriter.write(stream, num_bytes);
}
/// Writes a JSON message with the specified status
void writeJsonBody(T)(T data, int status = HTTPStatus.OK, string content_type = "application/json; charset=UTF-8", bool allow_chunked = false)
{
import std.traits;
import vibe.stream.wrapper;
static if (is(typeof(data.data())) && isArray!(typeof(data.data()))) {
static assert(!is(T == Appender!(typeof(data.data()))), "Passed an Appender!T to writeJsonBody - this is most probably not doing what's indended.");
}
statusCode = status;
headers["Content-Type"] = content_type;
// set an explicit content-length field if chunked encoding is not allowed
if (!allow_chunked) {
import vibe.internal.rangeutil;
long length = 0;
auto counter = RangeCounter(&length);
serializeToJson(counter, data);
headers["Content-Length"] = formatAlloc(m_requestAlloc, "%d", length);
{
auto rng = StreamOutputRange(bodyWriter);
serializeToJson(&rng, data);
}
assert(this.bytesWritten == length);
} else {
auto rng = StreamOutputRange(bodyWriter);
serializeToJson(&rng, data);
}
}
/**
* Writes the response with no body.
*
* This method should be used in situations where no body is
* requested, such as a HEAD request. For an empty body, just use writeBody,
* as this method causes problems with some keep-alive connections.
*/
void writeVoidBody()
{
if (!m_isHeadResponse) {
assert("Content-Length" !in headers);
assert("Transfer-Encoding" !in headers);
}
assert(!headerWritten);
writeHeader();
}
/** A stream for writing the body of the HTTP response.
Note that after 'bodyWriter' has been accessed for the first time, it
is not allowed to change any header or the status code of the response.
*/
@property OutputStream bodyWriter()
{
assert(m_conn !is null);
if (m_bodyWriter) return m_bodyWriter;
assert(!m_headerWritten, "A void body was already written!");
if (m_isHeadResponse) {
// for HEAD requests, we define a NullOutputWriter for convenience
// - no body will be written. However, the request handler should call writeVoidBody()
// and skip writing of the body in this case.
if ("Content-Length" !in headers)
headers["Transfer-Encoding"] = "chunked";
writeHeader();
m_bodyWriter = new NullOutputStream;
return m_bodyWriter;
}
if ("Content-Encoding" in headers && "Content-Length" in headers) {
// we do not known how large the compressed body will be in advance
// so remove the content-length and use chunked transfer
headers.remove("Content-Length");
}
if ("Content-Length" in headers) {
writeHeader();
m_bodyWriter = m_countingWriter; // TODO: LimitedOutputStream(m_conn, content_length)
} else {
headers["Transfer-Encoding"] = "chunked";
writeHeader();
m_chunkedBodyWriter = FreeListRef!ChunkedOutputStream(m_countingWriter);
m_bodyWriter = m_chunkedBodyWriter;
}
if (auto pce = "Content-Encoding" in headers) {
if (*pce == "gzip") {
m_gzipOutputStream = FreeListRef!GzipOutputStream(m_bodyWriter);
m_bodyWriter = m_gzipOutputStream;
} else if (*pce == "deflate") {
m_deflateOutputStream = FreeListRef!DeflateOutputStream(m_bodyWriter);
m_bodyWriter = m_deflateOutputStream;
} else {
logWarn("Unsupported Content-Encoding set in response: '"~*pce~"'");
}
}
return m_bodyWriter;
}
/** Sends a redirect request to the client.
Params:
url = The URL to redirect to
status = The HTTP redirect status (3xx) to send - by default this is $D(D HTTPStatus.found)
*/
void redirect(string url, int status = HTTPStatus.Found)
{
statusCode = status;
headers["Location"] = url;
headers["Content-Length"] = "14";
bodyWriter.write("redirecting...");
}
/// ditto
void redirect(URL url, int status = HTTPStatus.Found)
{
redirect(url.toString(), status);
}
///
unittest {
import vibe.http.router;
void request_handler(HTTPServerRequest req, HTTPServerResponse res)
{
res.redirect("http://example.org/some_other_url");
}
void test()
{
auto router = new URLRouter;
router.get("/old_url", &request_handler);
listenHTTP(new HTTPServerSettings, router);
}
}
/** Special method sending a SWITCHING_PROTOCOLS response to the client.
*/
ConnectionStream switchProtocol(string protocol)
{
statusCode = HTTPStatus.SwitchingProtocols;
headers["Upgrade"] = protocol;
writeVoidBody();
return new ConnectionProxyStream(m_conn, m_rawConnection);
}
/** Sets the specified cookie value.
Params:
name = Name of the cookie
value = New cookie value - pass null to clear the cookie
path = Path (as seen by the client) of the directory tree in which the cookie is visible
*/
Cookie setCookie(string name, string value, string path = "/")
{
auto cookie = new Cookie();
cookie.path = path;
cookie.value = value;
if (value is null) {
cookie.maxAge = 0;
cookie.expires = "Thu, 01 Jan 1970 00:00:00 GMT";
}
cookies[name] = cookie;
return cookie;
}
/**
Initiates a new session.
The session is stored in the SessionStore that was specified when
creating the server. Depending on this, the session can be persistent
or temporary and specific to this server instance.
*/