http_net/lib.rs
1//! # http_net
2//!
3//! An HTTP/1.1 engine that does no I/O itself. Feed it the bytes a socket
4//! delivered; it hands back requests (or responses) as borrowed views of
5//! those bytes, decodes their bodies, and serializes what you send back.
6//! The caller owns sockets, threads, and timers, so the same core runs
7//! under a blocking loop, an event loop, or a test that never opens a
8//! socket.
9//!
10//! Parsing follows RFC 9112 strictly. Messages that recipients could
11//! disagree about are refused rather than repaired: conflicting
12//! `Content-Length` / `Transfer-Encoding`, duplicate `Content-Length`,
13//! obsolete line folding, bare CR or LF, whitespace before a colon, and
14//! control characters in field values each have their own [`HttpError`].
15//! Every buffer is bounded by [`Limits`], and each limit is checked before
16//! the bytes it governs are buffered.
17//!
18//! ## Tier 1: serve and fetch (blocking, `std`)
19//!
20//! ```
21//! # #[cfg(feature = "std")]
22//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
23//! use http_net::{blocking, Response};
24//!
25//! let server = blocking::Server::bind("127.0.0.1:0")?;
26//! let addr = server.local_addr();
27//! let stop = server.shutdown_handle();
28//! let t = std::thread::spawn(move || server.serve(|req, _body| Response::text(200, req.path())));
29//!
30//! let resp = blocking::get(&format!("http://{addr}/hi"))?;
31//! assert_eq!(resp.text(), Some("/hi"));
32//!
33//! stop.shutdown();
34//! t.join().unwrap()?;
35//! # Ok(())
36//! # }
37//! # #[cfg(not(feature = "std"))]
38//! # fn main() {}
39//! ```
40//!
41//! ## Tier 2: the sans-IO connection
42//!
43//! ```
44//! use http_net::{Response, ServerConn, ServerEvent};
45//!
46//! let mut conn = ServerConn::new();
47//! let mut out = Vec::new();
48//! let _ = conn.feed(b"GET /status HTTP/1.1\r\nHost: localhost\r\n\r\n");
49//! loop {
50//! match conn.poll()? {
51//! ServerEvent::Request(req) => assert_eq!(req.path(), "/status"),
52//! ServerEvent::Body(_) => {}
53//! ServerEvent::RequestEnd => conn.respond(&Response::text(200, "up"), &mut out)?,
54//! _ => break, // NeedInput: read more from the socket
55//! }
56//! }
57//! assert!(out.starts_with(b"HTTP/1.1 200 OK\r\n"));
58//! # Ok::<(), http_net::HttpError>(())
59//! ```
60//!
61//! [`ClientConn`] is the mirror image for the client side, and the
62//! `blocking` module shows how either is driven over `std::net`.
63//!
64//! ## Protocol upgrades
65//!
66//! A request with `Connection: upgrade` and an `Upgrade` field offering a
67//! protocol other than `h2c` reports [`RequestHead::is_upgrade`]. Answering
68//! it with [`Response::switching_protocols`] naming an offered protocol
69//! moves the connection to [`ServerEvent::Upgraded`], after which
70//! [`ServerConn::remaining_input`] holds any bytes of the new protocol that
71//! arrived with the request. This is the hand-off point for a WebSocket
72//! engine such as `ws-net`.
73//!
74//! ## Feature flags
75//!
76//! | Feature | Default | Description |
77//! |---|---|---|
78//! | `std` | yes | The `blocking` adapter over `std::net`. Without it the crate is `no_std` and needs only `alloc` (built in CI for `thumbv7em-none-eabihf`). |
79//!
80//! ## Credentials in `Debug` output
81//!
82//! Every `Debug` implementation in the crate prints the values of
83//! `authorization`, `proxy-authorization`, `cookie`, and `set-cookie` as
84//! `<redacted N bytes>`, so logging a request with `{:?}` never leaks a
85//! session cookie or a bearer token. The accessors return the real values.
86
87#![cfg_attr(not(feature = "std"), no_std)]
88#![cfg_attr(docsrs, feature(doc_cfg))]
89#![forbid(unsafe_code)]
90#![deny(missing_docs)]
91#![deny(unused_must_use)]
92#![deny(unused_results)]
93#![deny(clippy::unwrap_used)]
94#![deny(clippy::expect_used)]
95#![deny(clippy::todo)]
96#![deny(clippy::unimplemented)]
97#![deny(clippy::print_stdout)]
98#![deny(clippy::print_stderr)]
99#![deny(clippy::dbg_macro)]
100#![deny(clippy::unreachable)]
101#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
102
103extern crate alloc;
104
105mod body;
106mod buffer;
107mod chunked;
108mod client;
109mod date;
110mod error;
111mod forward;
112mod head;
113mod limits;
114mod message;
115mod method;
116mod preface;
117mod raw;
118mod redact;
119mod scan;
120mod server;
121pub mod status;
122mod write;
123
124#[cfg(feature = "std")]
125#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
126pub mod blocking;
127
128pub use chunked::{ChunkStep, ChunkedDecoder};
129pub use client::{ClientConn, ClientEvent, ClientLeniency};
130pub use date::{DateCache, HttpDate};
131pub use error::HttpError;
132pub use forward::is_hop_by_hop;
133pub use head::{
134 Asked, BodyFraming, FieldSpan, HeaderValues, Headers, ListElements, RequestHead, ResponseHead,
135 Span, TargetForm, Version,
136};
137pub use limits::Limits;
138pub use message::{Request, Response};
139pub use method::{Method, MethodSet};
140pub use preface::is_h2_preface;
141pub use raw::{
142 HeadFacts, OwnedRequestHead, Parsed, ParsedRequest, ParsedResponse, RawHead,
143 parse_request_head, parse_response_head,
144};
145pub use server::{Progress, ServerConn, ServerEvent};
146pub use status::{StatusClass, reason_phrase, status_allows_body, status_class};
147pub use write::{BodyPlan, OutgoingBody, Output, ResponseHeadRef};
148
149/// The crate version, as published (`CARGO_PKG_VERSION`).
150///
151/// # Examples
152///
153/// ```
154/// assert_eq!(http_net::VERSION.split('.').count(), 3);
155/// ```
156pub const VERSION: &str = env!("CARGO_PKG_VERSION");
157
158// The README's and the API reference's examples run as doctests, so their
159// claims stay true.
160#[cfg(all(doctest, feature = "std"))]
161#[doc = include_str!("../README.md")]
162struct ReadmeDoctests;
163
164#[cfg(all(doctest, feature = "std"))]
165#[doc = include_str!("../docs/API.md")]
166struct ApiDoctests;
167
168#[cfg(all(doctest, feature = "std"))]
169#[doc = include_str!("../docs/MIGRATION.md")]
170struct MigrationDoctests;
171
172#[cfg(test)]
173mod tests {
174 #[test]
175 fn test_public_types_are_send_and_sync() {
176 fn assert<T: Send + Sync>() {}
177 assert::<crate::ServerConn>();
178 assert::<crate::ServerEvent<'_>>();
179 assert::<crate::ClientConn>();
180 assert::<crate::ClientLeniency>();
181 assert::<crate::ClientEvent<'_>>();
182 assert::<crate::Response>();
183 assert::<crate::Request>();
184 assert::<crate::RequestHead<'_>>();
185 assert::<crate::ResponseHead<'_>>();
186 assert::<crate::Headers<'_>>();
187 assert::<crate::HeaderValues<'_, '_>>();
188 assert::<crate::HttpError>();
189 assert::<crate::Limits>();
190 assert::<crate::Method>();
191 assert::<crate::MethodSet>();
192 assert::<crate::Version>();
193 assert::<crate::BodyFraming>();
194 assert::<crate::TargetForm>();
195 assert::<crate::StatusClass>();
196 #[cfg(feature = "std")]
197 {
198 assert::<crate::blocking::Server>();
199 assert::<crate::blocking::ServerConfig>();
200 assert::<crate::blocking::ShutdownHandle>();
201 assert::<crate::blocking::Connection>();
202 assert::<crate::blocking::Incoming<'_>>();
203 assert::<crate::blocking::Upgraded>();
204 assert::<crate::blocking::Client>();
205 assert::<crate::blocking::ClientResponse>();
206 assert::<crate::blocking::Error>();
207 }
208 }
209
210 #[test]
211 fn test_version_matches_the_manifest() {
212 assert_eq!(crate::VERSION, env!("CARGO_PKG_VERSION"));
213 }
214}