Skip to main content

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 client;
108mod error;
109mod head;
110mod limits;
111mod message;
112mod method;
113mod redact;
114mod server;
115pub mod status;
116mod syntax;
117
118#[cfg(feature = "std")]
119#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
120pub mod blocking;
121
122pub use client::{ClientConn, ClientEvent};
123pub use error::HttpError;
124pub use head::{
125    BodyFraming, HeaderValues, Headers, RequestHead, ResponseHead, TargetForm, Version,
126};
127pub use limits::Limits;
128pub use message::{Request, Response};
129pub use method::{Method, MethodSet};
130pub use server::{ServerConn, ServerEvent};
131pub use status::{StatusClass, reason_phrase, status_class};
132
133/// The crate version, as published (`CARGO_PKG_VERSION`).
134///
135/// # Examples
136///
137/// ```
138/// assert_eq!(http_net::VERSION.split('.').count(), 3);
139/// ```
140pub const VERSION: &str = env!("CARGO_PKG_VERSION");
141
142// The README's and the API reference's examples run as doctests, so their
143// claims stay true.
144#[cfg(all(doctest, feature = "std"))]
145#[doc = include_str!("../README.md")]
146struct ReadmeDoctests;
147
148#[cfg(all(doctest, feature = "std"))]
149#[doc = include_str!("../docs/API.md")]
150struct ApiDoctests;
151
152#[cfg(all(doctest, feature = "std"))]
153#[doc = include_str!("../docs/MIGRATION.md")]
154struct MigrationDoctests;
155
156#[cfg(test)]
157mod tests {
158    #[test]
159    fn test_public_types_are_send_and_sync() {
160        fn assert<T: Send + Sync>() {}
161        assert::<crate::ServerConn>();
162        assert::<crate::ServerEvent<'_>>();
163        assert::<crate::ClientConn>();
164        assert::<crate::ClientEvent<'_>>();
165        assert::<crate::Response>();
166        assert::<crate::Request>();
167        assert::<crate::RequestHead<'_>>();
168        assert::<crate::ResponseHead<'_>>();
169        assert::<crate::Headers<'_>>();
170        assert::<crate::HeaderValues<'_, '_>>();
171        assert::<crate::HttpError>();
172        assert::<crate::Limits>();
173        assert::<crate::Method>();
174        assert::<crate::MethodSet>();
175        assert::<crate::Version>();
176        assert::<crate::BodyFraming>();
177        assert::<crate::TargetForm>();
178        assert::<crate::StatusClass>();
179        #[cfg(feature = "std")]
180        {
181            assert::<crate::blocking::Server>();
182            assert::<crate::blocking::ServerConfig>();
183            assert::<crate::blocking::ShutdownHandle>();
184            assert::<crate::blocking::Connection>();
185            assert::<crate::blocking::Incoming<'_>>();
186            assert::<crate::blocking::Upgraded>();
187            assert::<crate::blocking::Client>();
188            assert::<crate::blocking::ClientResponse>();
189            assert::<crate::blocking::Error>();
190        }
191    }
192
193    #[test]
194    fn test_version_matches_the_manifest() {
195        assert_eq!(crate::VERSION, env!("CARGO_PKG_VERSION"));
196    }
197}