forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http2.d
5945 lines (4862 loc) · 169 KB
/
http2.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
// Copyright 2013-2022, Adam D. Ruppe.
// FIXME: websocket proxy support
// FIXME: ipv6 support
// FIXME: headers are supposed to be case insensitive. ugh.
/++
This is version 2 of my http/1.1 client implementation.
It has no dependencies for basic operation, but does require OpenSSL
libraries (or compatible) to be support HTTPS. This dynamically loaded
on-demand (meaning it won't be loaded if you don't use it, but if you do
use it, the openssl dynamic libraries must be found in the system search path).
You can compile with `-version=without_openssl` to entirely disable ssl support.
http2.d, despite its name, does NOT implement HTTP/2.0, but this
shouldn't matter for 99.9% of usage, since all servers will continue
to support HTTP/1.1 for a very long time.
History:
Automatic `100 Continue` handling was added on September 28, 2021. It doesn't
set the Expect header, so it isn't supposed to happen, but plenty of web servers
don't follow the standard anyway.
A dependency on [arsd.core] was added on March 19, 2023 (dub v11.0). Previously,
module was stand-alone. You will have add the `core.d` file from the arsd repo
to your build now if you are managing the files and builds yourself.
The benefits of this dependency include some simplified implementation code which
makes it easier for me to add more api conveniences, better exceptions with more
information, and better event loop integration with other arsd modules beyond
just the simpledisplay adapters available previously. The new integration can
also make things like heartbeat timers easier for you to code.
+/
module arsd.http2;
static import arsd.core;
///
unittest {
import arsd.http2;
void main() {
auto client = new HttpClient();
auto request = client.request(Uri("http://dlang.org/"));
auto response = request.waitForCompletion();
import std.stdio;
writeln(response.contentText);
writeln(response.code, " ", response.codeText);
writeln(response.contentType);
}
version(arsd_http2_integration_test) main(); // exclude from docs
}
// FIXME: I think I want to disable sigpipe here too.
import std.uri : encodeComponent;
debug(arsd_http2_verbose) debug=arsd_http2;
debug(arsd_http2) import std.stdio : writeln;
version=arsd_http_internal_implementation;
version(without_openssl) {}
else {
version=use_openssl;
version=with_openssl;
version(older_openssl) {} else
version=newer_openssl;
}
version(arsd_http_winhttp_implementation) {
pragma(lib, "winhttp")
import core.sys.windows.winhttp;
// FIXME: alter the dub package file too
// https://github.com/curl/curl/blob/master/lib/vtls/schannel.c
// https://docs.microsoft.com/en-us/windows/win32/secauthn/creating-an-schannel-security-context
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpreaddata
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpsendrequest
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpopenrequest
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpconnect
}
/++
Demonstrates core functionality, using the [HttpClient],
[HttpRequest] (returned by [HttpClient.navigateTo|client.navigateTo]),
and [HttpResponse] (returned by [HttpRequest.waitForCompletion|request.waitForCompletion]).
+/
unittest {
import arsd.http2;
void main() {
auto client = new HttpClient();
auto request = client.navigateTo(Uri("http://dlang.org/"));
auto response = request.waitForCompletion();
string returnedHtml = response.contentText;
}
}
// FIXME: multipart encoded file uploads needs implementation
// future: do web client api stuff
private __gshared bool defaultVerifyPeer_ = true;
void defaultVerifyPeer(bool v) {
defaultVerifyPeer_ = v;
}
debug import std.stdio;
import std.socket;
import core.time;
// FIXME: check Transfer-Encoding: gzip always
version(with_openssl) {
//pragma(lib, "crypto");
//pragma(lib, "ssl");
}
/+
HttpRequest httpRequest(string method, string url, ubyte[] content, string[string] content) {
return null;
}
+/
/**
auto request = get("http://arsdnet.net/");
request.send();
auto response = get("http://arsdnet.net/").waitForCompletion();
*/
HttpRequest get(string url) {
auto client = new HttpClient();
auto request = client.navigateTo(Uri(url));
return request;
}
/**
Do not forget to call `waitForCompletion()` on the returned object!
*/
HttpRequest post(string url, string[string] req) {
auto client = new HttpClient();
ubyte[] bdata;
foreach(k, v; req) {
if(bdata.length)
bdata ~= cast(ubyte[]) "&";
bdata ~= cast(ubyte[]) encodeComponent(k);
bdata ~= cast(ubyte[]) "=";
bdata ~= cast(ubyte[]) encodeComponent(v);
}
auto request = client.request(Uri(url), HttpVerb.POST, bdata, "application/x-www-form-urlencoded");
return request;
}
/// gets the text off a url. basic operation only.
string getText(string url) {
auto request = get(url);
auto response = request.waitForCompletion();
return cast(string) response.content;
}
/+
ubyte[] getBinary(string url, string[string] cookies = null) {
auto hr = httpRequest("GET", url, null, cookies);
if(hr.code != 200)
throw new Exception(format("HTTP answered %d instead of 200 on %s", hr.code, url));
return hr.content;
}
/**
Gets a textual document, ignoring headers. Throws on non-text or error.
*/
string get(string url, string[string] cookies = null) {
auto hr = httpRequest("GET", url, null, cookies);
if(hr.code != 200)
throw new Exception(format("HTTP answered %d instead of 200 on %s", hr.code, url));
if(hr.contentType.indexOf("text/") == -1)
throw new Exception(hr.contentType ~ " is bad content for conversion to string");
return cast(string) hr.content;
}
static import std.uri;
string post(string url, string[string] args, string[string] cookies = null) {
string content;
foreach(name, arg; args) {
if(content.length)
content ~= "&";
content ~= std.uri.encode(name) ~ "=" ~ std.uri.encode(arg);
}
auto hr = httpRequest("POST", url, cast(ubyte[]) content, cookies, ["Content-Type: application/x-www-form-urlencoded"]);
if(hr.code != 200)
throw new Exception(format("HTTP answered %d instead of 200", hr.code));
if(hr.contentType.indexOf("text/") == -1)
throw new Exception(hr.contentType ~ " is bad content for conversion to string");
return cast(string) hr.content;
}
+/
///
struct HttpResponse {
/++
The HTTP response code, if the response was completed, or some value < 100 if it was aborted or failed.
Code 0 - initial value, nothing happened
Code 1 - you called request.abort
Code 2 - connection refused
Code 3 - connection succeeded, but server disconnected early
Code 4 - server sent corrupted response (or this code has a bug and processed it wrong)
Code 5 - request timed out
Code >= 100 - a HTTP response
+/
int code;
string codeText; ///
string httpVersion; ///
string statusLine; ///
string contentType; /// The *full* content type header. See also [contentTypeMimeType] and [contentTypeCharset].
string location; /// The location header
/++
History:
Added December 5, 2020 (version 9.1)
+/
bool wasSuccessful() {
return code >= 200 && code < 400;
}
/++
Returns the mime type part of the [contentType] header.
History:
Added July 25, 2022 (version 10.9)
+/
string contentTypeMimeType() {
auto idx = contentType.indexOf(";");
if(idx == -1)
return contentType;
return contentType[0 .. idx].strip;
}
/// the charset out of content type, if present. `null` if not.
string contentTypeCharset() {
auto idx = contentType.indexOf("charset=");
if(idx == -1)
return null;
auto c = contentType[idx + "charset=".length .. $].strip;
if(c.length)
return c;
return null;
}
/++
Names and values of cookies set in the response.
History:
Prior to July 5, 2021 (dub v10.2), this was a public field instead of a property. I did
not consider this a breaking change since the intended use is completely compatible with the
property, and it was not actually implemented properly before anyway.
+/
@property string[string] cookies() const {
string[string] ret;
foreach(cookie; cookiesDetails)
ret[cookie.name] = cookie.value;
return ret;
}
/++
The full parsed-out information of cookies set in the response.
History:
Added July 5, 2021 (dub v10.2).
+/
@property CookieHeader[] cookiesDetails() inout {
CookieHeader[] ret;
foreach(header; headers) {
if(auto content = header.isHttpHeader("set-cookie")) {
// format: name=value, value might be double quoted. it MIGHT be url encoded, but im not going to attempt that since the RFC is silent.
// then there's optionally ; attr=value after that. attributes need not have a value
CookieHeader cookie;
auto remaining = content;
cookie_name:
foreach(idx, ch; remaining) {
if(ch == '=') {
cookie.name = remaining[0 .. idx].idup_if_needed;
remaining = remaining[idx + 1 .. $];
break;
}
}
cookie_value:
{
auto idx = remaining.indexOf(";");
if(idx == -1) {
cookie.value = remaining.idup_if_needed;
remaining = remaining[$..$];
} else {
cookie.value = remaining[0 .. idx].idup_if_needed;
remaining = remaining[idx + 1 .. $].stripLeft;
}
if(cookie.value.length > 2 && cookie.value[0] == '"' && cookie.value[$-1] == '"')
cookie.value = cookie.value[1 .. $ - 1];
}
cookie_attributes:
while(remaining.length) {
string name;
foreach(idx, ch; remaining) {
if(ch == '=') {
name = remaining[0 .. idx].idup_if_needed;
remaining = remaining[idx + 1 .. $];
string value;
foreach(idx2, ch2; remaining) {
if(ch2 == ';') {
value = remaining[0 .. idx2].idup_if_needed;
remaining = remaining[idx2 + 1 .. $].stripLeft;
break;
}
}
if(value is null) {
value = remaining.idup_if_needed;
remaining = remaining[$ .. $];
}
cookie.attributes[name] = value;
continue cookie_attributes;
} else if(ch == ';') {
name = remaining[0 .. idx].idup_if_needed;
remaining = remaining[idx + 1 .. $].stripLeft;
cookie.attributes[name] = "";
continue cookie_attributes;
}
}
if(remaining.length) {
cookie.attributes[remaining.idup_if_needed] = "";
remaining = remaining[$..$];
}
}
ret ~= cookie;
}
}
return ret;
}
string[] headers; /// Array of all headers returned.
string[string] headersHash; ///
ubyte[] content; /// The raw content returned in the response body.
string contentText; /// [content], but casted to string (for convenience)
alias responseText = contentText; // just cuz I do this so often.
//alias body = content;
/++
returns `new Document(this.contentText)`. Requires [arsd.dom].
+/
auto contentDom()() {
import arsd.dom;
return new Document(this.contentText);
}
/++
returns `var.fromJson(this.contentText)`. Requires [arsd.jsvar].
+/
auto contentJson()() {
import arsd.jsvar;
return var.fromJson(this.contentText);
}
HttpRequestParameters requestParameters; ///
LinkHeader[] linksStored;
bool linksLazilyParsed;
HttpResponse deepCopy() const {
HttpResponse h = cast(HttpResponse) this;
h.headers = h.headers.dup;
h.headersHash = h.headersHash.dup;
h.content = h.content.dup;
h.linksStored = h.linksStored.dup;
return h;
}
/// Returns links header sorted by "rel" attribute.
/// It returns a new array on each call.
LinkHeader[string] linksHash() {
auto links = this.links();
LinkHeader[string] ret;
foreach(link; links)
ret[link.rel] = link;
return ret;
}
/// Returns the Link header, parsed.
LinkHeader[] links() {
if(linksLazilyParsed)
return linksStored;
linksLazilyParsed = true;
LinkHeader[] ret;
auto hdrPtr = "link" in headersHash;
if(hdrPtr is null)
return ret;
auto header = *hdrPtr;
LinkHeader current;
while(header.length) {
char ch = header[0];
if(ch == '<') {
// read url
header = header[1 .. $];
size_t idx;
while(idx < header.length && header[idx] != '>')
idx++;
current.url = header[0 .. idx];
header = header[idx .. $];
} else if(ch == ';') {
// read attribute
header = header[1 .. $];
header = header.stripLeft;
size_t idx;
while(idx < header.length && header[idx] != '=')
idx++;
string name = header[0 .. idx];
if(idx + 1 < header.length)
header = header[idx + 1 .. $];
else
header = header[$ .. $];
string value;
if(header.length && header[0] == '"') {
// quoted value
header = header[1 .. $];
idx = 0;
while(idx < header.length && header[idx] != '\"')
idx++;
value = header[0 .. idx];
header = header[idx .. $];
} else if(header.length) {
// unquoted value
idx = 0;
while(idx < header.length && header[idx] != ',' && header[idx] != ' ' && header[idx] != ';')
idx++;
value = header[0 .. idx];
header = header[idx .. $].stripLeft;
}
name = name.toLower;
if(name == "rel")
current.rel = value;
else
current.attributes[name] = value;
} else if(ch == ',') {
// start another
ret ~= current;
current = LinkHeader.init;
} else if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') {
// ignore
}
if(header.length)
header = header[1 .. $];
}
ret ~= current;
linksStored = ret;
return ret;
}
}
/+
headerName MUST be all lower case and NOT have the colon on it
returns slice of the input thing after the header name
+/
private inout(char)[] isHttpHeader(inout(char)[] thing, const(char)[] headerName) {
foreach(idx, ch; thing) {
if(idx < headerName.length) {
if(headerName[idx] == '-' && ch != '-')
return null;
if((ch | ' ') != headerName[idx])
return null;
} else if(idx == headerName.length) {
if(ch != ':')
return null;
} else {
return thing[idx .. $].strip;
}
}
return null;
}
private string idup_if_needed(string s) { return s; }
private string idup_if_needed(const(char)[] s) { return s.idup; }
unittest {
assert("Cookie: foo=bar".isHttpHeader("cookie") == "foo=bar");
assert("cookie: foo=bar".isHttpHeader("cookie") == "foo=bar");
assert("cOOkie: foo=bar".isHttpHeader("cookie") == "foo=bar");
assert("Set-Cookie: foo=bar".isHttpHeader("set-cookie") == "foo=bar");
assert(!"".isHttpHeader("cookie"));
}
///
struct LinkHeader {
string url; ///
string rel; ///
string[string] attributes; /// like title, rev, media, whatever attributes
}
/++
History:
Added July 5, 2021
+/
struct CookieHeader {
string name;
string value;
string[string] attributes;
}
import std.string;
static import std.algorithm;
import std.conv;
import std.range;
private AddressFamily family(string unixSocketPath) {
if(unixSocketPath.length)
return AddressFamily.UNIX;
else // FIXME: what about ipv6?
return AddressFamily.INET;
}
version(Windows)
private class UnixAddress : Address {
this(string) {
throw new Exception("No unix address support on this system in lib yet :(");
}
override sockaddr* name() { assert(0); }
override const(sockaddr)* name() const { assert(0); }
override int nameLen() const { assert(0); }
}
// Copy pasta from cgi.d, then stripped down. unix path thing added tho
/++
Represents a URI. It offers named access to the components and relative uri resolution, though as a user of the library, you'd mostly just construct it like `Uri("http://example.com/index.html")`.
+/
struct Uri {
alias toString this; // blargh idk a url really is a string, but should it be implicit?
// scheme://userinfo@host:port/path?query#fragment
string scheme; /// e.g. "http" in "http://example.com/"
string userinfo; /// the username (and possibly a password) in the uri
string host; /// the domain name
int port; /// port number, if given. Will be zero if a port was not explicitly given
string path; /// e.g. "/folder/file.html" in "http://example.com/folder/file.html"
string query; /// the stuff after the ? in a uri
string fragment; /// the stuff after the # in a uri.
/// Breaks down a uri string to its components
this(string uri) {
size_t lastGoodIndex;
foreach(char ch; uri) {
if(ch > 127) {
break;
}
lastGoodIndex++;
}
string replacement = uri[0 .. lastGoodIndex];
foreach(char ch; uri[lastGoodIndex .. $]) {
if(ch > 127) {
// need to percent-encode any non-ascii in it
char[3] buffer;
buffer[0] = '%';
auto first = ch / 16;
auto second = ch % 16;
first += (first >= 10) ? ('A'-10) : '0';
second += (second >= 10) ? ('A'-10) : '0';
buffer[1] = cast(char) first;
buffer[2] = cast(char) second;
replacement ~= buffer[];
} else {
replacement ~= ch;
}
}
reparse(replacement);
}
/// Returns `port` if set, otherwise if scheme is https 443, otherwise always 80
int effectivePort() const @property nothrow pure @safe @nogc {
return port != 0 ? port
: scheme == "https" ? 443 : 80;
}
private string unixSocketPath = null;
/// Indicates it should be accessed through a unix socket instead of regular tcp. Returns new version without modifying this object.
Uri viaUnixSocket(string path) const {
Uri copy = this;
copy.unixSocketPath = path;
return copy;
}
/// Goes through a unix socket in the abstract namespace (linux only). Returns new version without modifying this object.
version(linux)
Uri viaAbstractSocket(string path) const {
Uri copy = this;
copy.unixSocketPath = "\0" ~ path;
return copy;
}
private void reparse(string uri) {
// from RFC 3986
// the ctRegex triples the compile time and makes ugly errors for no real benefit
// it was a nice experiment but just not worth it.
// enum ctr = ctRegex!r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?";
/*
Captures:
0 = whole url
1 = scheme, with :
2 = scheme, no :
3 = authority, with //
4 = authority, no //
5 = path
6 = query string, with ?
7 = query string, no ?
8 = anchor, with #
9 = anchor, no #
*/
// Yikes, even regular, non-CT regex is also unacceptably slow to compile. 1.9s on my computer!
// instead, I will DIY and cut that down to 0.6s on the same computer.
/*
Note that authority is
user:password@domain:port
where the user:password@ part is optional, and the :port is optional.
Regex translation:
Scheme cannot have :, /, ?, or # in it, and must have one or more chars and end in a :. It is optional, but must be first.
Authority must start with //, but cannot have any other /, ?, or # in it. It is optional.
Path cannot have any ? or # in it. It is optional.
Query must start with ? and must not have # in it. It is optional.
Anchor must start with # and can have anything else in it to end of string. It is optional.
*/
this = Uri.init; // reset all state
// empty uri = nothing special
if(uri.length == 0) {
return;
}
size_t idx;
scheme_loop: foreach(char c; uri[idx .. $]) {
switch(c) {
case ':':
case '/':
case '?':
case '#':
break scheme_loop;
default:
}
idx++;
}
if(idx == 0 && uri[idx] == ':') {
// this is actually a path! we skip way ahead
goto path_loop;
}
if(idx == uri.length) {
// the whole thing is a path, apparently
path = uri;
return;
}
if(idx > 0 && uri[idx] == ':') {
scheme = uri[0 .. idx];
idx++;
} else {
// we need to rewind; it found a / but no :, so the whole thing is prolly a path...
idx = 0;
}
if(idx + 2 < uri.length && uri[idx .. idx + 2] == "//") {
// we have an authority....
idx += 2;
auto authority_start = idx;
authority_loop: foreach(char c; uri[idx .. $]) {
switch(c) {
case '/':
case '?':
case '#':
break authority_loop;
default:
}
idx++;
}
auto authority = uri[authority_start .. idx];
auto idx2 = authority.indexOf("@");
if(idx2 != -1) {
userinfo = authority[0 .. idx2];
authority = authority[idx2 + 1 .. $];
}
if(authority.length && authority[0] == '[') {
// ipv6 address special casing
idx2 = authority.indexOf(']');
if(idx2 != -1) {
auto end = authority[idx2 + 1 .. $];
if(end.length && end[0] == ':')
idx2 = idx2 + 1;
else
idx2 = -1;
}
} else {
idx2 = authority.indexOf(":");
}
if(idx2 == -1) {
port = 0; // 0 means not specified; we should use the default for the scheme
host = authority;
} else {
host = authority[0 .. idx2];
if(idx2 + 1 < authority.length)
port = to!int(authority[idx2 + 1 .. $]);
else
port = 0;
}
}
path_loop:
auto path_start = idx;
foreach(char c; uri[idx .. $]) {
if(c == '?' || c == '#')
break;
idx++;
}
path = uri[path_start .. idx];
if(idx == uri.length)
return; // nothing more to examine...
if(uri[idx] == '?') {
idx++;
auto query_start = idx;
foreach(char c; uri[idx .. $]) {
if(c == '#')
break;
idx++;
}
query = uri[query_start .. idx];
}
if(idx < uri.length && uri[idx] == '#') {
idx++;
fragment = uri[idx .. $];
}
// uriInvalidated = false;
}
private string rebuildUri() const {
string ret;
if(scheme.length)
ret ~= scheme ~ ":";
if(userinfo.length || host.length)
ret ~= "//";
if(userinfo.length)
ret ~= userinfo ~ "@";
if(host.length)
ret ~= host;
if(port)
ret ~= ":" ~ to!string(port);
ret ~= path;
if(query.length)
ret ~= "?" ~ query;
if(fragment.length)
ret ~= "#" ~ fragment;
// uri = ret;
// uriInvalidated = false;
return ret;
}
/// Converts the broken down parts back into a complete string
string toString() const {
// if(uriInvalidated)
return rebuildUri();
}
/// Returns a new absolute Uri given a base. It treats this one as
/// relative where possible, but absolute if not. (If protocol, domain, or
/// other info is not set, the new one inherits it from the base.)
///
/// Browsers use a function like this to figure out links in html.
Uri basedOn(in Uri baseUrl) const {
Uri n = this; // copies
if(n.scheme == "data")
return n;
// n.uriInvalidated = true; // make sure we regenerate...
// userinfo is not inherited... is this wrong?
// if anything is given in the existing url, we don't use the base anymore.
if(n.scheme.empty) {
n.scheme = baseUrl.scheme;
if(n.host.empty) {
n.host = baseUrl.host;
if(n.port == 0) {
n.port = baseUrl.port;
if(n.path.length > 0 && n.path[0] != '/') {
auto b = baseUrl.path[0 .. baseUrl.path.lastIndexOf("/") + 1];
if(b.length == 0)
b = "/";
n.path = b ~ n.path;
} else if(n.path.length == 0) {
n.path = baseUrl.path;
}
}
}
}
n.removeDots();
// if still basically talking to the same thing, we should inherit the unix path
// too since basically the unix path is saying for this service, always use this override.
if(n.host == baseUrl.host && n.scheme == baseUrl.scheme && n.port == baseUrl.port)
n.unixSocketPath = baseUrl.unixSocketPath;
return n;
}
/++
Resolves ../ and ./ parts of the path. Used in the implementation of [basedOn] and you could also use it to normalize things.
+/
void removeDots() {
auto parts = this.path.split("/");
string[] toKeep;
foreach(part; parts) {
if(part == ".") {
continue;
} else if(part == "..") {
//if(toKeep.length > 1)
toKeep = toKeep[0 .. $-1];
//else
//toKeep = [""];
continue;
} else {
//if(toKeep.length && toKeep[$-1].length == 0 && part.length == 0)
//continue; // skip a `//` situation
toKeep ~= part;
}
}
auto path = toKeep.join("/");
if(path.length && path[0] != '/')
path = "/" ~ path;
this.path = path;
}
}
/*
void main(string args[]) {
write(post("http://arsdnet.net/bugs.php", ["test" : "hey", "again" : "what"]));
}
*/
///
struct BasicAuth {
string username; ///
string password; ///
}
class ProxyException : Exception {
this(string msg) {super(msg); }
}
/**
Represents a HTTP request. You usually create these through a [HttpClient].
---
auto request = new HttpRequest(); // note that when there's no associated client, some features may not work
// normally you'd instead do `new HttpClient(); client.request(...)`
// set any properties here
// synchronous usage
auto reply = request.perform();
// async usage, type 1:
request.send();
request2.send();
// wait until the first one is done, with the second one still in-flight
auto response = request.waitForCompletion();
// async usage, type 2:
request.onDataReceived = (HttpRequest hr) {
if(hr.state == HttpRequest.State.complete) {
// use hr.responseData
}
};
request.send(); // send, using the callback
// before terminating, be sure you wait for your requests to finish!
request.waitForCompletion();
---
*/
class HttpRequest {
/// Automatically follow a redirection?
bool followLocation = false;
/++
Maximum number of redirections to follow (used only if [followLocation] is set to true). Will resolve with an error if a single request has more than this number of redirections. The default value is currently 10, but may change without notice. If you need a specific value, be sure to call this function.
If you want unlimited redirects, call it with `int.max`. If you set it to 0 but set [followLocation] to `true`, any attempt at redirection will abort the request. To disable automatically following redirection, set [followLocation] to `false` so you can process the 30x code yourself as a completed request.
History:
Added July 27, 2022 (dub v10.9)
+/
void setMaximumNumberOfRedirects(int max = 10) {
maximumNumberOfRedirectsRemaining = max;
}
private int maximumNumberOfRedirectsRemaining;
/++
Set to `true` to automatically retain cookies in the associated [HttpClient] from this request.
Note that you must have constructed the request from a `HttpClient` or at least passed one into the
constructor for this to have any effect.
Bugs: