Skip to content

Commit f287921

Browse files
freeinternet865freeinternet865
andauthored
proxy_server: support chunked request bodies (#21)
Teach the incoming HTTP request parser to handle Transfer-Encoding: chunked instead of only Content-Length-framed bodies. Also reply with 100 Continue when a client sends Expect: 100-continue before waiting for the request body. This keeps request framing correct for POST/PUT-style clients and adds focused tests for chunked decoding and 100-continue handling. Co-authored-by: freeinternet865 <free@internet865.com>
1 parent 1880d26 commit f287921

1 file changed

Lines changed: 219 additions & 12 deletions

File tree

‎src/proxy_server.rs‎

Lines changed: 219 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -950,7 +950,6 @@ where
950950
None => return Ok(false),
951951
};
952952

953-
// Read body if content-length is set.
954953
let body = read_body(stream, &leftover, &headers).await?;
955954

956955
let default_port = if scheme == "https" { 443 } else { 80 };
@@ -1006,36 +1005,178 @@ where
10061005
}
10071006
}
10081007

1008+
fn header_value<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
1009+
headers
1010+
.iter()
1011+
.find(|(k, _)| k.eq_ignore_ascii_case(name))
1012+
.map(|(_, v)| v.as_str())
1013+
}
1014+
1015+
fn expects_100_continue(headers: &[(String, String)]) -> bool {
1016+
header_value(headers, "expect")
1017+
.map(|v| {
1018+
v.split(',')
1019+
.any(|part| part.trim().eq_ignore_ascii_case("100-continue"))
1020+
})
1021+
.unwrap_or(false)
1022+
}
1023+
1024+
fn invalid_body(msg: impl Into<String>) -> std::io::Error {
1025+
std::io::Error::new(std::io::ErrorKind::InvalidData, msg.into())
1026+
}
1027+
10091028
async fn read_body<S>(
10101029
stream: &mut S,
10111030
leftover: &[u8],
10121031
headers: &[(String, String)],
10131032
) -> std::io::Result<Vec<u8>>
10141033
where
1015-
S: tokio::io::AsyncRead + Unpin,
1034+
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
10161035
{
1017-
let cl: Option<usize> = headers
1018-
.iter()
1019-
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
1020-
.and_then(|(_, v)| v.parse().ok());
1036+
let transfer_encoding = header_value(headers, "transfer-encoding");
1037+
let is_chunked = transfer_encoding
1038+
.map(|v| {
1039+
v.split(',')
1040+
.any(|part| part.trim().eq_ignore_ascii_case("chunked"))
1041+
})
1042+
.unwrap_or(false);
1043+
1044+
let content_length = match header_value(headers, "content-length") {
1045+
Some(v) => Some(
1046+
v.parse::<usize>()
1047+
.map_err(|_| invalid_body(format!("invalid Content-Length: {}", v)))?,
1048+
),
1049+
None => None,
1050+
};
1051+
1052+
if transfer_encoding.is_some() && !is_chunked {
1053+
return Err(invalid_body(format!(
1054+
"unsupported Transfer-Encoding: {}",
1055+
transfer_encoding.unwrap_or_default()
1056+
)));
1057+
}
1058+
1059+
if is_chunked && content_length.is_some() {
1060+
return Err(invalid_body(
1061+
"both Transfer-Encoding: chunked and Content-Length are present",
1062+
));
1063+
}
10211064

1022-
let Some(cl) = cl else {
1065+
if expects_100_continue(headers) && (is_chunked || content_length.is_some()) {
1066+
stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n").await?;
1067+
stream.flush().await?;
1068+
}
1069+
1070+
if is_chunked {
1071+
return read_chunked_request_body(stream, leftover.to_vec()).await;
1072+
}
1073+
1074+
let Some(content_length) = content_length else {
10231075
return Ok(Vec::new());
10241076
};
1025-
let mut body = Vec::with_capacity(cl);
1026-
body.extend_from_slice(&leftover[..leftover.len().min(cl)]);
1077+
1078+
let mut body = Vec::with_capacity(content_length);
1079+
body.extend_from_slice(&leftover[..leftover.len().min(content_length)]);
10271080
let mut tmp = [0u8; 8192];
1028-
while body.len() < cl {
1081+
while body.len() < content_length {
10291082
let n = stream.read(&mut tmp).await?;
10301083
if n == 0 {
1031-
break;
1084+
return Err(std::io::Error::new(
1085+
std::io::ErrorKind::UnexpectedEof,
1086+
"EOF mid-body",
1087+
));
10321088
}
1033-
let need = cl - body.len();
1089+
let need = content_length - body.len();
10341090
body.extend_from_slice(&tmp[..n.min(need)]);
10351091
}
10361092
Ok(body)
10371093
}
10381094

1095+
async fn read_chunked_request_body<S>(stream: &mut S, mut buf: Vec<u8>) -> std::io::Result<Vec<u8>>
1096+
where
1097+
S: tokio::io::AsyncRead + Unpin,
1098+
{
1099+
let mut out = Vec::new();
1100+
let mut tmp = [0u8; 8192];
1101+
1102+
loop {
1103+
let line = read_crlf_line(stream, &mut buf, &mut tmp).await?;
1104+
if line.is_empty() {
1105+
continue;
1106+
}
1107+
1108+
let line_str = std::str::from_utf8(&line)
1109+
.map_err(|_| invalid_body("non-utf8 chunk size line"))?
1110+
.trim();
1111+
let size_hex = line_str.split(';').next().unwrap_or("");
1112+
let size = usize::from_str_radix(size_hex, 16)
1113+
.map_err(|_| invalid_body(format!("bad chunk size '{}'", line_str)))?;
1114+
1115+
if size == 0 {
1116+
loop {
1117+
let trailer = read_crlf_line(stream, &mut buf, &mut tmp).await?;
1118+
if trailer.is_empty() {
1119+
return Ok(out);
1120+
}
1121+
}
1122+
}
1123+
1124+
fill_buffer(stream, &mut buf, &mut tmp, size + 2).await?;
1125+
if &buf[size..size + 2] != b"\r\n" {
1126+
return Err(invalid_body("chunk missing trailing CRLF"));
1127+
}
1128+
out.extend_from_slice(&buf[..size]);
1129+
buf.drain(..size + 2);
1130+
}
1131+
}
1132+
1133+
async fn read_crlf_line<S>(
1134+
stream: &mut S,
1135+
buf: &mut Vec<u8>,
1136+
tmp: &mut [u8],
1137+
) -> std::io::Result<Vec<u8>>
1138+
where
1139+
S: tokio::io::AsyncRead + Unpin,
1140+
{
1141+
loop {
1142+
if let Some(idx) = buf.windows(2).position(|w| w == b"\r\n") {
1143+
let line = buf[..idx].to_vec();
1144+
buf.drain(..idx + 2);
1145+
return Ok(line);
1146+
}
1147+
let n = stream.read(tmp).await?;
1148+
if n == 0 {
1149+
return Err(std::io::Error::new(
1150+
std::io::ErrorKind::UnexpectedEof,
1151+
"EOF in chunked body",
1152+
));
1153+
}
1154+
buf.extend_from_slice(&tmp[..n]);
1155+
}
1156+
}
1157+
1158+
async fn fill_buffer<S>(
1159+
stream: &mut S,
1160+
buf: &mut Vec<u8>,
1161+
tmp: &mut [u8],
1162+
want: usize,
1163+
) -> std::io::Result<()>
1164+
where
1165+
S: tokio::io::AsyncRead + Unpin,
1166+
{
1167+
while buf.len() < want {
1168+
let n = stream.read(tmp).await?;
1169+
if n == 0 {
1170+
return Err(std::io::Error::new(
1171+
std::io::ErrorKind::UnexpectedEof,
1172+
"EOF in chunked body",
1173+
));
1174+
}
1175+
buf.extend_from_slice(&tmp[..n]);
1176+
}
1177+
Ok(())
1178+
}
1179+
10391180
// ---------- Plain HTTP proxy ----------
10401181

10411182
async fn do_plain_http(
@@ -1068,3 +1209,69 @@ async fn do_plain_http(
10681209
sock.flush().await?;
10691210
Ok(())
10701211
}
1212+
1213+
#[cfg(test)]
1214+
mod tests {
1215+
use super::*;
1216+
use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt};
1217+
1218+
fn headers(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
1219+
pairs
1220+
.iter()
1221+
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
1222+
.collect()
1223+
}
1224+
1225+
#[tokio::test(flavor = "current_thread")]
1226+
async fn read_body_decodes_chunked_request() {
1227+
let (mut client, mut server) = duplex(1024);
1228+
let writer = tokio::spawn(async move {
1229+
client
1230+
.write_all(b"llo\r\n6\r\n world\r\n0\r\nFoo: bar\r\n\r\n")
1231+
.await
1232+
.unwrap();
1233+
});
1234+
1235+
let body = read_body(
1236+
&mut server,
1237+
b"5\r\nhe",
1238+
&headers(&[("Transfer-Encoding", "chunked")]),
1239+
)
1240+
.await
1241+
.unwrap();
1242+
1243+
writer.await.unwrap();
1244+
assert_eq!(body, b"hello world");
1245+
}
1246+
1247+
#[tokio::test(flavor = "current_thread")]
1248+
async fn read_body_sends_100_continue_before_waiting_for_body() {
1249+
let (mut client, mut server) = duplex(1024);
1250+
let client_task = tokio::spawn(async move {
1251+
let mut got = Vec::new();
1252+
let mut tmp = [0u8; 64];
1253+
loop {
1254+
let n = client.read(&mut tmp).await.unwrap();
1255+
assert!(n > 0, "proxy closed before sending 100 Continue");
1256+
got.extend_from_slice(&tmp[..n]);
1257+
if got.windows(4).any(|w| w == b"\r\n\r\n") {
1258+
break;
1259+
}
1260+
}
1261+
assert_eq!(got, b"HTTP/1.1 100 Continue\r\n\r\n");
1262+
client.write_all(b"hello").await.unwrap();
1263+
});
1264+
1265+
let body = read_body(
1266+
&mut server,
1267+
&[],
1268+
&headers(&[("Content-Length", "5"), ("Expect", "100-continue")]),
1269+
)
1270+
.await
1271+
.unwrap();
1272+
1273+
client_task.await.unwrap();
1274+
assert_eq!(body, b"hello");
1275+
}
1276+
1277+
}

0 commit comments

Comments
 (0)