-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
role.rs
3085 lines (2775 loc) · 104 KB
/
role.rs
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
use std::mem::MaybeUninit;
#[cfg(feature = "client")]
use std::fmt::{self, Write as _};
use bytes::Bytes;
use bytes::BytesMut;
#[cfg(feature = "client")]
use http::header::Entry;
#[cfg(feature = "server")]
use http::header::ValueIter;
use http::header::{self, HeaderMap, HeaderName, HeaderValue};
use http::{Method, StatusCode, Version};
use smallvec::{smallvec, smallvec_inline, SmallVec};
use crate::body::DecodedLength;
#[cfg(feature = "server")]
use crate::common::date;
use crate::error::Parse;
use crate::ext::HeaderCaseMap;
#[cfg(feature = "ffi")]
use crate::ext::OriginalHeaderOrder;
use crate::headers;
use crate::proto::h1::{
Encode, Encoder, Http1Transaction, ParseContext, ParseResult, ParsedMessage,
};
#[cfg(feature = "client")]
use crate::proto::RequestHead;
use crate::proto::{BodyLength, MessageHead, RequestLine};
pub(crate) const DEFAULT_MAX_HEADERS: usize = 100;
const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific
#[cfg(feature = "server")]
const MAX_URI_LEN: usize = (u16::MAX - 1) as usize;
macro_rules! header_name {
($bytes:expr) => {{
{
match HeaderName::from_bytes($bytes) {
Ok(name) => name,
Err(e) => maybe_panic!(e),
}
}
}};
}
macro_rules! header_value {
($bytes:expr) => {{
{
unsafe { HeaderValue::from_maybe_shared_unchecked($bytes) }
}
}};
}
macro_rules! maybe_panic {
($($arg:tt)*) => ({
let _err = ($($arg)*);
if cfg!(debug_assertions) {
panic!("{:?}", _err);
} else {
error!("Internal Hyper error, please report {:?}", _err);
return Err(Parse::Internal)
}
})
}
pub(super) fn parse_headers<T>(
bytes: &mut BytesMut,
prev_len: Option<usize>,
ctx: ParseContext<'_>,
) -> ParseResult<T::Incoming>
where
T: Http1Transaction,
{
// If the buffer is empty, don't bother entering the span, it's just noise.
if bytes.is_empty() {
return Ok(None);
}
let _entered = trace_span!("parse_headers");
if let Some(prev_len) = prev_len {
if !is_complete_fast(bytes, prev_len) {
return Ok(None);
}
}
T::parse(bytes, ctx)
}
/// A fast scan for the end of a message.
/// Used when there was a partial read, to skip full parsing on a
/// a slow connection.
fn is_complete_fast(bytes: &[u8], prev_len: usize) -> bool {
let start = if prev_len < 3 { 0 } else { prev_len - 3 };
let bytes = &bytes[start..];
for (i, b) in bytes.iter().copied().enumerate() {
if b == b'\r' {
if bytes[i + 1..].chunks(3).next() == Some(&b"\n\r\n"[..]) {
return true;
}
} else if b == b'\n' {
if bytes.get(i + 1) == Some(&b'\n') {
return true;
}
}
}
false
}
pub(super) fn encode_headers<T>(
enc: Encode<'_, T::Outgoing>,
dst: &mut Vec<u8>,
) -> crate::Result<Encoder>
where
T: Http1Transaction,
{
let _entered = trace_span!("encode_headers");
T::encode(enc, dst)
}
// There are 2 main roles, Client and Server.
#[cfg(feature = "client")]
pub(crate) enum Client {}
#[cfg(feature = "server")]
pub(crate) enum Server {}
#[cfg(feature = "server")]
impl Http1Transaction for Server {
type Incoming = RequestLine;
type Outgoing = StatusCode;
#[cfg(feature = "tracing")]
const LOG: &'static str = "{role=server}";
fn parse(buf: &mut BytesMut, ctx: ParseContext<'_>) -> ParseResult<RequestLine> {
debug_assert!(!buf.is_empty(), "parse called with empty buf");
let mut keep_alive;
let is_http_11;
let subject;
let version;
let len;
let headers_len;
let method;
let path_range;
// Both headers_indices and headers are using uninitialized memory,
// but we *never* read any of it until after httparse has assigned
// values into it. By not zeroing out the stack memory, this saves
// a good ~5% on pipeline benchmarks.
let mut headers_indices: SmallVec<[MaybeUninit<HeaderIndices>; DEFAULT_MAX_HEADERS]> =
match ctx.h1_max_headers {
Some(cap) => smallvec![MaybeUninit::uninit(); cap],
None => smallvec_inline![MaybeUninit::uninit(); DEFAULT_MAX_HEADERS],
};
{
let mut headers: SmallVec<[MaybeUninit<httparse::Header<'_>>; DEFAULT_MAX_HEADERS]> =
match ctx.h1_max_headers {
Some(cap) => smallvec![MaybeUninit::uninit(); cap],
None => smallvec_inline![MaybeUninit::uninit(); DEFAULT_MAX_HEADERS],
};
trace!(bytes = buf.len(), "Request.parse");
let mut req = httparse::Request::new(&mut []);
let bytes = buf.as_ref();
match req.parse_with_uninit_headers(bytes, &mut headers) {
Ok(httparse::Status::Complete(parsed_len)) => {
trace!("Request.parse Complete({})", parsed_len);
len = parsed_len;
let uri = req.path.unwrap();
if uri.len() > MAX_URI_LEN {
return Err(Parse::UriTooLong);
}
method = Method::from_bytes(req.method.unwrap().as_bytes())?;
path_range = Server::record_path_range(bytes, uri);
version = if req.version.unwrap() == 1 {
keep_alive = true;
is_http_11 = true;
Version::HTTP_11
} else {
keep_alive = false;
is_http_11 = false;
Version::HTTP_10
};
record_header_indices(bytes, req.headers, &mut headers_indices)?;
headers_len = req.headers.len();
}
Ok(httparse::Status::Partial) => return Ok(None),
Err(err) => {
return Err(match err {
// if invalid Token, try to determine if for method or path
httparse::Error::Token => {
if req.method.is_none() {
Parse::Method
} else {
debug_assert!(req.path.is_none());
Parse::Uri
}
}
other => other.into(),
});
}
}
};
let slice = buf.split_to(len).freeze();
let uri = {
let uri_bytes = slice.slice_ref(&slice[path_range]);
// TODO(lucab): switch to `Uri::from_shared()` once public.
http::Uri::from_maybe_shared(uri_bytes)?
};
subject = RequestLine(method, uri);
// According to https://tools.ietf.org/html/rfc7230#section-3.3.3
// 1. (irrelevant to Request)
// 2. (irrelevant to Request)
// 3. Transfer-Encoding: chunked has a chunked body.
// 4. If multiple differing Content-Length headers or invalid, close connection.
// 5. Content-Length header has a sized body.
// 6. Length 0.
// 7. (irrelevant to Request)
let mut decoder = DecodedLength::ZERO;
let mut expect_continue = false;
let mut con_len = None;
let mut is_te = false;
let mut is_te_chunked = false;
let mut wants_upgrade = subject.0 == Method::CONNECT;
let mut header_case_map = if ctx.preserve_header_case {
Some(HeaderCaseMap::default())
} else {
None
};
#[cfg(feature = "ffi")]
let mut header_order = if ctx.preserve_header_order {
Some(OriginalHeaderOrder::default())
} else {
None
};
let mut headers = ctx.cached_headers.take().unwrap_or_default();
headers.reserve(headers_len);
for header in &headers_indices[..headers_len] {
// SAFETY: array is valid up to `headers_len`
let header = unsafe { header.assume_init_ref() };
let name = header_name!(&slice[header.name.0..header.name.1]);
let value = header_value!(slice.slice(header.value.0..header.value.1));
match name {
header::TRANSFER_ENCODING => {
// https://tools.ietf.org/html/rfc7230#section-3.3.3
// If Transfer-Encoding header is present, and 'chunked' is
// not the final encoding, and this is a Request, then it is
// malformed. A server should respond with 400 Bad Request.
if !is_http_11 {
debug!("HTTP/1.0 cannot have Transfer-Encoding header");
return Err(Parse::transfer_encoding_unexpected());
}
is_te = true;
if headers::is_chunked_(&value) {
is_te_chunked = true;
decoder = DecodedLength::CHUNKED;
} else {
is_te_chunked = false;
}
}
header::CONTENT_LENGTH => {
if is_te {
continue;
}
let len = headers::content_length_parse(&value)
.ok_or_else(Parse::content_length_invalid)?;
if let Some(prev) = con_len {
if prev != len {
debug!(
"multiple Content-Length headers with different values: [{}, {}]",
prev, len,
);
return Err(Parse::content_length_invalid());
}
// we don't need to append this secondary length
continue;
}
decoder = DecodedLength::checked_new(len)?;
con_len = Some(len);
}
header::CONNECTION => {
// keep_alive was previously set to default for Version
if keep_alive {
// HTTP/1.1
keep_alive = !headers::connection_close(&value);
} else {
// HTTP/1.0
keep_alive = headers::connection_keep_alive(&value);
}
}
header::EXPECT => {
// According to https://datatracker.ietf.org/doc/html/rfc2616#section-14.20
// Comparison of expectation values is case-insensitive for unquoted tokens
// (including the 100-continue token)
expect_continue = value.as_bytes().eq_ignore_ascii_case(b"100-continue");
}
header::UPGRADE => {
// Upgrades are only allowed with HTTP/1.1
wants_upgrade = is_http_11;
}
_ => (),
}
if let Some(ref mut header_case_map) = header_case_map {
header_case_map.append(&name, slice.slice(header.name.0..header.name.1));
}
#[cfg(feature = "ffi")]
if let Some(ref mut header_order) = header_order {
header_order.append(&name);
}
headers.append(name, value);
}
if is_te && !is_te_chunked {
debug!("request with transfer-encoding header, but not chunked, bad request");
return Err(Parse::transfer_encoding_invalid());
}
let mut extensions = http::Extensions::default();
if let Some(header_case_map) = header_case_map {
extensions.insert(header_case_map);
}
#[cfg(feature = "ffi")]
if let Some(header_order) = header_order {
extensions.insert(header_order);
}
*ctx.req_method = Some(subject.0.clone());
Ok(Some(ParsedMessage {
head: MessageHead {
version,
subject,
headers,
extensions,
},
decode: decoder,
expect_continue,
keep_alive,
wants_upgrade,
}))
}
fn encode(mut msg: Encode<'_, Self::Outgoing>, dst: &mut Vec<u8>) -> crate::Result<Encoder> {
trace!(
"Server::encode status={:?}, body={:?}, req_method={:?}",
msg.head.subject,
msg.body,
msg.req_method
);
let mut wrote_len = false;
// hyper currently doesn't support returning 1xx status codes as a Response
// This is because Service only allows returning a single Response, and
// so if you try to reply with a e.g. 100 Continue, you have no way of
// replying with the latter status code response.
let (ret, is_last) = if msg.head.subject == StatusCode::SWITCHING_PROTOCOLS {
(Ok(()), true)
} else if msg.req_method == &Some(Method::CONNECT) && msg.head.subject.is_success() {
// Sending content-length or transfer-encoding header on 2xx response
// to CONNECT is forbidden in RFC 7231.
wrote_len = true;
(Ok(()), true)
} else if msg.head.subject.is_informational() {
warn!("response with 1xx status code not supported");
*msg.head = MessageHead::default();
msg.head.subject = StatusCode::INTERNAL_SERVER_ERROR;
msg.body = None;
(Err(crate::Error::new_user_unsupported_status_code()), true)
} else {
(Ok(()), !msg.keep_alive)
};
// In some error cases, we don't know about the invalid message until already
// pushing some bytes onto the `dst`. In those cases, we don't want to send
// the half-pushed message, so rewind to before.
let orig_len = dst.len();
let init_cap = 30 + msg.head.headers.len() * AVERAGE_HEADER_SIZE;
dst.reserve(init_cap);
let custom_reason_phrase = msg.head.extensions.get::<crate::ext::ReasonPhrase>();
if msg.head.version == Version::HTTP_11
&& msg.head.subject == StatusCode::OK
&& custom_reason_phrase.is_none()
{
extend(dst, b"HTTP/1.1 200 OK\r\n");
} else {
match msg.head.version {
Version::HTTP_10 => extend(dst, b"HTTP/1.0 "),
Version::HTTP_11 => extend(dst, b"HTTP/1.1 "),
Version::HTTP_2 => {
debug!("response with HTTP2 version coerced to HTTP/1.1");
extend(dst, b"HTTP/1.1 ");
}
other => panic!("unexpected response version: {:?}", other),
}
extend(dst, msg.head.subject.as_str().as_bytes());
extend(dst, b" ");
if let Some(reason) = custom_reason_phrase {
extend(dst, reason.as_bytes());
} else {
// a reason MUST be written, as many parsers will expect it.
extend(
dst,
msg.head
.subject
.canonical_reason()
.unwrap_or("<none>")
.as_bytes(),
);
}
extend(dst, b"\r\n");
}
let orig_headers;
let extensions = std::mem::take(&mut msg.head.extensions);
let orig_headers = match extensions.get::<HeaderCaseMap>() {
None if msg.title_case_headers => {
orig_headers = HeaderCaseMap::default();
Some(&orig_headers)
}
orig_headers => orig_headers,
};
let encoder = if let Some(orig_headers) = orig_headers {
Self::encode_headers_with_original_case(
msg,
dst,
is_last,
orig_len,
wrote_len,
orig_headers,
)?
} else {
Self::encode_headers_with_lower_case(msg, dst, is_last, orig_len, wrote_len)?
};
ret.map(|()| encoder)
}
fn on_error(err: &crate::Error) -> Option<MessageHead<Self::Outgoing>> {
use crate::error::Kind;
let status = match *err.kind() {
Kind::Parse(Parse::Method)
| Kind::Parse(Parse::Header(_))
| Kind::Parse(Parse::Uri)
| Kind::Parse(Parse::Version) => StatusCode::BAD_REQUEST,
Kind::Parse(Parse::TooLarge) => StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE,
Kind::Parse(Parse::UriTooLong) => StatusCode::URI_TOO_LONG,
_ => return None,
};
debug!("sending automatic response ({}) for parse error", status);
let msg = MessageHead {
subject: status,
..Default::default()
};
Some(msg)
}
fn is_server() -> bool {
true
}
fn update_date() {
date::update();
}
}
#[cfg(feature = "server")]
impl Server {
fn can_have_body(method: &Option<Method>, status: StatusCode) -> bool {
Server::can_chunked(method, status)
}
fn can_chunked(method: &Option<Method>, status: StatusCode) -> bool {
if method == &Some(Method::HEAD)
|| method == &Some(Method::CONNECT) && status.is_success()
|| status.is_informational()
{
false
} else {
!matches!(status, StatusCode::NO_CONTENT | StatusCode::NOT_MODIFIED)
}
}
fn can_have_content_length(method: &Option<Method>, status: StatusCode) -> bool {
if status.is_informational() || method == &Some(Method::CONNECT) && status.is_success() {
false
} else {
!matches!(status, StatusCode::NO_CONTENT | StatusCode::NOT_MODIFIED)
}
}
fn can_have_implicit_zero_content_length(method: &Option<Method>, status: StatusCode) -> bool {
Server::can_have_content_length(method, status) && method != &Some(Method::HEAD)
}
fn encode_headers_with_lower_case(
msg: Encode<'_, StatusCode>,
dst: &mut Vec<u8>,
is_last: bool,
orig_len: usize,
wrote_len: bool,
) -> crate::Result<Encoder> {
struct LowercaseWriter;
impl HeaderNameWriter for LowercaseWriter {
#[inline]
fn write_full_header_line(
&mut self,
dst: &mut Vec<u8>,
line: &str,
_: (HeaderName, &str),
) {
extend(dst, line.as_bytes())
}
#[inline]
fn write_header_name_with_colon(
&mut self,
dst: &mut Vec<u8>,
name_with_colon: &str,
_: HeaderName,
) {
extend(dst, name_with_colon.as_bytes())
}
#[inline]
fn write_header_name(&mut self, dst: &mut Vec<u8>, name: &HeaderName) {
extend(dst, name.as_str().as_bytes())
}
}
Self::encode_headers(msg, dst, is_last, orig_len, wrote_len, LowercaseWriter)
}
#[cold]
#[inline(never)]
fn encode_headers_with_original_case(
msg: Encode<'_, StatusCode>,
dst: &mut Vec<u8>,
is_last: bool,
orig_len: usize,
wrote_len: bool,
orig_headers: &HeaderCaseMap,
) -> crate::Result<Encoder> {
struct OrigCaseWriter<'map> {
map: &'map HeaderCaseMap,
current: Option<(HeaderName, ValueIter<'map, Bytes>)>,
title_case_headers: bool,
}
impl HeaderNameWriter for OrigCaseWriter<'_> {
#[inline]
fn write_full_header_line(
&mut self,
dst: &mut Vec<u8>,
_: &str,
(name, rest): (HeaderName, &str),
) {
self.write_header_name(dst, &name);
extend(dst, rest.as_bytes());
}
#[inline]
fn write_header_name_with_colon(
&mut self,
dst: &mut Vec<u8>,
_: &str,
name: HeaderName,
) {
self.write_header_name(dst, &name);
extend(dst, b": ");
}
#[inline]
fn write_header_name(&mut self, dst: &mut Vec<u8>, name: &HeaderName) {
let Self {
map,
ref mut current,
title_case_headers,
} = *self;
if current.as_ref().map_or(true, |(last, _)| last != name) {
*current = None;
}
let (_, values) =
current.get_or_insert_with(|| (name.clone(), map.get_all_internal(name)));
if let Some(orig_name) = values.next() {
extend(dst, orig_name);
} else if title_case_headers {
title_case(dst, name.as_str().as_bytes());
} else {
extend(dst, name.as_str().as_bytes());
}
}
}
let header_name_writer = OrigCaseWriter {
map: orig_headers,
current: None,
title_case_headers: msg.title_case_headers,
};
Self::encode_headers(msg, dst, is_last, orig_len, wrote_len, header_name_writer)
}
#[inline]
fn encode_headers<W>(
msg: Encode<'_, StatusCode>,
dst: &mut Vec<u8>,
mut is_last: bool,
orig_len: usize,
mut wrote_len: bool,
mut header_name_writer: W,
) -> crate::Result<Encoder>
where
W: HeaderNameWriter,
{
// In some error cases, we don't know about the invalid message until already
// pushing some bytes onto the `dst`. In those cases, we don't want to send
// the half-pushed message, so rewind to before.
let rewind = |dst: &mut Vec<u8>| {
dst.truncate(orig_len);
};
let mut encoder = Encoder::length(0);
let mut allowed_trailer_fields: Option<Vec<HeaderValue>> = None;
let mut wrote_date = false;
let mut cur_name = None;
let mut is_name_written = false;
let mut must_write_chunked = false;
let mut prev_con_len = None;
macro_rules! handle_is_name_written {
() => {{
if is_name_written {
// we need to clean up and write the newline
debug_assert_ne!(
&dst[dst.len() - 2..],
b"\r\n",
"previous header wrote newline but set is_name_written"
);
if must_write_chunked {
extend(dst, b", chunked\r\n");
} else {
extend(dst, b"\r\n");
}
}
}};
}
'headers: for (opt_name, value) in msg.head.headers.drain() {
if let Some(n) = opt_name {
cur_name = Some(n);
handle_is_name_written!();
is_name_written = false;
}
let name = cur_name.as_ref().expect("current header name");
match *name {
header::CONTENT_LENGTH => {
if wrote_len && !is_name_written {
warn!("unexpected content-length found, canceling");
rewind(dst);
return Err(crate::Error::new_user_header());
}
match msg.body {
Some(BodyLength::Known(known_len)) => {
// The Body claims to know a length, and
// the headers are already set. For performance
// reasons, we are just going to trust that
// the values match.
//
// In debug builds, we'll assert they are the
// same to help developers find bugs.
#[cfg(debug_assertions)]
{
if let Some(len) = headers::content_length_parse(&value) {
assert!(
len == known_len,
"payload claims content-length of {}, custom content-length header claims {}",
known_len,
len,
);
}
}
if !is_name_written {
encoder = Encoder::length(known_len);
header_name_writer.write_header_name_with_colon(
dst,
"content-length: ",
header::CONTENT_LENGTH,
);
extend(dst, value.as_bytes());
wrote_len = true;
is_name_written = true;
}
continue 'headers;
}
Some(BodyLength::Unknown) => {
// The Body impl didn't know how long the
// body is, but a length header was included.
// We have to parse the value to return our
// Encoder...
if let Some(len) = headers::content_length_parse(&value) {
if let Some(prev) = prev_con_len {
if prev != len {
warn!(
"multiple Content-Length values found: [{}, {}]",
prev, len
);
rewind(dst);
return Err(crate::Error::new_user_header());
}
debug_assert!(is_name_written);
continue 'headers;
} else {
// we haven't written content-length yet!
encoder = Encoder::length(len);
header_name_writer.write_header_name_with_colon(
dst,
"content-length: ",
header::CONTENT_LENGTH,
);
extend(dst, value.as_bytes());
wrote_len = true;
is_name_written = true;
prev_con_len = Some(len);
continue 'headers;
}
} else {
warn!("illegal Content-Length value: {:?}", value);
rewind(dst);
return Err(crate::Error::new_user_header());
}
}
None => {
// We have no body to actually send,
// but the headers claim a content-length.
// There's only 2 ways this makes sense:
//
// - The header says the length is `0`.
// - This is a response to a `HEAD` request.
if msg.req_method == &Some(Method::HEAD) {
debug_assert_eq!(encoder, Encoder::length(0));
} else {
if value.as_bytes() != b"0" {
warn!(
"content-length value found, but empty body provided: {:?}",
value
);
}
continue 'headers;
}
}
}
wrote_len = true;
}
header::TRANSFER_ENCODING => {
if wrote_len && !is_name_written {
warn!("unexpected transfer-encoding found, canceling");
rewind(dst);
return Err(crate::Error::new_user_header());
}
// check that we actually can send a chunked body...
if msg.head.version == Version::HTTP_10
|| !Server::can_chunked(msg.req_method, msg.head.subject)
{
continue;
}
wrote_len = true;
// Must check each value, because `chunked` needs to be the
// last encoding, or else we add it.
must_write_chunked = !headers::is_chunked_(&value);
if !is_name_written {
encoder = Encoder::chunked();
is_name_written = true;
header_name_writer.write_header_name_with_colon(
dst,
"transfer-encoding: ",
header::TRANSFER_ENCODING,
);
extend(dst, value.as_bytes());
} else {
extend(dst, b", ");
extend(dst, value.as_bytes());
}
continue 'headers;
}
header::CONNECTION => {
if !is_last && headers::connection_close(&value) {
is_last = true;
}
if !is_name_written {
is_name_written = true;
header_name_writer.write_header_name_with_colon(
dst,
"connection: ",
header::CONNECTION,
);
extend(dst, value.as_bytes());
} else {
extend(dst, b", ");
extend(dst, value.as_bytes());
}
continue 'headers;
}
header::DATE => {
wrote_date = true;
}
header::TRAILER => {
// check that we actually can send a chunked body...
if msg.head.version == Version::HTTP_10
|| !Server::can_chunked(msg.req_method, msg.head.subject)
{
continue;
}
if !is_name_written {
is_name_written = true;
header_name_writer.write_header_name_with_colon(
dst,
"trailer: ",
header::TRAILER,
);
extend(dst, value.as_bytes());
} else {
extend(dst, b", ");
extend(dst, value.as_bytes());
}
match allowed_trailer_fields {
Some(ref mut allowed_trailer_fields) => {
allowed_trailer_fields.push(value);
}
None => {
allowed_trailer_fields = Some(vec![value]);
}
}
continue 'headers;
}
_ => (),
}
//TODO: this should perhaps instead combine them into
//single lines, as RFC7230 suggests is preferable.
// non-special write Name and Value
debug_assert!(
!is_name_written,
"{:?} set is_name_written and didn't continue loop",
name,
);
header_name_writer.write_header_name(dst, name);
extend(dst, b": ");
extend(dst, value.as_bytes());
extend(dst, b"\r\n");
}
handle_is_name_written!();
if !wrote_len {
encoder = match msg.body {
Some(BodyLength::Unknown) => {
if msg.head.version == Version::HTTP_10
|| !Server::can_chunked(msg.req_method, msg.head.subject)
{
Encoder::close_delimited()
} else {
header_name_writer.write_full_header_line(
dst,
"transfer-encoding: chunked\r\n",
(header::TRANSFER_ENCODING, ": chunked\r\n"),
);
Encoder::chunked()
}
}
None | Some(BodyLength::Known(0)) => {
if Server::can_have_implicit_zero_content_length(
msg.req_method,
msg.head.subject,
) {
header_name_writer.write_full_header_line(
dst,
"content-length: 0\r\n",
(header::CONTENT_LENGTH, ": 0\r\n"),
)
}
Encoder::length(0)
}
Some(BodyLength::Known(len)) => {
if !Server::can_have_content_length(msg.req_method, msg.head.subject) {
Encoder::length(0)
} else {
header_name_writer.write_header_name_with_colon(
dst,
"content-length: ",
header::CONTENT_LENGTH,
);
extend(dst, ::itoa::Buffer::new().format(len).as_bytes());
extend(dst, b"\r\n");
Encoder::length(len)
}
}
};
}
if !Server::can_have_body(msg.req_method, msg.head.subject) {
trace!(
"server body forced to 0; method={:?}, status={:?}",
msg.req_method,
msg.head.subject
);
encoder = Encoder::length(0);
}
// cached date is much faster than formatting every request
// don't force the write if disabled
if !wrote_date && msg.date_header {
dst.reserve(date::DATE_VALUE_LENGTH + 8);
header_name_writer.write_header_name_with_colon(dst, "date: ", header::DATE);
date::extend(dst);
extend(dst, b"\r\n\r\n");
} else {
extend(dst, b"\r\n");
}
if encoder.is_chunked() {
if let Some(allowed_trailer_fields) = allowed_trailer_fields {
encoder = encoder.into_chunked_with_trailing_fields(allowed_trailer_fields);
}
}
Ok(encoder.set_last(is_last))
}
/// Helper for zero-copy parsing of request path URI.
#[inline]
fn record_path_range(bytes: &[u8], req_path: &str) -> std::ops::Range<usize> {
let bytes_ptr = bytes.as_ptr() as usize;
let start = req_path.as_ptr() as usize - bytes_ptr;
let end = start + req_path.len();
std::ops::Range { start, end }
}
}
#[cfg(feature = "server")]
trait HeaderNameWriter {
fn write_full_header_line(
&mut self,
dst: &mut Vec<u8>,
line: &str,
name_value_pair: (HeaderName, &str),
);
fn write_header_name_with_colon(
&mut self,
dst: &mut Vec<u8>,
name_with_colon: &str,
name: HeaderName,
);
fn write_header_name(&mut self, dst: &mut Vec<u8>, name: &HeaderName);
}
#[cfg(feature = "client")]
impl Http1Transaction for Client {
type Incoming = StatusCode;
type Outgoing = RequestLine;
#[cfg(feature = "tracing")]
const LOG: &'static str = "{role=client}";
fn parse(buf: &mut BytesMut, ctx: ParseContext<'_>) -> ParseResult<StatusCode> {