Skip to main content

form_net/
lib.rs

1//! # form_net
2//!
3//! Parses what a browser sends when a form is submitted:
4//! `application/x-www-form-urlencoded` fields and `multipart/form-data`
5//! uploads. It does no I/O: feed it bytes, get fields and parts.
6//!
7//! Every budget (field count, name and value length, part count, part
8//! header size, file count and size, total size) is checked before the bytes
9//! it governs are buffered. Input that two parsers could read differently is
10//! refused with a precise error, never repaired. No error, `Debug`, or
11//! `Display` output ever contains a field value or a file name.
12//!
13//! ## Tier 1
14//!
15//! ```
16//! // A urlencoded body
17//! let form = form_net::parse_urlencoded(b"email=a%40b.example&remember=on")?;
18//! assert_eq!(form.get("email"), Some("a@b.example"));
19//!
20//! // A query string
21//! let query = form_net::parse_query(b"?q=rust+forms&page=2")?;
22//! assert_eq!(query.get("q"), Some("rust forms"));
23//!
24//! // Building one
25//! assert_eq!(form_net::serialize_urlencoded([("q", "rust forms")]), "q=rust+forms");
26//!
27//! // A buffered multipart body
28//! let body = b"--X\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHoliday\r\n--X--";
29//! let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
30//! assert_eq!(mp.field("title"), Some("Holiday"));
31//! # Ok::<(), form_net::FormError>(())
32//! ```
33//!
34//! A typed form, from either encoding:
35//!
36//! ```
37//! use form_net::FromForm;
38//!
39//! form_net::form! {
40//!     pub struct Login {
41//!         pub email: String,
42//!         pub password: form_net::Secret,
43//!         pub remember: bool,
44//!     }
45//!     ignore = ["csrf_token"];
46//! }
47//!
48//! let body = b"email=a%40b.example&password=pw&remember=on&csrf_token=t";
49//! let login = Login::from_body(b"application/x-www-form-urlencoded", body)?;
50//! assert_eq!((login.email.as_str(), login.remember), ("a@b.example", true));
51//! # Ok::<(), form_net::FormError>(())
52//! ```
53//!
54//! An upload read from any `std::io::Read`, large files spilled to private
55//! temporary files that are deleted on drop (feature `fs`):
56//!
57//! ```
58//! # #[cfg(feature = "fs")] {
59//! let body = b"--X\r\nContent-Disposition: form-data; name=doc; filename=a.txt\r\n\r\nhello\r\n--X--";
60//! let upload = form_net::read_multipart(b"multipart/form-data; boundary=X", &body[..])?;
61//! assert_eq!(upload.file("doc").map(|f| f.len()), Some(5));
62//! # }
63//! # Ok::<(), form_net::FormError>(())
64//! ```
65//!
66//! ## Tiers 2 and 3
67//!
68//! Explicit [`Limits`] and [`Policy`] per route (`parse_urlencoded_with`,
69//! `parse_multipart_with`); an [`Inspector`] that sees every part head, the
70//! first bytes of every file, and every field before anything is stored;
71//! a [`Sink`] that decides where file bytes go, driven by the [`Driver`]; the
72//! allocation-free core ([`raw_pairs`], [`decode_into`], [`encode_into`],
73//! [`UrlencodedParser`], [`Boundary`], [`MultipartParser`],
74//! [`encode_part_head`]), which builds without `alloc`.
75//!
76//! ## Features
77//!
78//! | Feature | Default | Adds |
79//! |---|---|---|
80//! | (none) | | the allocation-free core; `no_std` without `alloc` |
81//! | `alloc` | | owned results, the Tier 1 functions, `form!`, `Driver`, `MemorySink` |
82//! | `std` | yes | `MultipartReader`, `MultipartWriter`, `FormError::Io`, `FormError::Random`; implies `alloc` |
83//! | `random` | | `Boundary::generate`, `MultipartWriter::new`; implies `std` |
84//! | `fs` | | `Store`, `StoredFile`, `Upload`, `UploadSession`, `read_multipart`, `SpillQuota`, `sweep`, `FileName::sanitized`; implies `random` |
85//! | `unicode` | | `FileName::nfc`, and NFC in `FileName::sanitized`; implies `alloc` |
86//!
87//! The full contract is `docs/API.md` in the
88//! [repository](https://github.com/jamesgober/form-net), with
89//! `docs/ARCHITECTURE.md`, `docs/PLATFORM-NOTES.md`, and
90//! `docs/PERFORMANCE.md` (measurements against the other Rust form parsers).
91//! This release (0.7) is feature complete, optimised, and hardened.
92
93#![no_std]
94#![doc(html_root_url = "https://docs.rs/form-net")]
95#![cfg_attr(docsrs, feature(doc_cfg))]
96#![forbid(unsafe_code)]
97#![deny(missing_docs)]
98#![cfg_attr(
99    not(test),
100    deny(
101        clippy::unwrap_used,
102        clippy::expect_used,
103        clippy::panic,
104        clippy::indexing_slicing,
105        clippy::arithmetic_side_effects,
106        clippy::todo,
107        clippy::unimplemented,
108        clippy::unreachable,
109        clippy::dbg_macro,
110        clippy::print_stdout,
111        clippy::print_stderr
112    )
113)]
114
115#[cfg(any(feature = "alloc", test))]
116extern crate alloc;
117#[cfg(any(feature = "std", test))]
118extern crate std;
119
120mod error;
121#[cfg(feature = "alloc")]
122mod extract;
123mod hook;
124#[cfg(feature = "std")]
125mod io;
126mod kind;
127mod limits;
128mod multipart;
129#[cfg(feature = "random")]
130mod random;
131mod scan;
132#[cfg(feature = "fs")]
133mod store;
134mod urlencoded;
135mod wipe;
136
137#[cfg(feature = "alloc")]
138#[doc(hidden)]
139pub use alloc::vec::Vec as __Vec;
140pub use error::{
141    EncodingError, ExtractError, FormError, Limit, Location, PolicyRefusal, SyntaxError,
142};
143#[cfg(feature = "alloc")]
144#[doc(hidden)]
145pub use extract::{__push_field_error, __unknown, __value_error};
146#[cfg(feature = "alloc")]
147#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
148pub use extract::{
149    FileData, FileValue, FormBuilder, FormErrors, FromField, FromForm, Secret, ValueError,
150};
151#[cfg(feature = "alloc")]
152#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
153pub use hook::MemorySink;
154pub use hook::{DiscardSink, Inspector, NoInspector, Refusal, Sink, Verdict};
155pub use kind::FormKind;
156pub use limits::{
157    EmptyFilePolicy, ExtendedFilenamePolicy, HeaderPolicy, Limits, PercentPolicy, Policy,
158    TokenField, TokenPlacement,
159};
160pub use multipart::boundary::{Boundary, MAX_BOUNDARY_LEN, MAX_DELIMITER_LEN};
161#[cfg(feature = "alloc")]
162#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
163pub use multipart::driver::{Driver, Progress};
164pub use multipart::filename::{FileName, FileNameSource};
165#[cfg(feature = "alloc")]
166#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
167pub use multipart::owned_head::OwnedPartHead;
168pub use multipart::parser::{
169    Charset, ContentType, Event, Headers, MultipartParser, PartHead, PartKind, PartSummary, Step,
170};
171#[cfg(feature = "std")]
172#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
173pub use multipart::writer::MultipartWriter;
174pub use multipart::writer::encode_part_head;
175#[cfg(feature = "alloc")]
176#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
177pub use multipart::{
178    Multipart, Part, parse_multipart, parse_multipart_inspected, parse_multipart_with,
179};
180pub use urlencoded::decode::decode_into;
181pub use urlencoded::encode::encode_into;
182#[cfg(feature = "alloc")]
183#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
184pub use urlencoded::encode::{Serializer, serialize_urlencoded};
185pub use urlencoded::raw::{RawPair, RawPairs, raw_pairs};
186pub use urlencoded::stream::{UrlencodedEvent, UrlencodedParser, UrlencodedStep};
187#[cfg(feature = "alloc")]
188#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
189pub use urlencoded::{
190    Form, Pairs, pairs, parse_query, parse_urlencoded, parse_urlencoded_inspected,
191    parse_urlencoded_with,
192};
193
194#[cfg(feature = "std")]
195#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
196pub use io::{MultipartReader, PartReader};
197#[cfg(feature = "fs")]
198#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
199pub use store::{
200    SpillBudget, SpillMode, SpillQuota, Store, StoreError, StoreSink, StoreStats, StoredFile,
201    StoredReader, Upload, UploadSession, read_multipart, sweep,
202};
203
204/// Crate version string, populated by Cargo at build time.
205pub const VERSION: &str = env!("CARGO_PKG_VERSION");
206
207#[cfg(test)]
208mod tests {
209    use super::VERSION;
210
211    #[test]
212    fn test_version_matches_manifest() {
213        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
214        assert_eq!(VERSION.split('.').count(), 3, "expected MAJOR.MINOR.PATCH");
215    }
216
217    #[test]
218    fn test_public_types_are_send_and_sync() {
219        fn send_sync<T: Send + Sync>() {}
220        send_sync::<super::Limits>();
221        send_sync::<super::Policy>();
222        send_sync::<super::Boundary>();
223        send_sync::<super::FormError>();
224        send_sync::<super::MultipartParser<&mut [u8]>>();
225        #[cfg(feature = "alloc")]
226        {
227            send_sync::<super::MultipartParser<alloc::vec::Vec<u8>>>();
228            send_sync::<super::Form>();
229            send_sync::<super::Multipart<'static>>();
230            send_sync::<super::OwnedPartHead>();
231            send_sync::<super::MemorySink>();
232            send_sync::<super::Driver<alloc::vec::Vec<u8>, super::MemorySink>>();
233            send_sync::<super::FileData>();
234            send_sync::<super::Secret>();
235        }
236        #[cfg(feature = "std")]
237        send_sync::<super::MultipartReader<std::fs::File>>();
238        #[cfg(feature = "fs")]
239        {
240            send_sync::<super::Store>();
241            send_sync::<super::StoreSink>();
242            send_sync::<super::StoredFile>();
243            send_sync::<super::Upload>();
244            send_sync::<super::UploadSession>();
245        }
246    }
247}
248
249/// Every example of `docs/API.md`, compiled and run as a doctest (D-100).
250/// They use every feature, so they run with `--all-features`.
251#[cfg(all(doctest, feature = "fs", feature = "unicode"))]
252#[doc = include_str!("../docs/API.md")]
253struct ApiExamples;