-
Notifications
You must be signed in to change notification settings - Fork 128
/
http.d
674 lines (521 loc) · 15 KB
/
http.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
/++
OBSOLETE: Old version of my http implementation. Do not use this, instead use [arsd.http2].
I no longer work on this, use http2.d instead.
+/
/*deprecated*/ module arsd.http; // adrdox apparently loses the comment above with deprecated, i need to fix that over there.
import std.socket;
// FIXME: check Transfer-Encoding: gzip always
version(with_openssl) {
pragma(lib, "crypto");
pragma(lib, "ssl");
}
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 {
int code;
string contentType;
string[string] cookies;
string[] headers;
ubyte[] content;
}
import std.string;
static import std.algorithm;
import std.conv;
struct UriParts {
string original;
string method;
string host;
ushort port;
string path;
bool useHttps;
this(string uri) {
original = uri;
if(uri[0 .. 8] == "https://")
useHttps = true;
else
if(uri[0..7] != "http://")
throw new Exception("You must use an absolute, http or https URL.");
version(with_openssl) {} else
if(useHttps)
throw new Exception("openssl support not compiled in try -version=with_openssl");
int start = useHttps ? 8 : 7;
auto posSlash = uri[start..$].indexOf("/");
if(posSlash != -1)
posSlash += start;
if(posSlash == -1)
posSlash = uri.length;
auto posColon = uri[start..$].indexOf(":");
if(posColon != -1)
posColon += start;
if(useHttps)
port = 443;
else
port = 80;
if(posColon != -1 && posColon < posSlash) {
host = uri[start..posColon];
port = to!ushort(uri[posColon+1..posSlash]);
} else
host = uri[start..posSlash];
path = uri[posSlash..$];
if(path == "")
path = "/";
}
}
HttpResponse httpRequest(string method, string uri, const(ubyte)[] content = null, string[string] cookies = null, string[] headers = null) {
import std.socket;
auto u = UriParts(uri);
// auto f = openNetwork(u.host, u.port);
auto f = new TcpSocket();
f.connect(new InternetAddress(u.host, u.port));
void delegate(string) write = (string d) {
f.send(d);
};
char[4096] readBuffer; // rawRead actually blocks until it can fill up the whole buffer... which is broken as far as http goes so one char at a time i guess. slow lol
char[] delegate() read = () {
size_t num = f.receive(readBuffer);
return readBuffer[0..num];
};
version(with_openssl) {
import deimos.openssl.ssl;
SSL* ssl;
SSL_CTX* ctx;
if(u.useHttps) {
void sslAssert(bool ret){
if (!ret){
throw new Exception("SSL_ERROR");
}
}
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv3_client_method());
sslAssert(!(ctx is null));
ssl = SSL_new(ctx);
SSL_set_fd(ssl, f.handle);
sslAssert(SSL_connect(ssl) != -1);
write = (string d) {
SSL_write(ssl, d.ptr, cast(uint)d.length);
};
read = () {
auto len = SSL_read(ssl, readBuffer.ptr, readBuffer.length);
return readBuffer[0 .. len];
};
}
}
HttpResponse response = doHttpRequestOnHelpers(write, read, method, uri, content, cookies, headers, u.useHttps);
version(with_openssl) {
if(u.useHttps) {
SSL_free(ssl);
SSL_CTX_free(ctx);
}
}
return response;
}
/**
Executes a generic http request, returning the full result. The correct formatting
of the parameters are the caller's responsibility. Content-Length is added automatically,
but YOU must give Content-Type!
*/
HttpResponse doHttpRequestOnHelpers(void delegate(string) write, char[] delegate() read, string method, string uri, const(ubyte)[] content = null, string[string] cookies = null, string[] headers = null, bool https = false)
in {
assert(method == "POST" || method == "GET");
}
do {
auto u = UriParts(uri);
write(format("%s %s HTTP/1.1\r\n", method, u.path));
write(format("Host: %s\r\n", u.host));
write(format("Connection: close\r\n"));
if(content !is null)
write(format("Content-Length: %d\r\n", content.length));
if(cookies !is null) {
string cookieHeader = "Cookie: ";
bool first = true;
foreach(k, v; cookies) {
if(first)
first = false;
else
cookieHeader ~= "; ";
cookieHeader ~= std.uri.encodeComponent(k) ~ "=" ~ std.uri.encodeComponent(v);
}
write(format("%s\r\n", cookieHeader));
}
if(headers !is null)
foreach(header; headers)
write(format("%s\r\n", header));
write("\r\n");
if(content !is null)
write(cast(string) content);
string buffer;
string readln() {
auto idx = buffer.indexOf("\r\n");
if(idx == -1) {
auto more = read();
if(more.length == 0) { // end of file or something
auto ret = buffer;
buffer = null;
return ret;
}
buffer ~= more;
return readln();
}
auto ret = buffer[0 .. idx + 2]; // + the \r\n
if(idx + 2 < buffer.length)
buffer = buffer[idx + 2 .. $];
else
buffer = null;
return ret;
}
HttpResponse hr;
cont:
string l = readln();
if(l[0..9] != "HTTP/1.1 ")
throw new Exception("Not talking to a http server");
hr.code = to!int(l[9..12]); // HTTP/1.1 ### OK
if(hr.code == 100) { // continue
do {
l = readln();
} while(l.length > 1);
goto cont;
}
bool chunked = false;
auto line = readln();
while(line.length) {
if(line.strip.length == 0)
break;
hr.headers ~= line;
if(line.startsWith("Content-Type: "))
hr.contentType = line[14..$-1];
if(line.startsWith("Set-Cookie: ")) {
auto hdr = line["Set-Cookie: ".length .. $-1];
auto semi = hdr.indexOf(";");
if(semi != -1)
hdr = hdr[0 .. semi];
auto equal = hdr.indexOf("=");
string name, value;
if(equal == -1) {
name = hdr;
// doesn't this mean erase the cookie?
} else {
name = hdr[0 .. equal];
value = hdr[equal + 1 .. $];
}
name = std.uri.decodeComponent(name);
value = std.uri.decodeComponent(value);
hr.cookies[name] = value;
}
if(line.startsWith("Transfer-Encoding: chunked"))
chunked = true;
line = readln();
}
// there might be leftover stuff in the line buffer
ubyte[] response = cast(ubyte[]) buffer.dup;
auto part = read();
while(part.length) {
response ~= part;
part = read();
}
if(chunked) {
// read the hex length, stopping at a \r\n, ignoring everything between the new line but after the first non-valid hex character
// read binary data of that length. it is our content
// repeat until a zero sized chunk
// then read footers as headers.
int state = 0;
int size;
int start = 0;
for(int a = 0; a < response.length; a++) {
final switch(state) {
case 0: // reading hex
char c = response[a];
if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
// just keep reading
} else {
int power = 1;
size = 0;
for(int b = a-1; b >= start; b--) {
char cc = response[b];
if(cc >= 'a' && cc <= 'z')
cc -= 0x20;
int val = 0;
if(cc >= '0' && cc <= '9')
val = cc - '0';
else
val = cc - 'A' + 10;
size += power * val;
power *= 16;
}
state++;
continue;
}
break;
case 1: // reading until end of line
char c = response[a];
if(c == '\n') {
if(size == 0)
state = 3;
else
state = 2;
}
break;
case 2: // reading data
hr.content ~= response[a..a+size];
a += size;
a+= 1; // skipping a 13 10
start = a + 1;
state = 0;
break;
case 3: // reading footers
goto done; // FIXME
}
}
} else
hr.content = response;
done:
return hr;
}
/*
void main(string args[]) {
write(post("http://arsdnet.net/bugs.php", ["test" : "hey", "again" : "what"]));
}
*/
version(none):
struct Url {
string url;
}
struct BasicAuth {
string username;
string password;
}
/*
When you send something, it creates a request
and sends it asynchronously. The request object
auto request = new HttpRequest();
// 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 {
private static {
// we manage the actual connections. When a request is made on a particular
// host, we try to reuse connections. We may open more than one connection per
// host to do parallel requests.
//
// The key is the *domain name*. Multiple domains on the same address will have separate connections.
Socket[][string] socketsPerHost;
// only one request can be active on a given socket (at least HTTP < 2.0) so this is that
HttpRequest[Socket] activeRequestOnSocket;
HttpRequest[] pending; // and these are the requests that are waiting
SocketSet readSet;
void advanceConnections() {
if(readSet is null)
readSet = new SocketSet();
// are there pending requests? let's try to send them
readSet.reset();
// active requests need to be read or written to
foreach(sock, request; activeRequestOnSocket)
readSet.add(sock);
// check the other sockets just for EOF, if they close, take them out of our list,
// we'll reopen if needed upon request.
auto got = Socket.select(readSet, writeSet, null, 10.seconds /* timeout */);
if(got == 0) /* timeout */
{}
else
if(got == -1) /* interrupted */
{}
else /* ready */
{}
// call select(), do what needs to be done
// no requests are active, send the ones pending connection now
// we've completed a request, are there any more pending connection? if so, send them now
auto readSet = new SocketSet();
}
}
this() {
addConnection(this);
}
~this() {
removeConnection(this);
}
HttpResponse responseData;
HttpRequestParameters parameters;
private HttpClient parentClient;
size_t bodyBytesSent;
size_t bodyBytesReceived;
State state;
/// Called when data is received. Check the state to see what data is available.
void delegate(AsynchronousHttpRequest) onDataReceived;
enum State {
/// The request has not yet been sent
unsent,
/// The send() method has been called, but no data is
/// sent on the socket yet because the connection is busy.
pendingAvailableConnection,
/// The headers are being sent now
sendingHeaders,
/// The body is being sent now
sendingBody,
/// The request has been sent but we haven't received any response yet
waitingForResponse,
/// We have received some data and are currently receiving headers
readingHeaders,
/// All headers are available but we're still waiting on the body
readingBody,
/// The request is complete.
complete,
/// The request is aborted, either by the abort() method, or as a result of the server disconnecting
aborted
}
/// Sends now and waits for the request to finish, returning the response.
HttpResponse perform() {
send();
return waitForCompletion();
}
/// Sends the request asynchronously.
void send() {
if(state != State.unsent && state != State.aborted)
return; // already sent
responseData = HttpResponse.init;
bodyBytesSent = 0;
bodyBytesReceived = 0;
state = State.pendingAvailableConnection;
HttpResponse.advanceConnections();
}
/// Waits for the request to finish or timeout, whichever comes furst.
HttpResponse waitForCompletion() {
while(state != State.aborted && state != State.complete)
HttpResponse.advanceConnections();
return responseData;
}
/// Aborts this request.
/// Due to the nature of the HTTP protocol, aborting one request will result in all subsequent requests made on this same connection to be aborted as well.
void abort() {
parentClient.close();
}
}
struct HttpRequestParameters {
Duration timeout;
// debugging
bool useHttp11 = true;
bool acceptGzip = true;
// the request itself
HttpVerb method;
string host;
string uri;
string userAgent;
string[string] cookies;
string[] headers; /// do not duplicate host, content-length, content-type, or any others that have a specific property
string contentType;
ubyte[] bodyData;
}
interface IHttpClient {
}
enum HttpVerb { GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, CONNECT }
/*
Usage:
auto client = new HttpClient("localhost", 80);
// relative links work based on the current url
client.get("foo/bar");
client.get("baz"); // gets foo/baz
auto request = client.get("rofl");
auto response = request.waitForCompletion();
*/
/// HttpClient keeps cookies, location, and some other state to reuse connections, when possible, like a web browser.
class HttpClient {
/* Protocol restrictions, useful to disable when debugging servers */
bool useHttp11 = true;
bool useGzip = true;
/// Automatically follow a redirection?
bool followLocation = false;
@property Url location() {
return currentUrl;
}
/// High level function that works similarly to entering a url
/// into a browser.
///
/// Follows locations, updates the current url.
AsynchronousHttpRequest navigateTo(Url where) {
currentUrl = where.basedOn(currentUrl);
assert(0);
}
private Url currentUrl;
this() {
}
this(Url url) {
open(url);
}
this(string host, ushort port = 80, bool useSsl = false) {
open(host, port);
}
// FIXME: add proxy
// FIXME: some kind of caching
void open(Url url) {
}
void open(string host, ushort port = 80, bool useSsl = false) {
}
void close() {
socket.close();
}
void setCookie(string name, string value) {
}
void clearCookies() {
}
HttpResponse sendSynchronously() {
auto request = sendAsynchronously();
return request.waitForCompletion();
}
AsynchronousHttpRequest sendAsynchronously() {
}
string method;
string host;
ushort port;
string uri;
string[] headers;
ubyte[] requestBody;
string userAgent;
/* inter-request state */
string[string] cookies;
}
// FIXME: websocket