-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathClient.zig
More file actions
1851 lines (1610 loc) · 68.7 KB
/
Copy pathClient.zig
File metadata and controls
1851 lines (1610 loc) · 68.7 KB
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
//! HTTP(S) Client implementation.
//!
//! Connections are opened in a thread-safe manner, but individual Requests are not.
//!
//! TLS support may be disabled via `std.options.http_disable_tls`.
const std = @import("../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const http = std.http;
const mem = std.mem;
const Uri = std.Uri;
const Allocator = mem.Allocator;
const assert = std.debug.assert;
const Io = std.Io;
const Writer = std.Io.Writer;
const Reader = std.Io.Reader;
const HostName = std.Io.net.HostName;
const Client = @This();
pub const disable_tls = std.options.http_disable_tls;
/// Used for all client allocations. Must be thread-safe.
allocator: Allocator,
/// Used for opening TCP connections.
io: Io,
ca_bundle: if (disable_tls) void else std.crypto.Certificate.Bundle = if (disable_tls) {} else .{},
ca_bundle_mutex: std.Thread.Mutex = .{},
/// Used both for the reader and writer buffers.
tls_buffer_size: if (disable_tls) u0 else usize = if (disable_tls) 0 else std.crypto.tls.Client.min_buffer_len,
/// If non-null, ssl secrets are logged to a stream. Creating such a stream
/// allows other processes with access to that stream to decrypt all
/// traffic over connections created with this `Client`.
ssl_key_log: ?*std.crypto.tls.Client.SslKeyLog = null,
/// The time used to decide whether certificates are expired.
///
/// When this is `null`, the next time this client performs an HTTPS request,
/// it will first check the time and rescan the system for root certificates.
now: ?Io.Timestamp = null,
/// The pool of connections that can be reused (and currently in use).
connection_pool: ConnectionPool = .{},
/// Each `Connection` allocates this amount for the reader buffer.
///
/// If the entire HTTP header cannot fit in this amount of bytes,
/// `error.HttpHeadersOversize` will be returned from `Request.wait`.
read_buffer_size: usize = 8192,
/// Each `Connection` allocates this amount for the writer buffer.
write_buffer_size: usize = 1024,
/// If populated, all http traffic travels through this third party.
/// This field cannot be modified while the client has active connections.
/// Pointer to externally-owned memory.
http_proxy: ?*Proxy = null,
/// If populated, all https traffic travels through this third party.
/// This field cannot be modified while the client has active connections.
/// Pointer to externally-owned memory.
https_proxy: ?*Proxy = null,
/// A Least-Recently-Used cache of open connections to be reused.
pub const ConnectionPool = struct {
mutex: std.Thread.Mutex = .{},
/// Open connections that are currently in use.
used: std.DoublyLinkedList = .{},
/// Open connections that are not currently in use.
free: std.DoublyLinkedList = .{},
free_len: usize = 0,
free_size: usize = 32,
/// The criteria for a connection to be considered a match.
pub const Criteria = struct {
host: HostName,
port: u16,
protocol: Protocol,
};
/// Finds and acquires a connection from the connection pool matching the criteria.
/// If no connection is found, null is returned.
///
/// Threadsafe.
pub fn findConnection(pool: *ConnectionPool, criteria: Criteria) ?*Connection {
pool.mutex.lock();
defer pool.mutex.unlock();
var next = pool.free.last;
while (next) |node| : (next = node.prev) {
const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
if (connection.protocol != criteria.protocol) continue;
if (connection.port != criteria.port) continue;
// Domain names are case-insensitive (RFC 5890, Section 2.3.2.4)
if (!connection.host().eql(criteria.host)) continue;
pool.acquireUnsafe(connection);
return connection;
}
return null;
}
/// Acquires an existing connection from the connection pool. This function is not threadsafe.
pub fn acquireUnsafe(pool: *ConnectionPool, connection: *Connection) void {
pool.free.remove(&connection.pool_node);
pool.free_len -= 1;
pool.used.append(&connection.pool_node);
}
/// Acquires an existing connection from the connection pool. This function is threadsafe.
pub fn acquire(pool: *ConnectionPool, connection: *Connection) void {
pool.mutex.lock();
defer pool.mutex.unlock();
return pool.acquireUnsafe(connection);
}
/// Tries to release a connection back to the connection pool.
/// If the connection is marked as closing, it will be closed instead.
///
/// Threadsafe.
pub fn release(pool: *ConnectionPool, connection: *Connection, io: Io) void {
pool.mutex.lock();
defer pool.mutex.unlock();
pool.used.remove(&connection.pool_node);
if (connection.closing or pool.free_size == 0) return connection.destroy(io);
if (pool.free_len >= pool.free_size) {
const popped: *Connection = @alignCast(@fieldParentPtr("pool_node", pool.free.popFirst().?));
pool.free_len -= 1;
popped.destroy(io);
}
if (connection.proxied) {
// proxied connections go to the end of the queue, always try direct connections first
pool.free.prepend(&connection.pool_node);
} else {
pool.free.append(&connection.pool_node);
}
pool.free_len += 1;
}
/// Adds a newly created node to the pool of used connections. This function is threadsafe.
pub fn addUsed(pool: *ConnectionPool, connection: *Connection) void {
pool.mutex.lock();
defer pool.mutex.unlock();
pool.used.append(&connection.pool_node);
}
/// Resizes the connection pool.
///
/// If the new size is smaller than the current size, then idle connections will be closed until the pool is the new size.
///
/// Threadsafe.
pub fn resize(pool: *ConnectionPool, allocator: Allocator, new_size: usize) void {
pool.mutex.lock();
defer pool.mutex.unlock();
const next = pool.free.first;
_ = next;
while (pool.free_len > new_size) {
const popped = pool.free.popFirst() orelse unreachable;
pool.free_len -= 1;
popped.data.close(allocator);
allocator.destroy(popped);
}
pool.free_size = new_size;
}
/// Frees the connection pool and closes all connections within.
///
/// All future operations on the connection pool will deadlock.
///
/// Threadsafe.
pub fn deinit(pool: *ConnectionPool, io: Io) void {
pool.mutex.lock();
var next = pool.free.first;
while (next) |node| {
const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
next = node.next;
connection.destroy(io);
}
next = pool.used.first;
while (next) |node| {
const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
next = node.next;
connection.destroy(io);
}
pool.* = undefined;
}
};
pub const Protocol = enum {
plain,
tls,
fn port(protocol: Protocol) u16 {
return switch (protocol) {
.plain => 80,
.tls => 443,
};
}
pub fn fromScheme(scheme: []const u8) ?Protocol {
const protocol_map = std.StaticStringMap(Protocol).initComptime(.{
.{ "http", .plain },
.{ "ws", .plain },
.{ "https", .tls },
.{ "wss", .tls },
});
return protocol_map.get(scheme);
}
pub fn fromUri(uri: Uri) ?Protocol {
return fromScheme(uri.scheme);
}
};
pub const Connection = struct {
client: *Client,
stream_writer: Io.net.Stream.Writer,
stream_reader: Io.net.Stream.Reader,
/// Entry in `ConnectionPool.used` or `ConnectionPool.free`.
pool_node: std.DoublyLinkedList.Node,
port: u16,
host_len: u8,
proxied: bool,
closing: bool,
protocol: Protocol,
const Plain = struct {
connection: Connection,
fn create(
client: *Client,
remote_host: HostName,
port: u16,
stream: Io.net.Stream,
) error{OutOfMemory}!*Plain {
const io = client.io;
const gpa = client.allocator;
const alloc_len = allocLen(client, remote_host.bytes.len);
const base = try gpa.alignedAlloc(u8, .of(Plain), alloc_len);
errdefer gpa.free(base);
const host_buffer = base[@sizeOf(Plain)..][0..remote_host.bytes.len];
const socket_read_buffer = host_buffer.ptr[host_buffer.len..][0..client.read_buffer_size];
const socket_write_buffer = socket_read_buffer.ptr[socket_read_buffer.len..][0..client.write_buffer_size];
assert(base.ptr + alloc_len == socket_write_buffer.ptr + socket_write_buffer.len);
@memcpy(host_buffer, remote_host.bytes);
const plain: *Plain = @ptrCast(base);
plain.* = .{
.connection = .{
.client = client,
.stream_writer = stream.writer(io, socket_write_buffer),
.stream_reader = stream.reader(io, socket_read_buffer),
.pool_node = .{},
.port = port,
.host_len = @intCast(remote_host.bytes.len),
.proxied = false,
.closing = false,
.protocol = .plain,
},
};
return plain;
}
fn destroy(plain: *Plain) void {
const c = &plain.connection;
const gpa = c.client.allocator;
const base: [*]align(@alignOf(Plain)) u8 = @ptrCast(plain);
gpa.free(base[0..allocLen(c.client, c.host_len)]);
}
fn allocLen(client: *Client, host_len: usize) usize {
return @sizeOf(Plain) + host_len + client.read_buffer_size + client.write_buffer_size;
}
fn host(plain: *Plain) HostName {
const base: [*]u8 = @ptrCast(plain);
return .{ .bytes = base[@sizeOf(Plain)..][0..plain.connection.host_len] };
}
};
const Tls = struct {
client: std.crypto.tls.Client,
connection: Connection,
/// Asserts that `client.now` is non-null.
fn create(
client: *Client,
remote_host: HostName,
port: u16,
stream: Io.net.Stream,
) !*Tls {
const io = client.io;
const gpa = client.allocator;
const alloc_len = allocLen(client, remote_host.bytes.len);
const base = try gpa.alignedAlloc(u8, .of(Tls), alloc_len);
errdefer gpa.free(base);
const host_buffer = base[@sizeOf(Tls)..][0..remote_host.bytes.len];
// The TLS client wants enough buffer for the max encrypted frame
// size, and the HTTP body reader wants enough buffer for the
// entire HTTP header. This means we need a combined upper bound.
const tls_read_buffer_len = client.tls_buffer_size + client.read_buffer_size;
const tls_read_buffer = host_buffer.ptr[host_buffer.len..][0..tls_read_buffer_len];
const tls_write_buffer = tls_read_buffer.ptr[tls_read_buffer.len..][0..client.tls_buffer_size];
const socket_write_buffer = tls_write_buffer.ptr[tls_write_buffer.len..][0..client.write_buffer_size];
const socket_read_buffer = socket_write_buffer.ptr[socket_write_buffer.len..][0..client.tls_buffer_size];
assert(base.ptr + alloc_len == socket_read_buffer.ptr + socket_read_buffer.len);
@memcpy(host_buffer, remote_host.bytes);
const tls: *Tls = @ptrCast(base);
var random_buffer: [176]u8 = undefined;
std.crypto.random.bytes(&random_buffer);
tls.* = .{
.connection = .{
.client = client,
.stream_writer = stream.writer(io, tls_write_buffer),
.stream_reader = stream.reader(io, socket_read_buffer),
.pool_node = .{},
.port = port,
.host_len = @intCast(remote_host.bytes.len),
.proxied = false,
.closing = false,
.protocol = .tls,
},
// TODO data race here on ca_bundle if the user sets `now` to null
.client = std.crypto.tls.Client.init(
&tls.connection.stream_reader.interface,
&tls.connection.stream_writer.interface,
.{
.host = .{ .explicit = remote_host.bytes },
.ca = .{ .bundle = client.ca_bundle },
.ssl_key_log = client.ssl_key_log,
.read_buffer = tls_read_buffer,
.write_buffer = socket_write_buffer,
.entropy = &random_buffer,
.realtime_now_seconds = client.now.?.toSeconds(),
// This is appropriate for HTTPS because the HTTP headers contain
// the content length which is used to detect truncation attacks.
.allow_truncation_attacks = true,
},
) catch |err| switch (err) {
error.WriteFailed => return tls.connection.stream_writer.err.?,
error.ReadFailed => return tls.connection.stream_reader.err.?,
else => |e| return e,
},
};
return tls;
}
fn destroy(tls: *Tls) void {
const c = &tls.connection;
const gpa = c.client.allocator;
const base: [*]align(@alignOf(Tls)) u8 = @ptrCast(tls);
gpa.free(base[0..allocLen(c.client, c.host_len)]);
}
fn allocLen(client: *Client, host_len: usize) usize {
const tls_read_buffer_len = client.tls_buffer_size + client.read_buffer_size;
return @sizeOf(Tls) + host_len + tls_read_buffer_len + client.tls_buffer_size +
client.write_buffer_size + client.tls_buffer_size;
}
fn host(tls: *Tls) HostName {
const base: [*]u8 = @ptrCast(tls);
return .{ .bytes = base[@sizeOf(Tls)..][0..tls.connection.host_len] };
}
};
pub const ReadError = std.crypto.tls.Client.ReadError || Io.net.Stream.Reader.Error;
pub fn getReadError(c: *const Connection) ?ReadError {
return switch (c.protocol) {
.tls => {
if (disable_tls) unreachable;
const tls: *const Tls = @alignCast(@fieldParentPtr("connection", c));
return tls.client.read_err orelse c.stream_reader.err.?;
},
.plain => {
return c.stream_reader.err.?;
},
};
}
fn getStream(c: *Connection) Io.net.Stream {
return c.stream_reader.stream;
}
pub fn host(c: *Connection) HostName {
return switch (c.protocol) {
.tls => {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
return tls.host();
},
.plain => {
const plain: *Plain = @alignCast(@fieldParentPtr("connection", c));
return plain.host();
},
};
}
/// If this is called without calling `flush` or `end`, data will be
/// dropped unsent.
pub fn destroy(c: *Connection, io: Io) void {
c.stream_reader.stream.close(io);
switch (c.protocol) {
.tls => {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
tls.destroy();
},
.plain => {
const plain: *Plain = @alignCast(@fieldParentPtr("connection", c));
plain.destroy();
},
}
}
/// HTTP protocol from client to server.
/// This either goes directly to `stream_writer`, or to a TLS client.
pub fn writer(c: *Connection) *Writer {
return switch (c.protocol) {
.tls => {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
return &tls.client.writer;
},
.plain => &c.stream_writer.interface,
};
}
/// HTTP protocol from server to client.
/// This either comes directly from `stream_reader`, or from a TLS client.
pub fn reader(c: *Connection) *Reader {
return switch (c.protocol) {
.tls => {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
return &tls.client.reader;
},
.plain => &c.stream_reader.interface,
};
}
pub fn flush(c: *Connection) Writer.Error!void {
if (c.protocol == .tls) {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
try tls.client.writer.flush();
}
try c.stream_writer.interface.flush();
}
/// If the connection is a TLS connection, sends the close_notify alert.
///
/// Flushes all buffers.
pub fn end(c: *Connection) Writer.Error!void {
if (c.protocol == .tls) {
if (disable_tls) unreachable;
const tls: *Tls = @alignCast(@fieldParentPtr("connection", c));
try tls.client.end();
}
try c.stream_writer.interface.flush();
}
};
pub const Response = struct {
request: *Request,
/// Pointers in this struct are invalidated when the response body stream
/// is initialized.
head: Head,
pub const Head = struct {
bytes: []const u8,
version: http.Version,
status: http.Status,
reason: []const u8,
location: ?[]const u8 = null,
content_type: ?[]const u8 = null,
content_disposition: ?[]const u8 = null,
keep_alive: bool,
/// If present, the number of bytes in the response body.
content_length: ?u64 = null,
transfer_encoding: http.TransferEncoding = .none,
content_encoding: http.ContentEncoding = .identity,
pub const ParseError = error{
HttpConnectionHeaderUnsupported,
HttpContentEncodingUnsupported,
HttpHeaderContinuationsUnsupported,
HttpHeadersInvalid,
HttpTransferEncodingUnsupported,
InvalidContentLength,
};
pub fn parse(bytes: []const u8) ParseError!Head {
var res: Head = .{
.bytes = bytes,
.status = undefined,
.reason = undefined,
.version = undefined,
.keep_alive = false,
};
var it = mem.splitSequence(u8, bytes, "\r\n");
const first_line = it.first();
if (first_line.len < 12) return error.HttpHeadersInvalid;
const version: http.Version = switch (int64(first_line[0..8])) {
int64("HTTP/1.0") => .@"HTTP/1.0",
int64("HTTP/1.1") => .@"HTTP/1.1",
else => return error.HttpHeadersInvalid,
};
if (first_line[8] != ' ') return error.HttpHeadersInvalid;
const status: http.Status = @enumFromInt(parseInt3(first_line[9..12]));
const reason = mem.trimLeft(u8, first_line[12..], " ");
res.version = version;
res.status = status;
res.reason = reason;
res.keep_alive = switch (version) {
.@"HTTP/1.0" => false,
.@"HTTP/1.1" => true,
};
while (it.next()) |line| {
if (line.len == 0) return res;
switch (line[0]) {
' ', '\t' => return error.HttpHeaderContinuationsUnsupported,
else => {},
}
var line_it = mem.splitScalar(u8, line, ':');
const header_name = line_it.next().?;
const header_value = mem.trim(u8, line_it.rest(), " \t");
if (header_name.len == 0) return error.HttpHeadersInvalid;
if (std.ascii.eqlIgnoreCase(header_name, "connection")) {
res.keep_alive = !std.ascii.eqlIgnoreCase(header_value, "close");
} else if (std.ascii.eqlIgnoreCase(header_name, "content-type")) {
res.content_type = header_value;
} else if (std.ascii.eqlIgnoreCase(header_name, "location")) {
res.location = header_value;
} else if (std.ascii.eqlIgnoreCase(header_name, "content-disposition")) {
res.content_disposition = header_value;
} else if (std.ascii.eqlIgnoreCase(header_name, "transfer-encoding")) {
// Transfer-Encoding: second, first
// Transfer-Encoding: deflate, chunked
var iter = mem.splitBackwardsScalar(u8, header_value, ',');
const first = iter.first();
const trimmed_first = mem.trim(u8, first, " ");
var next: ?[]const u8 = first;
if (std.meta.stringToEnum(http.TransferEncoding, trimmed_first)) |transfer| {
if (res.transfer_encoding != .none) return error.HttpHeadersInvalid; // we already have a transfer encoding
res.transfer_encoding = transfer;
next = iter.next();
}
if (next) |second| {
const trimmed_second = mem.trim(u8, second, " ");
if (http.ContentEncoding.fromString(trimmed_second)) |transfer| {
if (res.content_encoding != .identity) return error.HttpHeadersInvalid; // double compression is not supported
res.content_encoding = transfer;
} else {
return error.HttpTransferEncodingUnsupported;
}
}
if (iter.next()) |_| return error.HttpTransferEncodingUnsupported;
} else if (std.ascii.eqlIgnoreCase(header_name, "content-length")) {
const content_length = std.fmt.parseInt(u64, header_value, 10) catch return error.InvalidContentLength;
if (res.content_length != null and res.content_length != content_length) return error.HttpHeadersInvalid;
res.content_length = content_length;
} else if (std.ascii.eqlIgnoreCase(header_name, "content-encoding")) {
if (res.content_encoding != .identity) return error.HttpHeadersInvalid;
const trimmed = mem.trim(u8, header_value, " ");
if (http.ContentEncoding.fromString(trimmed)) |ce| {
res.content_encoding = ce;
} else {
return error.HttpContentEncodingUnsupported;
}
}
}
return error.HttpHeadersInvalid; // missing empty line
}
test parse {
const response_bytes = "HTTP/1.1 200 OK\r\n" ++
"LOcation:url\r\n" ++
"content-tYpe: text/plain\r\n" ++
"content-disposition:attachment; filename=example.txt \r\n" ++
"content-Length:10\r\n" ++
"TRansfer-encoding:\tdeflate, chunked \r\n" ++
"connectioN:\t keep-alive \r\n\r\n";
const head = try Head.parse(response_bytes);
try testing.expectEqual(.@"HTTP/1.1", head.version);
try testing.expectEqualStrings("OK", head.reason);
try testing.expectEqual(.ok, head.status);
try testing.expectEqualStrings("url", head.location.?);
try testing.expectEqualStrings("text/plain", head.content_type.?);
try testing.expectEqualStrings("attachment; filename=example.txt", head.content_disposition.?);
try testing.expectEqual(true, head.keep_alive);
try testing.expectEqual(10, head.content_length.?);
try testing.expectEqual(.chunked, head.transfer_encoding);
try testing.expectEqual(.deflate, head.content_encoding);
}
pub fn iterateHeaders(h: Head) http.HeaderIterator {
return .init(h.bytes);
}
test iterateHeaders {
const response_bytes = "HTTP/1.1 200 OK\r\n" ++
"LOcation:url\r\n" ++
"content-tYpe: text/plain\r\n" ++
"content-disposition:attachment; filename=example.txt \r\n" ++
"content-Length:10\r\n" ++
"TRansfer-encoding:\tdeflate, chunked \r\n" ++
"connectioN:\t keep-alive \r\n\r\n";
const head = try Head.parse(response_bytes);
var it = head.iterateHeaders();
{
const header = it.next().?;
try testing.expectEqualStrings("LOcation", header.name);
try testing.expectEqualStrings("url", header.value);
try testing.expect(!it.is_trailer);
}
{
const header = it.next().?;
try testing.expectEqualStrings("content-tYpe", header.name);
try testing.expectEqualStrings("text/plain", header.value);
try testing.expect(!it.is_trailer);
}
{
const header = it.next().?;
try testing.expectEqualStrings("content-disposition", header.name);
try testing.expectEqualStrings("attachment; filename=example.txt", header.value);
try testing.expect(!it.is_trailer);
}
{
const header = it.next().?;
try testing.expectEqualStrings("content-Length", header.name);
try testing.expectEqualStrings("10", header.value);
try testing.expect(!it.is_trailer);
}
{
const header = it.next().?;
try testing.expectEqualStrings("TRansfer-encoding", header.name);
try testing.expectEqualStrings("deflate, chunked", header.value);
try testing.expect(!it.is_trailer);
}
{
const header = it.next().?;
try testing.expectEqualStrings("connectioN", header.name);
try testing.expectEqualStrings("keep-alive", header.value);
try testing.expect(!it.is_trailer);
}
try testing.expectEqual(null, it.next());
}
inline fn int64(array: *const [8]u8) u64 {
return @bitCast(array.*);
}
fn parseInt3(text: *const [3]u8) u10 {
const nnn: @Vector(3, u8) = text.*;
const zero: @Vector(3, u8) = .{ '0', '0', '0' };
const mmm: @Vector(3, u10) = .{ 100, 10, 1 };
return @reduce(.Add, (nnn -% zero) *% mmm);
}
test parseInt3 {
const expectEqual = testing.expectEqual;
try expectEqual(@as(u10, 0), parseInt3("000"));
try expectEqual(@as(u10, 418), parseInt3("418"));
try expectEqual(@as(u10, 999), parseInt3("999"));
}
/// Help the programmer avoid bugs by calling this when the string
/// memory of `Head` becomes invalidated.
fn invalidateStrings(h: *Head) void {
h.bytes = undefined;
h.reason = undefined;
if (h.location) |*s| s.* = undefined;
if (h.content_type) |*s| s.* = undefined;
if (h.content_disposition) |*s| s.* = undefined;
}
};
/// If compressed body has been negotiated this will return compressed bytes.
///
/// If the returned `Reader` returns `error.ReadFailed` the error is
/// available via `bodyErr`.
///
/// Asserts that this function is only called once.
///
/// See also:
/// * `readerDecompressing`
pub fn reader(response: *Response, transfer_buffer: []u8) *Reader {
response.head.invalidateStrings();
const req = response.request;
if (!req.method.responseHasBody()) return .ending;
const head = &response.head;
return req.reader.bodyReader(transfer_buffer, head.transfer_encoding, head.content_length);
}
/// If compressed body has been negotiated this will return decompressed bytes.
///
/// If the returned `Reader` returns `error.ReadFailed` the error is
/// available via `bodyErr`.
///
/// Asserts that this function is only called once.
///
/// See also:
/// * `reader`
pub fn readerDecompressing(
response: *Response,
transfer_buffer: []u8,
decompress: *http.Decompress,
decompress_buffer: []u8,
) *Reader {
response.head.invalidateStrings();
const head = &response.head;
return response.request.reader.bodyReaderDecompressing(
transfer_buffer,
head.transfer_encoding,
head.content_length,
head.content_encoding,
decompress,
decompress_buffer,
);
}
/// After receiving `error.ReadFailed` from the `Reader` returned by
/// `reader` or `readerDecompressing`, this function accesses the
/// more specific error code.
pub fn bodyErr(response: *const Response) ?http.Reader.BodyError {
return response.request.reader.body_err;
}
pub fn iterateTrailers(response: *const Response) http.HeaderIterator {
const r = &response.request.reader;
assert(r.state == .ready);
return .{
.bytes = r.trailers,
.index = 0,
.is_trailer = true,
};
}
};
pub const Request = struct {
/// This field is provided so that clients can observe redirected URIs.
///
/// Its backing memory is externally provided by API users when creating a
/// request, and then again provided externally via `redirect_buffer` to
/// `receiveHead`.
uri: Uri,
client: *Client,
/// This is null when the connection is released.
connection: ?*Connection,
reader: http.Reader,
keep_alive: bool,
method: http.Method,
version: http.Version = .@"HTTP/1.1",
transfer_encoding: TransferEncoding,
redirect_behavior: RedirectBehavior,
accept_encoding: @TypeOf(default_accept_encoding) = default_accept_encoding,
/// Whether the request should handle a 100-continue response before sending the request body.
handle_continue: bool,
/// Standard headers that have default, but overridable, behavior.
headers: Headers,
/// Populated in `receiveHead`; used in `deinit` to determine whether to
/// discard the body to reuse the connection.
response_content_length: ?u64 = null,
/// Populated in `receiveHead`; used in `deinit` to determine whether to
/// discard the body to reuse the connection.
response_transfer_encoding: http.TransferEncoding = .none,
/// These headers are kept including when following a redirect to a
/// different domain.
/// Externally-owned; must outlive the Request.
extra_headers: []const http.Header,
/// These headers are stripped when following a redirect to a different
/// domain.
/// Externally-owned; must outlive the Request.
privileged_headers: []const http.Header,
pub const default_accept_encoding: [@typeInfo(http.ContentEncoding).@"enum".fields.len]bool = b: {
var result: [@typeInfo(http.ContentEncoding).@"enum".fields.len]bool = @splat(false);
result[@intFromEnum(http.ContentEncoding.gzip)] = true;
result[@intFromEnum(http.ContentEncoding.deflate)] = true;
result[@intFromEnum(http.ContentEncoding.identity)] = true;
break :b result;
};
pub const TransferEncoding = union(enum) {
content_length: u64,
chunked: void,
none: void,
};
pub const Headers = struct {
host: Value = .default,
authorization: Value = .default,
user_agent: Value = .default,
connection: Value = .default,
accept_encoding: Value = .default,
content_type: Value = .default,
pub const Value = union(enum) {
default,
omit,
override: []const u8,
};
};
/// Any value other than `not_allowed` or `unhandled` means that integer represents
/// how many remaining redirects are allowed.
pub const RedirectBehavior = enum(u16) {
/// The next redirect will cause an error.
not_allowed = 0,
/// Redirects are passed to the client to analyze the redirect response
/// directly.
unhandled = std.math.maxInt(u16),
_,
pub fn init(n: u16) RedirectBehavior {
assert(n != std.math.maxInt(u16));
return @enumFromInt(n);
}
pub fn subtractOne(rb: *RedirectBehavior) void {
switch (rb.*) {
.not_allowed => unreachable,
.unhandled => unreachable,
_ => rb.* = @enumFromInt(@intFromEnum(rb.*) - 1),
}
}
pub fn remaining(rb: RedirectBehavior) u16 {
assert(rb != .unhandled);
return @intFromEnum(rb);
}
};
/// Returns the request's `Connection` back to the pool of the `Client`.
pub fn deinit(r: *Request) void {
const io = r.client.io;
if (r.connection) |connection| {
connection.closing = connection.closing or switch (r.reader.state) {
.ready => false,
.received_head => c: {
if (r.method.requestHasBody()) break :c true;
if (!r.method.responseHasBody()) break :c false;
const reader = r.reader.bodyReader(&.{}, r.response_transfer_encoding, r.response_content_length);
_ = reader.discardRemaining() catch |err| switch (err) {
error.ReadFailed => break :c true,
};
break :c r.reader.state != .ready;
},
else => true,
};
r.client.connection_pool.release(connection, io);
}
r.* = undefined;
}
/// Sends and flushes a complete request as only HTTP head, no body.
pub fn sendBodiless(r: *Request) Writer.Error!void {
try sendBodilessUnflushed(r);
try r.connection.?.flush();
}
/// Sends but does not flush a complete request as only HTTP head, no body.
pub fn sendBodilessUnflushed(r: *Request) Writer.Error!void {
assert(r.transfer_encoding == .none);
assert(!r.method.requestHasBody());
try sendHead(r);
}
/// Transfers the HTTP head over the connection and flushes.
///
/// See also:
/// * `sendBodyUnflushed`
pub fn sendBody(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter {
const result = try sendBodyUnflushed(r, buffer);
try r.connection.?.flush();
return result;
}
/// Transfers the HTTP head and body over the connection and flushes.
pub fn sendBodyComplete(r: *Request, body: []u8) Writer.Error!void {
r.transfer_encoding = .{ .content_length = body.len };
var bw = try sendBodyUnflushed(r, body);
bw.writer.end = body.len;
try bw.end();
try r.connection.?.flush();
}
/// Transfers the HTTP head over the connection, which is not flushed until
/// `BodyWriter.flush` or `BodyWriter.end` is called.
///
/// See also:
/// * `sendBody`
pub fn sendBodyUnflushed(r: *Request, buffer: []u8) Writer.Error!http.BodyWriter {
assert(r.method.requestHasBody());
try sendHead(r);
const http_protocol_output = r.connection.?.writer();
return switch (r.transfer_encoding) {
.chunked => .{
.http_protocol_output = http_protocol_output,
.state = .init_chunked,
.writer = .{
.buffer = buffer,
.vtable = &.{
.drain = http.BodyWriter.chunkedDrain,
.sendFile = http.BodyWriter.chunkedSendFile,
},
},
},
.content_length => |len| .{
.http_protocol_output = http_protocol_output,
.state = .{ .content_length = len },
.writer = .{
.buffer = buffer,
.vtable = &.{
.drain = http.BodyWriter.contentLengthDrain,
.sendFile = http.BodyWriter.contentLengthSendFile,
},
},
},
.none => .{
.http_protocol_output = http_protocol_output,
.state = .none,
.writer = .{
.buffer = buffer,
.vtable = &.{
.drain = http.BodyWriter.noneDrain,
.sendFile = http.BodyWriter.noneSendFile,
},
},
},
};
}
/// Sends HTTP headers without flushing.
fn sendHead(r: *Request) Writer.Error!void {
const uri = r.uri;
const connection = r.connection.?;
const w = connection.writer();
try w.writeAll(@tagName(r.method));
try w.writeByte(' ');
if (r.method == .CONNECT) {
try uri.writeToStream(w, .{ .authority = true });
} else {
try uri.writeToStream(w, .{
.scheme = connection.proxied,
.authentication = connection.proxied,
.authority = connection.proxied,
.path = true,
.query = true,
});
}