| 1 |
#![deny(warnings, clippy::pedantic)] |
| 2 |
#![allow(clippy::missing_errors_doc)] // Too lazy to document these. |
| 3 |
|
| 4 |
#[cfg(feature = "read-bhttp")] |
| 5 |
use std::convert::TryFrom; |
| 6 |
#[cfg(any( |
| 7 |
feature = "read-http", |
| 8 |
feature = "write-http", |
| 9 |
feature = "read-bhttp", |
| 10 |
feature = "write-bhttp" |
| 11 |
))] |
| 12 |
use std::io; |
| 13 |
#[cfg(feature = "read-http")] |
| 14 |
use url::Url; |
| 15 |
|
| 16 |
mod err; |
| 17 |
mod parse; |
| 18 |
#[cfg(any(feature = "read-bhttp", feature = "write-bhttp"))] |
| 19 |
mod rw; |
| 20 |
|
| 21 |
pub use err::Error; |
| 22 |
#[cfg(any( |
| 23 |
feature = "read-http", |
| 24 |
feature = "write-http", |
| 25 |
feature = "read-bhttp", |
| 26 |
feature = "write-bhttp" |
| 27 |
))] |
| 28 |
use err::Res; |
| 29 |
#[cfg(feature = "read-http")] |
| 30 |
use parse::{downcase, is_ows, read_line, split_at, COLON, SEMICOLON, SLASH, SP}; |
| 31 |
use parse::{index_of, trim_ows, COMMA}; |
| 32 |
#[cfg(feature = "read-bhttp")] |
| 33 |
use rw::{read_varint, read_vec}; |
| 34 |
#[cfg(feature = "write-bhttp")] |
| 35 |
use rw::{write_len, write_varint, write_vec}; |
| 36 |
#[cfg(any(feature = "read-http", feature = "read-bhttp",))] |
| 37 |
use std::borrow::BorrowMut; |
| 38 |
|
| 39 |
#[cfg(feature = "read-http")] |
| 40 |
const CONTENT_LENGTH: &[u8] = b"content-length"; |
| 41 |
#[cfg(feature = "read-bhttp")] |
| 42 |
const COOKIE: &[u8] = b"cookie"; |
| 43 |
const TRANSFER_ENCODING: &[u8] = b"transfer-encoding"; |
| 44 |
const CHUNKED: &[u8] = b"chunked"; |
| 45 |
|
| 46 |
pub type StatusCode = u16; |
| 47 |
|
| 48 |
pub trait ReadSeek: io::BufRead + io::Seek {} |
| 49 |
impl<T> ReadSeek for io::Cursor<T> where T: AsRef<[u8]> {} |
| 50 |
impl<T> ReadSeek for io::BufReader<T> where T: io::Read + io::Seek {} |
| 51 |
|
| 52 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 53 |
#[cfg(any(feature = "read-bhttp", feature = "write-bhttp"))] |
| 54 |
pub enum Mode { |
| 55 |
KnownLength, |
| 56 |
IndefiniteLength, |
| 57 |
} |
| 58 |
|
| 59 |
pub struct Field { |
| 60 |
name: Vec<u8>, |
| 61 |
value: Vec<u8>, |
| 62 |
} |
| 63 |
|
| 64 |
impl Field { |
| 65 |
#[must_use] |
| 66 |
pub fn new(name: Vec<u8>, value: Vec<u8>) -> Self { |
| 67 |
Self { name, value } |
| 68 |
} |
| 69 |
|
| 70 |
#[must_use] |
| 71 |
pub fn name(&self) -> &[u8] { |
| 72 |
&self.name |
| 73 |
} |
| 74 |
|
| 75 |
#[must_use] |
| 76 |
pub fn value(&self) -> &[u8] { |
| 77 |
&self.value |
| 78 |
} |
| 79 |
|
| 80 |
#[cfg(feature = "write-http")] |
| 81 |
pub fn write_http(&self, w: &mut impl io::Write) -> Res<()> { |
| 82 |
w.write_all(&self.name)?; |
| 83 |
w.write_all(b": ")?; |
| 84 |
w.write_all(&self.value)?; |
| 85 |
w.write_all(b"\r\n")?; |
| 86 |
Ok(()) |
| 87 |
} |
| 88 |
|
| 89 |
#[cfg(feature = "write-bhttp")] |
| 90 |
pub fn write_bhttp(&self, w: &mut impl io::Write) -> Res<()> { |
| 91 |
write_vec(&self.name, w)?; |
| 92 |
write_vec(&self.value, w)?; |
| 93 |
Ok(()) |
| 94 |
} |
| 95 |
|
| 96 |
#[cfg(feature = "read-http")] |
| 97 |
pub fn obs_fold(&mut self, extra: &[u8]) { |
| 98 |
self.value.push(SP); |
| 99 |
self.value.extend(trim_ows(extra)); |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
#[derive(Default)] |
| 104 |
pub struct FieldSection(Vec<Field>); |
| 105 |
impl FieldSection { |
| 106 |
#[must_use] |
| 107 |
pub fn is_empty(&self) -> bool { |
| 108 |
self.0.is_empty() |
| 109 |
} |
| 110 |
|
| 111 |
/// Gets the value from the first instance of the field. |
| 112 |
#[must_use] |
| 113 |
pub fn get(&self, n: &[u8]) -> Option<&[u8]> { |
| 114 |
for f in &self.0 { |
| 115 |
if &f.name[..] == n { |
| 116 |
return Some(&f.value); |
| 117 |
} |
| 118 |
} |
| 119 |
None |
| 120 |
} |
| 121 |
|
| 122 |
pub fn put(&mut self, name: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) { |
| 123 |
self.0.push(Field::new(name.into(), value.into())); |
| 124 |
} |
| 125 |
|
| 126 |
pub fn iter(&self) -> impl Iterator<Item = &Field> { |
| 127 |
self.0.iter() |
| 128 |
} |
| 129 |
|
| 130 |
#[must_use] |
| 131 |
pub fn fields(&self) -> &[Field] { |
| 132 |
&self.0 |
| 133 |
} |
| 134 |
|
| 135 |
#[must_use] |
| 136 |
pub fn is_chunked(&self) -> bool { |
| 137 |
// Look at the last symbol in Transfer-Encoding. |
| 138 |
// This is very primitive decoding; structured field this is not. |
| 139 |
if let Some(te) = self.get(TRANSFER_ENCODING) { |
| 140 |
let mut slc = te; |
| 141 |
while let Some(i) = index_of(COMMA, slc) { |
| 142 |
slc = trim_ows(&slc[i + 1..]); |
| 143 |
} |
| 144 |
slc == CHUNKED |
| 145 |
} else { |
| 146 |
false |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
/// As required by the HTTP specification, remove the Connection header |
| 151 |
/// field, everything it refers to, and a few extra fields. |
| 152 |
#[cfg(feature = "read-http")] |
| 153 |
fn strip_connection_headers(&mut self) { |
| 154 |
const CONNECTION: &[u8] = b"connection"; |
| 155 |
const PROXY_CONNECTION: &[u8] = b"proxy-connection"; |
| 156 |
const SHOULD_REMOVE: &[&[u8]] = &[ |
| 157 |
CONNECTION, |
| 158 |
PROXY_CONNECTION, |
| 159 |
b"keep-alive", |
| 160 |
b"te", |
| 161 |
b"trailer", |
| 162 |
b"transfer-encoding", |
| 163 |
b"upgrade", |
| 164 |
]; |
| 165 |
let mut listed = Vec::new(); |
| 166 |
let mut track = |n| { |
| 167 |
let mut name = Vec::from(trim_ows(n)); |
| 168 |
downcase(&mut name); |
| 169 |
if !listed.contains(&name) { |
| 170 |
listed.push(name); |
| 171 |
} |
| 172 |
}; |
| 173 |
|
| 174 |
for f in self |
| 175 |
.0 |
| 176 |
.iter() |
| 177 |
.filter(|f| f.name() == CONNECTION || f.name == PROXY_CONNECTION) |
| 178 |
{ |
| 179 |
let mut v = f.value(); |
| 180 |
while let Some(i) = index_of(COMMA, v) { |
| 181 |
track(&v[..i]); |
| 182 |
v = &v[i + 1..]; |
| 183 |
} |
| 184 |
track(v); |
| 185 |
} |
| 186 |
|
| 187 |
self.0.retain(|f| { |
| 188 |
!SHOULD_REMOVE.contains(&f.name()) && listed.iter().all(|x| &x[..] != f.name()) |
| 189 |
}); |
| 190 |
} |
| 191 |
|
| 192 |
#[cfg(feature = "read-http")] |
| 193 |
fn parse_line(fields: &mut Vec<Field>, line: Vec<u8>) -> Res<()> { |
| 194 |
// obs-fold is helpful in specs, so support it here too |
| 195 |
let f = if is_ows(line[0]) { |
| 196 |
let mut e = fields.pop().ok_or(Error::ObsFold)?; |
| 197 |
e.obs_fold(&line); |
| 198 |
e |
| 199 |
} else if let Some((n, v)) = split_at(COLON, line) { |
| 200 |
let mut name = Vec::from(trim_ows(&n)); |
| 201 |
downcase(&mut name); |
| 202 |
let value = Vec::from(trim_ows(&v)); |
| 203 |
Field::new(name, value) |
| 204 |
} else { |
| 205 |
return Err(Error::Missing(COLON)); |
| 206 |
}; |
| 207 |
fields.push(f); |
| 208 |
Ok(()) |
| 209 |
} |
| 210 |
|
| 211 |
#[cfg(feature = "read-http")] |
| 212 |
pub fn read_http<T, R>(r: &mut T) -> Res<Self> |
| 213 |
where |
| 214 |
T: BorrowMut<R> + ?Sized, |
| 215 |
R: ReadSeek + ?Sized, |
| 216 |
{ |
| 217 |
let mut fields = Vec::new(); |
| 218 |
loop { |
| 219 |
let line = read_line(r)?; |
| 220 |
if trim_ows(&line).is_empty() { |
| 221 |
return Ok(Self(fields)); |
| 222 |
} |
| 223 |
Self::parse_line(&mut fields, line)?; |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
#[cfg(feature = "read-bhttp")] |
| 228 |
fn read_bhttp_fields<T, R>(terminator: bool, r: &mut T) -> Res<Vec<Field>> |
| 229 |
where |
| 230 |
T: BorrowMut<R> + ?Sized, |
| 231 |
R: ReadSeek + ?Sized, |
| 232 |
{ |
| 233 |
let r = r.borrow_mut(); |
| 234 |
let mut fields = Vec::new(); |
| 235 |
let mut cookie_index: Option<usize> = None; |
| 236 |
loop { |
| 237 |
if let Some(n) = read_vec(r)? { |
| 238 |
if n.is_empty() { |
| 239 |
if terminator { |
| 240 |
return Ok(fields); |
| 241 |
} |
| 242 |
return Err(Error::Truncated); |
| 243 |
} |
| 244 |
let mut v = read_vec(r)?.ok_or(Error::Truncated)?; |
| 245 |
if n == COOKIE { |
| 246 |
if let Some(i) = &cookie_index { |
| 247 |
fields[*i].value.extend_from_slice(b"; "); |
| 248 |
fields[*i].value.append(&mut v); |
| 249 |
continue; |
| 250 |
} |
| 251 |
cookie_index = Some(fields.len()); |
| 252 |
} |
| 253 |
fields.push(Field::new(n, v)); |
| 254 |
} else if terminator { |
| 255 |
return Err(Error::Truncated); |
| 256 |
} else { |
| 257 |
return Ok(fields); |
| 258 |
} |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
#[cfg(feature = "read-bhttp")] |
| 263 |
pub fn read_bhttp<T, R>(mode: Mode, r: &mut T) -> Res<Self> |
| 264 |
where |
| 265 |
T: BorrowMut<R> + ?Sized, |
| 266 |
R: ReadSeek + ?Sized, |
| 267 |
{ |
| 268 |
let fields = if mode == Mode::KnownLength { |
| 269 |
if let Some(buf) = read_vec(r)? { |
| 270 |
Self::read_bhttp_fields(false, &mut io::Cursor::new(&buf[..]))? |
| 271 |
} else { |
| 272 |
Vec::new() |
| 273 |
} |
| 274 |
} else { |
| 275 |
Self::read_bhttp_fields(true, r)? |
| 276 |
}; |
| 277 |
Ok(Self(fields)) |
| 278 |
} |
| 279 |
|
| 280 |
#[cfg(feature = "write-bhttp")] |
| 281 |
fn write_bhttp_headers(&self, w: &mut impl io::Write) -> Res<()> { |
| 282 |
for f in &self.0 { |
| 283 |
f.write_bhttp(w)?; |
| 284 |
} |
| 285 |
Ok(()) |
| 286 |
} |
| 287 |
|
| 288 |
#[cfg(feature = "write-bhttp")] |
| 289 |
pub fn write_bhttp(&self, mode: Mode, w: &mut impl io::Write) -> Res<()> { |
| 290 |
if mode == Mode::KnownLength { |
| 291 |
let mut buf = Vec::new(); |
| 292 |
self.write_bhttp_headers(&mut buf)?; |
| 293 |
write_vec(&buf, w)?; |
| 294 |
} else { |
| 295 |
self.write_bhttp_headers(w)?; |
| 296 |
write_len(0, w)?; |
| 297 |
} |
| 298 |
Ok(()) |
| 299 |
} |
| 300 |
|
| 301 |
#[cfg(feature = "write-http")] |
| 302 |
pub fn write_http(&self, w: &mut impl io::Write) -> Res<()> { |
| 303 |
for f in &self.0 { |
| 304 |
f.write_http(w)?; |
| 305 |
} |
| 306 |
w.write_all(b"\r\n")?; |
| 307 |
Ok(()) |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
pub enum ControlData { |
| 312 |
Request { |
| 313 |
method: Vec<u8>, |
| 314 |
scheme: Vec<u8>, |
| 315 |
authority: Vec<u8>, |
| 316 |
path: Vec<u8>, |
| 317 |
}, |
| 318 |
Response(StatusCode), |
| 319 |
} |
| 320 |
|
| 321 |
impl ControlData { |
| 322 |
#[must_use] |
| 323 |
pub fn is_request(&self) -> bool { |
| 324 |
matches!(self, Self::Request { .. }) |
| 325 |
} |
| 326 |
|
| 327 |
#[must_use] |
| 328 |
pub fn method(&self) -> Option<&[u8]> { |
| 329 |
if let Self::Request { method, .. } = self { |
| 330 |
Some(method) |
| 331 |
} else { |
| 332 |
None |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
#[must_use] |
| 337 |
pub fn scheme(&self) -> Option<&[u8]> { |
| 338 |
if let Self::Request { scheme, .. } = self { |
| 339 |
Some(scheme) |
| 340 |
} else { |
| 341 |
None |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
#[must_use] |
| 346 |
pub fn authority(&self) -> Option<&[u8]> { |
| 347 |
if let Self::Request { authority, .. } = self { |
| 348 |
if authority.is_empty() { |
| 349 |
None |
| 350 |
} else { |
| 351 |
Some(authority) |
| 352 |
} |
| 353 |
} else { |
| 354 |
None |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
#[must_use] |
| 359 |
pub fn path(&self) -> Option<&[u8]> { |
| 360 |
if let Self::Request { path, .. } = self { |
| 361 |
if path.is_empty() { |
| 362 |
None |
| 363 |
} else { |
| 364 |
Some(path) |
| 365 |
} |
| 366 |
} else { |
| 367 |
None |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
#[must_use] |
| 372 |
pub fn status(&self) -> Option<StatusCode> { |
| 373 |
if let Self::Response(code) = self { |
| 374 |
Some(*code) |
| 375 |
} else { |
| 376 |
None |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
#[cfg(feature = "read-http")] |
| 381 |
pub fn read_http(line: Vec<u8>) -> Res<Self> { |
| 382 |
// request-line = method SP request-target SP HTTP-version |
| 383 |
// status-line = HTTP-version SP status-code SP [reason-phrase] |
| 384 |
let (a, r) = split_at(SP, line).ok_or(Error::Missing(SP))?; |
| 385 |
let (b, _) = split_at(SP, r).ok_or(Error::Missing(SP))?; |
| 386 |
if index_of(SLASH, &a).is_some() { |
| 387 |
// Probably a response, so treat it as such. |
| 388 |
let status_str = String::from_utf8(b)?; |
| 389 |
let code = status_str.parse::<u16>()?; |
| 390 |
Ok(Self::Response(code)) |
| 391 |
} else if index_of(COLON, &b).is_some() { |
| 392 |
// Now try to parse the URL. |
| 393 |
let url_str = String::from_utf8(b)?; |
| 394 |
let parsed = Url::parse(&url_str)?; |
| 395 |
let authority = parsed.host_str().map_or_else(String::new, |host| { |
| 396 |
let mut authority = String::from(host); |
| 397 |
if let Some(port) = parsed.port() { |
| 398 |
authority.push(':'); |
| 399 |
authority.push_str(&port.to_string()); |
| 400 |
} |
| 401 |
authority |
| 402 |
}); |
| 403 |
let mut path = String::from(parsed.path()); |
| 404 |
if let Some(q) = parsed.query() { |
| 405 |
path.push('?'); |
| 406 |
path.push_str(q); |
| 407 |
} |
| 408 |
Ok(Self::Request { |
| 409 |
method: a, |
| 410 |
scheme: Vec::from(parsed.scheme().as_bytes()), |
| 411 |
authority: Vec::from(authority.as_bytes()), |
| 412 |
path: Vec::from(path.as_bytes()), |
| 413 |
}) |
| 414 |
} else { |
| 415 |
if a == b"CONNECT" { |
| 416 |
return Err(Error::ConnectUnsupported); |
| 417 |
} |
| 418 |
Ok(Self::Request { |
| 419 |
method: a, |
| 420 |
scheme: Vec::from(&b"https"[..]), |
| 421 |
authority: Vec::new(), |
| 422 |
path: b, |
| 423 |
}) |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
#[cfg(feature = "read-bhttp")] |
| 428 |
pub fn read_bhttp<T, R>(request: bool, r: &mut T) -> Res<Self> |
| 429 |
where |
| 430 |
T: BorrowMut<R> + ?Sized, |
| 431 |
R: ReadSeek + ?Sized, |
| 432 |
{ |
| 433 |
let v = if request { |
| 434 |
let method = read_vec(r)?.ok_or(Error::Truncated)?; |
| 435 |
let scheme = read_vec(r)?.ok_or(Error::Truncated)?; |
| 436 |
let authority = read_vec(r)?.ok_or(Error::Truncated)?; |
| 437 |
let path = read_vec(r)?.ok_or(Error::Truncated)?; |
| 438 |
Self::Request { |
| 439 |
method, |
| 440 |
scheme, |
| 441 |
authority, |
| 442 |
path, |
| 443 |
} |
| 444 |
} else { |
| 445 |
Self::Response(u16::try_from(read_varint(r)?.ok_or(Error::Truncated)?)?) |
| 446 |
}; |
| 447 |
Ok(v) |
| 448 |
} |
| 449 |
|
| 450 |
/// If this is an informational response. |
| 451 |
#[cfg(any(feature = "read-bhttp", feature = "read-http"))] |
| 452 |
#[must_use] |
| 453 |
fn informational(&self) -> Option<StatusCode> { |
| 454 |
match self { |
| 455 |
Self::Response(v) if *v >= 100 && *v < 200 => Some(*v), |
| 456 |
_ => None, |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
#[cfg(feature = "write-bhttp")] |
| 461 |
#[must_use] |
| 462 |
fn code(&self, mode: Mode) -> u64 { |
| 463 |
match (self, mode) { |
| 464 |
(Self::Request { .. }, Mode::KnownLength) => 0, |
| 465 |
(Self::Response(_), Mode::KnownLength) => 1, |
| 466 |
(Self::Request { .. }, Mode::IndefiniteLength) => 2, |
| 467 |
(Self::Response(_), Mode::IndefiniteLength) => 3, |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
#[cfg(feature = "write-bhttp")] |
| 472 |
pub fn write_bhttp(&self, w: &mut impl io::Write) -> Res<()> { |
| 473 |
match self { |
| 474 |
Self::Request { |
| 475 |
method, |
| 476 |
scheme, |
| 477 |
authority, |
| 478 |
path, |
| 479 |
} => { |
| 480 |
write_vec(method, w)?; |
| 481 |
write_vec(scheme, w)?; |
| 482 |
write_vec(authority, w)?; |
| 483 |
write_vec(path, w)?; |
| 484 |
} |
| 485 |
Self::Response(status) => write_varint(*status, w)?, |
| 486 |
} |
| 487 |
Ok(()) |
| 488 |
} |
| 489 |
|
| 490 |
#[cfg(feature = "write-http")] |
| 491 |
pub fn write_http(&self, w: &mut impl io::Write) -> Res<()> { |
| 492 |
match self { |
| 493 |
Self::Request { |
| 494 |
method, |
| 495 |
scheme, |
| 496 |
authority, |
| 497 |
path, |
| 498 |
} => { |
| 499 |
w.write_all(method)?; |
| 500 |
w.write_all(b" ")?; |
| 501 |
if !authority.is_empty() { |
| 502 |
w.write_all(scheme)?; |
| 503 |
w.write_all(b"://")?; |
| 504 |
w.write_all(authority)?; |
| 505 |
} |
| 506 |
w.write_all(path)?; |
| 507 |
w.write_all(b" HTTP/1.1\r\n")?; |
| 508 |
} |
| 509 |
Self::Response(status) => { |
| 510 |
let buf = format!("HTTP/1.1 {} Reason\r\n", *status); |
| 511 |
w.write_all(buf.as_bytes())?; |
| 512 |
} |
| 513 |
} |
| 514 |
Ok(()) |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
pub struct InformationalResponse { |
| 519 |
status: StatusCode, |
| 520 |
fields: FieldSection, |
| 521 |
} |
| 522 |
|
| 523 |
impl InformationalResponse { |
| 524 |
#[must_use] |
| 525 |
pub fn new(status: StatusCode, fields: FieldSection) -> Self { |
| 526 |
Self { status, fields } |
| 527 |
} |
| 528 |
|
| 529 |
#[must_use] |
| 530 |
pub fn status(&self) -> StatusCode { |
| 531 |
self.status |
| 532 |
} |
| 533 |
|
| 534 |
#[must_use] |
| 535 |
pub fn fields(&self) -> &FieldSection { |
| 536 |
&self.fields |
| 537 |
} |
| 538 |
|
| 539 |
#[cfg(feature = "write-bhttp")] |
| 540 |
fn write_bhttp(&self, mode: Mode, w: &mut impl io::Write) -> Res<()> { |
| 541 |
write_varint(self.status, w)?; |
| 542 |
self.fields.write_bhttp(mode, w)?; |
| 543 |
Ok(()) |
| 544 |
} |
| 545 |
} |
| 546 |
|
| 547 |
pub struct Message { |
| 548 |
informational: Vec<InformationalResponse>, |
| 549 |
control: ControlData, |
| 550 |
header: FieldSection, |
| 551 |
content: Vec<u8>, |
| 552 |
trailer: FieldSection, |
| 553 |
} |
| 554 |
|
| 555 |
impl Message { |
| 556 |
#[must_use] |
| 557 |
pub fn request(method: Vec<u8>, scheme: Vec<u8>, authority: Vec<u8>, path: Vec<u8>) -> Self { |
| 558 |
Self { |
| 559 |
informational: Vec::new(), |
| 560 |
control: ControlData::Request { |
| 561 |
method, |
| 562 |
scheme, |
| 563 |
authority, |
| 564 |
path, |
| 565 |
}, |
| 566 |
header: FieldSection::default(), |
| 567 |
content: Vec::new(), |
| 568 |
trailer: FieldSection::default(), |
| 569 |
} |
| 570 |
} |
| 571 |
|
| 572 |
#[must_use] |
| 573 |
pub fn response(status: StatusCode) -> Self { |
| 574 |
Self { |
| 575 |
informational: Vec::new(), |
| 576 |
control: ControlData::Response(status), |
| 577 |
header: FieldSection::default(), |
| 578 |
content: Vec::new(), |
| 579 |
trailer: FieldSection::default(), |
| 580 |
} |
| 581 |
} |
| 582 |
|
| 583 |
pub fn put_header(&mut self, name: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) { |
| 584 |
self.header.put(name, value); |
| 585 |
} |
| 586 |
|
| 587 |
pub fn put_trailer(&mut self, name: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) { |
| 588 |
self.trailer.put(name, value); |
| 589 |
} |
| 590 |
|
| 591 |
pub fn write_content(&mut self, d: impl AsRef<[u8]>) { |
| 592 |
self.content.extend_from_slice(d.as_ref()); |
| 593 |
} |
| 594 |
|
| 595 |
#[must_use] |
| 596 |
pub fn informational(&self) -> &[InformationalResponse] { |
| 597 |
&self.informational |
| 598 |
} |
| 599 |
|
| 600 |
#[must_use] |
| 601 |
pub fn control(&self) -> &ControlData { |
| 602 |
&self.control |
| 603 |
} |
| 604 |
|
| 605 |
#[must_use] |
| 606 |
pub fn header(&self) -> &FieldSection { |
| 607 |
&self.header |
| 608 |
} |
| 609 |
|
| 610 |
#[must_use] |
| 611 |
pub fn content(&self) -> &[u8] { |
| 612 |
&self.content |
| 613 |
} |
| 614 |
|
| 615 |
#[must_use] |
| 616 |
pub fn trailer(&self) -> &FieldSection { |
| 617 |
&self.trailer |
| 618 |
} |
| 619 |
|
| 620 |
#[cfg(feature = "read-http")] |
| 621 |
fn read_chunked<T, R>(r: &mut T) -> Res<Vec<u8>> |
| 622 |
where |
| 623 |
T: BorrowMut<R> + ?Sized, |
| 624 |
R: ReadSeek + ?Sized, |
| 625 |
{ |
| 626 |
let mut content = Vec::new(); |
| 627 |
loop { |
| 628 |
let mut line = read_line(r)?; |
| 629 |
if let Some(i) = index_of(SEMICOLON, &line) { |
| 630 |
std::mem::drop(line.split_off(i)); |
| 631 |
} |
| 632 |
let count_str = String::from_utf8(line)?; |
| 633 |
let count = usize::from_str_radix(&count_str, 16)?; |
| 634 |
if count == 0 { |
| 635 |
return Ok(content); |
| 636 |
} |
| 637 |
let mut buf = vec![0; count]; |
| 638 |
r.borrow_mut().read_exact(&mut buf)?; |
| 639 |
assert!(read_line(r)?.is_empty()); |
| 640 |
content.append(&mut buf); |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
#[cfg(feature = "read-http")] |
| 645 |
#[allow(clippy::read_zero_byte_vec)] // https://github.com/rust-lang/rust-clippy/issues/9274 |
| 646 |
pub fn read_http<T, R>(r: &mut T) -> Res<Self> |
| 647 |
where |
| 648 |
T: BorrowMut<R> + ?Sized, |
| 649 |
R: ReadSeek + ?Sized, |
| 650 |
{ |
| 651 |
let line = read_line(r)?; |
| 652 |
let mut control = ControlData::read_http(line)?; |
| 653 |
let mut informational = Vec::new(); |
| 654 |
while let Some(status) = control.informational() { |
| 655 |
let fields = FieldSection::read_http(r)?; |
| 656 |
informational.push(InformationalResponse::new(status, fields)); |
| 657 |
let line = read_line(r)?; |
| 658 |
control = ControlData::read_http(line)?; |
| 659 |
} |
| 660 |
|
| 661 |
let mut header = FieldSection::read_http(r)?; |
| 662 |
|
| 663 |
let (content, trailer) = if matches!(control.status(), Some(204) | Some(304)) { |
| 664 |
// 204 and 304 have no body, no matter what Content-Length says. |
| 665 |
// Unfortunately, we can't do the same for responses to HEAD. |
| 666 |
(Vec::new(), FieldSection::default()) |
| 667 |
} else if header.is_chunked() { |
| 668 |
let content = Self::read_chunked(r)?; |
| 669 |
let trailer = FieldSection::read_http(r)?; |
| 670 |
(content, trailer) |
| 671 |
} else { |
| 672 |
let mut content = Vec::new(); |
| 673 |
if let Some(cl) = header.get(CONTENT_LENGTH) { |
| 674 |
let cl_str = String::from_utf8(Vec::from(cl))?; |
| 675 |
let cl_int = cl_str.parse::<usize>()?; |
| 676 |
if cl_int > 0 { |
| 677 |
content.resize(cl_int, 0); |
| 678 |
r.borrow_mut().read_exact(&mut content)?; |
| 679 |
} |
| 680 |
} else { |
| 681 |
// Note that for a request, the spec states that the content is |
| 682 |
// empty, but this just reads all input like for a response. |
| 683 |
r.borrow_mut().read_to_end(&mut content)?; |
| 684 |
} |
| 685 |
(content, FieldSection::default()) |
| 686 |
}; |
| 687 |
|
| 688 |
header.strip_connection_headers(); |
| 689 |
Ok(Self { |
| 690 |
informational, |
| 691 |
control, |
| 692 |
header, |
| 693 |
content, |
| 694 |
trailer, |
| 695 |
}) |
| 696 |
} |
| 697 |
|
| 698 |
#[cfg(feature = "write-http")] |
| 699 |
pub fn write_http(&self, w: &mut impl io::Write) -> Res<()> { |
| 700 |
for info in &self.informational { |
| 701 |
ControlData::Response(info.status()).write_http(w)?; |
| 702 |
info.fields().write_http(w)?; |
| 703 |
} |
| 704 |
self.control.write_http(w)?; |
| 705 |
if !self.content.is_empty() { |
| 706 |
if self.trailer.is_empty() { |
| 707 |
write!(w, "Content-Length: {}\r\n", self.content.len())?; |
| 708 |
} else { |
| 709 |
w.write_all(b"Transfer-Encoding: chunked\r\n")?; |
| 710 |
} |
| 711 |
} |
| 712 |
self.header.write_http(w)?; |
| 713 |
|
| 714 |
if self.header.is_chunked() { |
| 715 |
write!(w, "{:x}\r\n", self.content.len())?; |
| 716 |
w.write_all(&self.content)?; |
| 717 |
w.write_all(b"\r\n0\r\n")?; |
| 718 |
self.trailer.write_http(w)?; |
| 719 |
} else { |
| 720 |
w.write_all(&self.content)?; |
| 721 |
} |
| 722 |
|
| 723 |
Ok(()) |
| 724 |
} |
| 725 |
|
| 726 |
/// Read a BHTTP message. |
| 727 |
#[cfg(feature = "read-bhttp")] |
| 728 |
pub fn read_bhttp<T, R>(r: &mut T) -> Res<Self> |
| 729 |
where |
| 730 |
T: BorrowMut<R> + ?Sized, |
| 731 |
R: ReadSeek + ?Sized, |
| 732 |
{ |
| 733 |
let t = read_varint(r)?.ok_or(Error::Truncated)?; |
| 734 |
let request = t == 0 || t == 2; |
| 735 |
let mode = match t { |
| 736 |
0 | 1 => Mode::KnownLength, |
| 737 |
2 | 3 => Mode::IndefiniteLength, |
| 738 |
_ => return Err(Error::InvalidMode), |
| 739 |
}; |
| 740 |
|
| 741 |
let mut control = ControlData::read_bhttp(request, r)?; |
| 742 |
let mut informational = Vec::new(); |
| 743 |
while let Some(status) = control.informational() { |
| 744 |
let fields = FieldSection::read_bhttp(mode, r)?; |
| 745 |
informational.push(InformationalResponse::new(status, fields)); |
| 746 |
control = ControlData::read_bhttp(request, r)?; |
| 747 |
} |
| 748 |
let header = FieldSection::read_bhttp(mode, r)?; |
| 749 |
|
| 750 |
let mut content = read_vec(r)?.unwrap_or_default(); |
| 751 |
if mode == Mode::IndefiniteLength && !content.is_empty() { |
| 752 |
loop { |
| 753 |
let mut extra = read_vec(r)?.unwrap_or_default(); |
| 754 |
if extra.is_empty() { |
| 755 |
break; |
| 756 |
} |
| 757 |
content.append(&mut extra); |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
let trailer = FieldSection::read_bhttp(mode, r)?; |
| 762 |
|
| 763 |
Ok(Self { |
| 764 |
informational, |
| 765 |
control, |
| 766 |
header, |
| 767 |
content, |
| 768 |
trailer, |
| 769 |
}) |
| 770 |
} |
| 771 |
|
| 772 |
#[cfg(feature = "write-bhttp")] |
| 773 |
pub fn write_bhttp(&self, mode: Mode, w: &mut impl io::Write) -> Res<()> { |
| 774 |
write_varint(self.control.code(mode), w)?; |
| 775 |
for info in &self.informational { |
| 776 |
info.write_bhttp(mode, w)?; |
| 777 |
} |
| 778 |
self.control.write_bhttp(w)?; |
| 779 |
self.header.write_bhttp(mode, w)?; |
| 780 |
|
| 781 |
write_vec(&self.content, w)?; |
| 782 |
if mode == Mode::IndefiniteLength && !self.content.is_empty() { |
| 783 |
write_len(0, w)?; |
| 784 |
} |
| 785 |
self.trailer.write_bhttp(mode, w)?; |
| 786 |
Ok(()) |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
#[cfg(feature = "write-http")] |
| 791 |
impl std::fmt::Debug for Message { |
| 792 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { |
| 793 |
let mut buf = Vec::new(); |
| 794 |
self.write_http(&mut buf).map_err(|_| std::fmt::Error)?; |
| 795 |
write!(f, "{:?}", String::from_utf8_lossy(&buf)) |
| 796 |
} |
| 797 |
} |