1 // Copyright (c) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 //! HTTP [`Content`] implementation. 15 //! 16 //! # Introduction 17 //! 18 //! HTTP messages often transfer a complete or partial representation as the 19 //! message content: a stream of octets sent after the header section, as 20 //! delineated by the message framing. 21 //! 22 //! This abstract definition of content reflects the data after it has been 23 //! extracted from the message framing. For example, an `HTTP/1.1` message body 24 //! might consist of a stream of data encoded with the chunked transfer coding — 25 //! a sequence of data chunks, one zero-length chunk, and a trailer section — 26 //! whereas the content of that same message includes only the data stream after 27 //! the transfer coding has been decoded; it does not include the chunk lengths, 28 //! chunked framing syntax, nor the trailer fields. 29 //! 30 //! [`Content`]: https://httpwg.org/specs/rfc9110.html#content 31 //! 32 //! # Various Body Types 33 //! 34 //! This module provides following body types: 35 //! 36 //! - [`EmptyBody`]: `EmptyBody` represents an empty body. 37 //! - [`TextBody`]: `TextBody` represents a plain-text body. 38 //! 39 //! [`EmptyBody`]: EmptyBody 40 //! [`TextBody`]: TextBody 41 42 // TODO: Support `Trailers`. 43 44 mod chunk; 45 mod empty; 46 mod mime; 47 mod text; 48 49 pub use chunk::{Chunk, ChunkBody, ChunkBodyDecoder, ChunkExt, ChunkState, Chunks}; 50 pub use empty::EmptyBody; 51 pub use mime::{ 52 MimeMulti, MimeMultiBuilder, MimeMultiDecoder, MimeMultiEncoder, MimePart, MimePartBuilder, 53 MimePartEncoder, MimeType, MultiPart, Part, TokenStatus, XPart, 54 }; 55 pub use text::{Text, TextBody, TextBodyDecoder}; 56 57 /// Synchronous `Body` trait definition. 58 pub mod sync_impl { 59 use std::error::Error; 60 use std::io::Read; 61 62 use crate::headers::Headers; 63 64 /// The `sync_impl::Body` trait allows for reading body data synchronously. 65 /// 66 /// # Examples 67 /// 68 /// [`TextBody`] implements `sync_impl::Body`: 69 /// 70 /// ``` 71 /// use ylong_http::body::sync_impl::Body; 72 /// use ylong_http::body::TextBody; 73 /// 74 /// // `TextBody` has 5-bytes length content. 75 /// let mut body = TextBody::from_bytes(b"Hello"); 76 /// 77 /// // We can use any non-zero length `buf` to read it. 78 /// let mut buf = [0u8; 4]; 79 /// 80 /// // Read 4 bytes. `buf` is filled. 81 /// // The remaining 1 bytes of `TextBody` have not been read. 82 /// let read = body.data(&mut buf).unwrap(); 83 /// assert_eq!(read, 4); 84 /// assert_eq!(&buf[..read], b"Hell"); 85 /// 86 /// // Read next 1 bytes. Part of `buf` is filled. 87 /// // All bytes of `TextBody` have been read. 88 /// let read = body.data(&mut buf).unwrap(); 89 /// assert_eq!(read, 1); 90 /// assert_eq!(&buf[..read], b"o"); 91 /// 92 /// // The `TextBody` has already been read, and no more content can be read. 93 /// let read = body.data(&mut buf).unwrap(); 94 /// assert_eq!(read, 0); 95 /// ``` 96 /// 97 /// [`TextBody`]: super::text::TextBody 98 pub trait Body { 99 /// Errors that may occur when reading body data. 100 type Error: Into<Box<dyn Error + Send + Sync>>; 101 102 /// Synchronously reads part of the body data, returning how many bytes 103 /// were read. Body data will be written into buf as much as possible. 104 /// 105 /// # Return Value 106 /// 107 /// - `Ok(0)`: 108 /// If the length of the `buf` is not 0, it means that this 109 /// body has been completely read. 110 /// 111 /// - `Ok(size)` && `size != 0`: 112 /// A part of this body has been read, but the body may not be fully 113 /// read. You can call this method again to obtain next part of data. 114 /// 115 /// - `Err(e)`: 116 /// An error occurred while reading body data. 117 /// 118 /// # Note 119 /// 120 /// It is better for you **not** to use a `buf` with a length of 0, 121 /// otherwise it may lead to misunderstanding of the return value. 122 /// 123 /// # Examples 124 /// 125 /// [`TextBody`] implements `sync_impl::Body`: 126 /// 127 /// ``` 128 /// use ylong_http::body::sync_impl::Body; 129 /// use ylong_http::body::TextBody; 130 /// 131 /// // `TextBody` has 5-bytes length content. 132 /// let mut body = TextBody::from_bytes(b"Hello"); 133 /// 134 /// // We can use any non-zero length `buf` to read it. 135 /// let mut buf = [0u8; 4]; 136 /// 137 /// // Read 4 bytes. `buf` is filled. 138 /// // The remaining 1 bytes of `TextBody` have not been read. 139 /// let read = body.data(&mut buf).unwrap(); 140 /// assert_eq!(read, 4); 141 /// assert_eq!(&buf[..read], b"Hell"); 142 /// 143 /// // Read next 1 bytes. Part of `buf` is filled. 144 /// // All bytes of `TextBody` have been read. 145 /// let read = body.data(&mut buf).unwrap(); 146 /// assert_eq!(read, 1); 147 /// assert_eq!(&buf[..read], b"o"); 148 /// 149 /// // The `TextBody` has already been read, and no more content can be read. 150 /// let read = body.data(&mut buf).unwrap(); 151 /// assert_eq!(read, 0); 152 /// ``` 153 /// 154 /// [`TextBody`]: super::text::TextBody data(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>155 fn data(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>; 156 157 /// Gets trailer headers. trailer(&mut self) -> Result<Option<Headers>, Self::Error>158 fn trailer(&mut self) -> Result<Option<Headers>, Self::Error> { 159 Ok(None) 160 } 161 } 162 163 impl<T: Read> Body for T { 164 type Error = std::io::Error; 165 data(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>166 fn data(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> { 167 self.read(buf) 168 } 169 } 170 } 171 172 /// Asynchronous `Body` trait definition. 173 pub mod async_impl { 174 use core::future::Future; 175 use core::pin::Pin; 176 use core::task::{Context, Poll}; 177 use std::error::Error; 178 179 use crate::headers::Headers; 180 use crate::{AsyncRead, ReadBuf}; 181 182 /// The `async_impl::Body` trait allows for reading body data 183 /// asynchronously. 184 /// 185 /// # Examples 186 /// 187 /// [`TextBody`] implements `async_impl::Body`: 188 /// 189 /// ``` 190 /// use ylong_http::body::async_impl::Body; 191 /// use ylong_http::body::TextBody; 192 /// 193 /// # async fn read_body_data() { 194 /// // `TextBody` has 5-bytes length content. 195 /// let mut body = TextBody::from_bytes(b"Hello"); 196 /// 197 /// // We can use any non-zero length `buf` to read it. 198 /// let mut buf = [0u8; 4]; 199 /// 200 /// // Read 4 bytes. `buf` is filled. 201 /// // The remaining 1 bytes of `TextBody` have not been read. 202 /// let read = body.data(&mut buf).await.unwrap(); 203 /// assert_eq!(read, 4); 204 /// assert_eq!(&buf[..read], b"Hell"); 205 /// 206 /// // Read next 1 bytes. Part of `buf` is filled. 207 /// // All bytes of `TextBody` have been read. 208 /// let read = body.data(&mut buf).await.unwrap(); 209 /// assert_eq!(read, 1); 210 /// assert_eq!(&buf[..read], b"o"); 211 /// 212 /// // The `TextBody` has already been read, and no more content can be read. 213 /// let read = body.data(&mut buf).await.unwrap(); 214 /// assert_eq!(read, 0); 215 /// # } 216 /// ``` 217 /// 218 /// [`TextBody`]: super::text::TextBody 219 pub trait Body: Unpin + Sized { 220 /// Errors that may occur when reading body data. 221 type Error: Into<Box<dyn Error + Send + Sync>>; 222 223 /// Reads part of the body data, returning how many bytes were read. 224 /// 225 /// Body data will be written into buf as much as possible. poll_data( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, Self::Error>>226 fn poll_data( 227 self: Pin<&mut Self>, 228 cx: &mut Context<'_>, 229 buf: &mut [u8], 230 ) -> Poll<Result<usize, Self::Error>>; 231 232 /// Returns a future that reads part of the body data, returning how 233 /// many bytes were read. Body data will be written into buf as much 234 /// as possible. 235 /// 236 /// # Return Value 237 /// 238 /// - `Ok(0)`: 239 /// If the length of the `buf` is not 0, it means that this body has 240 /// been completely read. 241 /// 242 /// - `Ok(size)` && `size != 0`: 243 /// A part of this body has been read, but the body may not be 244 /// completely read. You can call this method again to obtain next part 245 /// of data. 246 /// 247 /// - `Err(e)`: 248 /// An error occurred while reading body data. 249 /// 250 /// # Note 251 /// 252 /// It is better for you **not** to use a `buf` with a length of 0, 253 /// otherwise it may lead to misunderstanding of the return value. 254 /// 255 /// # Examples 256 /// 257 /// [`TextBody`] implements `async_impl::Body`: 258 /// 259 /// ``` 260 /// use ylong_http::body::async_impl::Body; 261 /// use ylong_http::body::TextBody; 262 /// 263 /// # async fn read_body_data() { 264 /// // `TextBody` has 5-bytes length content. 265 /// let mut body = TextBody::from_bytes(b"Hello"); 266 /// 267 /// // We can use any non-zero length `buf` to read it. 268 /// let mut buf = [0u8; 4]; 269 /// 270 /// // Read 4 bytes. `buf` is filled. 271 /// // The remaining 1 bytes of `TextBody` have not been read. 272 /// let read = body.data(&mut buf).await.unwrap(); 273 /// assert_eq!(read, 4); 274 /// assert_eq!(&buf[..read], b"Hell"); 275 /// 276 /// // Read next 1 bytes. Part of `buf` is filled. 277 /// // All bytes of `TextBody` have been read. 278 /// let read = body.data(&mut buf).await.unwrap(); 279 /// assert_eq!(read, 1); 280 /// assert_eq!(&buf[..read], b"o"); 281 /// 282 /// // The `TextBody` has already been read, and no more content can be read. 283 /// let read = body.data(&mut buf).await.unwrap(); 284 /// assert_eq!(read, 0); 285 /// # } 286 /// ``` 287 /// 288 /// [`TextBody`]: super::text::TextBody data<'a, 'b>(&'a mut self, buf: &'b mut [u8]) -> DataFuture<'a, 'b, Self> where Self: 'a, Self: 'b,289 fn data<'a, 'b>(&'a mut self, buf: &'b mut [u8]) -> DataFuture<'a, 'b, Self> 290 where 291 Self: 'a, 292 Self: 'b, 293 { 294 DataFuture { body: self, buf } 295 } 296 297 /// Gets trailer headers. trailer(&mut self) -> Result<Option<Headers>, Self::Error>298 fn trailer(&mut self) -> Result<Option<Headers>, Self::Error> { 299 Ok(None) 300 } 301 } 302 303 /// A future that reads part of the body data, returning how many bytes 304 /// were read. 305 /// 306 /// This future is the return value of `async_impl::Body::data`. 307 /// 308 /// [`async_impl::Body::data`]: Body::data 309 pub struct DataFuture<'a, 'b, T> 310 where 311 T: Body + 'a + 'b, 312 { 313 body: &'a mut T, 314 buf: &'b mut [u8], 315 } 316 317 impl<'a, 'b, T> Future for DataFuture<'a, 'b, T> 318 where 319 T: Body + 'a + 'b, 320 { 321 type Output = Result<usize, T::Error>; 322 poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>323 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { 324 let fut = self.get_mut(); 325 Pin::new(&mut *fut.body).poll_data(cx, fut.buf) 326 } 327 } 328 329 // TODO: Adapter, remove this later. poll_read<T: AsyncRead + Unpin>( reader: Pin<&mut T>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, std::io::Error>>330 pub(crate) fn poll_read<T: AsyncRead + Unpin>( 331 reader: Pin<&mut T>, 332 cx: &mut Context<'_>, 333 buf: &mut [u8], 334 ) -> Poll<Result<usize, std::io::Error>> { 335 let mut read_buf = ReadBuf::new(buf); 336 let filled = read_buf.filled().len(); 337 match reader.poll_read(cx, &mut read_buf) { 338 Poll::Ready(Ok(())) => { 339 let new_filled = read_buf.filled().len(); 340 Poll::Ready(Ok(new_filled - filled)) 341 } 342 Poll::Ready(Err(e)) => Poll::Ready(Err(e)), 343 Poll::Pending => Poll::Pending, 344 } 345 } 346 347 // TODO: Adapter, remove this later. 348 impl Body for &'static [u8] { 349 type Error = std::io::Error; 350 poll_data( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, Self::Error>>351 fn poll_data( 352 self: Pin<&mut Self>, 353 cx: &mut Context<'_>, 354 buf: &mut [u8], 355 ) -> Poll<Result<usize, Self::Error>> { 356 poll_read(self, cx, buf) 357 } 358 } 359 360 // TODO: Adapter, remove this later. 361 impl Body for &'static str { 362 type Error = std::io::Error; 363 poll_data( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, Self::Error>>364 fn poll_data( 365 self: Pin<&mut Self>, 366 cx: &mut Context<'_>, 367 buf: &mut [u8], 368 ) -> Poll<Result<usize, Self::Error>> { 369 poll_read(Pin::new(&mut self.as_bytes()), cx, buf) 370 } 371 } 372 373 // TODO: Adapter, remove this later. 374 impl Body for String { 375 type Error = std::io::Error; 376 poll_data( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, Self::Error>>377 fn poll_data( 378 self: Pin<&mut Self>, 379 cx: &mut Context<'_>, 380 buf: &mut [u8], 381 ) -> Poll<Result<usize, Self::Error>> { 382 poll_read(Pin::new(&mut self.as_bytes()), cx, buf) 383 } 384 } 385 } 386 387 // Type definitions of the origin of the body data. 388 pub(crate) mod origin { 389 use core::ops::{Deref, DerefMut}; 390 use std::io::Read; 391 392 use crate::AsyncRead; 393 394 /// A type that represents the body data is from memory. 395 pub struct FromBytes<'a> { 396 pub(crate) bytes: &'a [u8], 397 } 398 399 impl<'a> FromBytes<'a> { new(bytes: &'a [u8]) -> Self400 pub(crate) fn new(bytes: &'a [u8]) -> Self { 401 Self { bytes } 402 } 403 } 404 405 impl<'a> Deref for FromBytes<'a> { 406 type Target = &'a [u8]; 407 deref(&self) -> &Self::Target408 fn deref(&self) -> &Self::Target { 409 &self.bytes 410 } 411 } 412 413 impl<'a> DerefMut for FromBytes<'a> { deref_mut(&mut self) -> &mut Self::Target414 fn deref_mut(&mut self) -> &mut Self::Target { 415 &mut self.bytes 416 } 417 } 418 419 /// A type that represents the body data is from a synchronous reader. 420 pub struct FromReader<T: Read> { 421 pub(crate) reader: T, 422 } 423 424 impl<T: Read> FromReader<T> { new(reader: T) -> Self425 pub(crate) fn new(reader: T) -> Self { 426 Self { reader } 427 } 428 } 429 430 impl<T: Read> Deref for FromReader<T> { 431 type Target = T; 432 deref(&self) -> &Self::Target433 fn deref(&self) -> &Self::Target { 434 &self.reader 435 } 436 } 437 438 impl<T: Read> DerefMut for FromReader<T> { deref_mut(&mut self) -> &mut Self::Target439 fn deref_mut(&mut self) -> &mut Self::Target { 440 &mut self.reader 441 } 442 } 443 444 /// A type that represent the body data is from an asynchronous reader. 445 pub struct FromAsyncReader<T: AsyncRead + Unpin + Send + Sync> { 446 pub(crate) reader: T, 447 } 448 449 impl<T: AsyncRead + Unpin + Send + Sync> FromAsyncReader<T> { new(reader: T) -> Self450 pub(crate) fn new(reader: T) -> Self { 451 Self { reader } 452 } 453 } 454 455 impl<T: AsyncRead + Unpin + Send + Sync> Deref for FromAsyncReader<T> { 456 type Target = T; 457 deref(&self) -> &Self::Target458 fn deref(&self) -> &Self::Target { 459 &self.reader 460 } 461 } 462 463 impl<T: AsyncRead + Unpin + Send + Sync> DerefMut for FromAsyncReader<T> { deref_mut(&mut self) -> &mut Self::Target464 fn deref_mut(&mut self) -> &mut Self::Target { 465 &mut self.reader 466 } 467 } 468 469 /// A type that represents the body data is from an asynchronous body. 470 pub struct FromAsyncBody<T: super::async_impl::Body> { 471 pub(crate) body: T, 472 } 473 474 impl<T: super::async_impl::Body> FromAsyncBody<T> { new(body: T) -> Self475 pub(crate) fn new(body: T) -> Self { 476 Self { body } 477 } 478 } 479 480 impl<T: super::async_impl::Body> Deref for FromAsyncBody<T> { 481 type Target = T; 482 deref(&self) -> &Self::Target483 fn deref(&self) -> &Self::Target { 484 &self.body 485 } 486 } 487 488 impl<T: super::async_impl::Body> DerefMut for FromAsyncBody<T> { deref_mut(&mut self) -> &mut Self::Target489 fn deref_mut(&mut self) -> &mut Self::Target { 490 &mut self.body 491 } 492 } 493 } 494 495 #[cfg(test)] 496 mod ut_mod { 497 use crate::body::EmptyBody; 498 499 /// UT test cases for `sync_impl::Body::data` of `&mut sync_impl::Body`. 500 /// 501 /// # Brief 502 /// 1. Creates a `sync_impl::Body` object. 503 /// 2. Gets its mutable reference. 504 /// 3. Calls its `sync_impl::Body::data` method and then checks the results. 505 #[test] ut_syn_body_mut_syn_body_data()506 fn ut_syn_body_mut_syn_body_data() { 507 use crate::body::sync_impl::Body; 508 509 let mut body = EmptyBody::new(); 510 let body_mut = &mut body; 511 let mut buf = [0u8; 1]; 512 assert_eq!(body_mut.data(&mut buf), Ok(0)); 513 } 514 515 /// UT test cases for `async_impl::Body::data` of `&mut async_impl::Body`. 516 /// 517 /// # Brief 518 /// 1. Creates a `async_impl::Body` object. 519 /// 2. Gets its mutable reference. 520 /// 3. Calls its `async_impl::Body::data` method and then checks the 521 /// results. 522 #[test] ut_asyn_body_mut_asyn_body_data()523 fn ut_asyn_body_mut_asyn_body_data() { 524 let handle = ylong_runtime::spawn(async move { 525 asyn_body_mut_asyn_body_data().await; 526 }); 527 ylong_runtime::block_on(handle).unwrap(); 528 } 529 asyn_body_mut_asyn_body_data()530 async fn asyn_body_mut_asyn_body_data() { 531 use crate::body::async_impl::Body; 532 533 let mut body = EmptyBody::new(); 534 let body_mut = &mut body; 535 let mut buf = [0u8; 1]; 536 assert_eq!(body_mut.data(&mut buf).await, Ok(0)); 537 } 538 } 539