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` and `docs/PLATFORM-NOTES.md`. This release (0.5)
90//! is feature complete.
91
92#![no_std]
93#![doc(html_root_url = "https://docs.rs/form-net")]
94#![cfg_attr(docsrs, feature(doc_cfg))]
95#![forbid(unsafe_code)]
96#![deny(missing_docs)]
97#![cfg_attr(
98    not(test),
99    deny(
100        clippy::unwrap_used,
101        clippy::expect_used,
102        clippy::panic,
103        clippy::indexing_slicing,
104        clippy::arithmetic_side_effects,
105        clippy::todo,
106        clippy::unimplemented,
107        clippy::unreachable,
108        clippy::dbg_macro,
109        clippy::print_stdout,
110        clippy::print_stderr
111    )
112)]
113
114#[cfg(any(feature = "alloc", test))]
115extern crate alloc;
116#[cfg(any(feature = "std", test))]
117extern crate std;
118
119mod error;
120#[cfg(feature = "alloc")]
121mod extract;
122mod hook;
123#[cfg(feature = "std")]
124mod io;
125mod kind;
126mod limits;
127mod multipart;
128#[cfg(feature = "random")]
129mod random;
130mod scan;
131#[cfg(feature = "fs")]
132mod store;
133mod urlencoded;
134mod wipe;
135
136#[cfg(feature = "alloc")]
137#[doc(hidden)]
138pub use alloc::vec::Vec as __Vec;
139pub use error::{
140    EncodingError, ExtractError, FormError, Limit, Location, PolicyRefusal, SyntaxError,
141};
142#[cfg(feature = "alloc")]
143#[doc(hidden)]
144pub use extract::{__push_field_error, __unknown, __value_error};
145#[cfg(feature = "alloc")]
146#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
147pub use extract::{
148    FileData, FileValue, FormBuilder, FormErrors, FromField, FromForm, Secret, ValueError,
149};
150#[cfg(feature = "alloc")]
151#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
152pub use hook::MemorySink;
153pub use hook::{DiscardSink, Inspector, NoInspector, Refusal, Sink, Verdict};
154pub use kind::FormKind;
155pub use limits::{
156    EmptyFilePolicy, ExtendedFilenamePolicy, HeaderPolicy, Limits, PercentPolicy, Policy,
157    TokenField, TokenPlacement,
158};
159pub use multipart::boundary::{Boundary, MAX_BOUNDARY_LEN, MAX_DELIMITER_LEN};
160#[cfg(feature = "alloc")]
161#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
162pub use multipart::driver::{Driver, Progress};
163pub use multipart::filename::{FileName, FileNameSource};
164#[cfg(feature = "alloc")]
165#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
166pub use multipart::owned_head::OwnedPartHead;
167pub use multipart::parser::{
168    Charset, ContentType, Event, Headers, MultipartParser, PartHead, PartKind, PartSummary, Step,
169};
170#[cfg(feature = "std")]
171#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
172pub use multipart::writer::MultipartWriter;
173pub use multipart::writer::encode_part_head;
174#[cfg(feature = "alloc")]
175#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
176pub use multipart::{
177    Multipart, Part, parse_multipart, parse_multipart_inspected, parse_multipart_with,
178};
179pub use urlencoded::decode::decode_into;
180pub use urlencoded::encode::encode_into;
181#[cfg(feature = "alloc")]
182#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
183pub use urlencoded::encode::{Serializer, serialize_urlencoded};
184pub use urlencoded::raw::{RawPair, RawPairs, raw_pairs};
185pub use urlencoded::stream::{UrlencodedEvent, UrlencodedParser, UrlencodedStep};
186#[cfg(feature = "alloc")]
187#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
188pub use urlencoded::{
189    Form, Pairs, pairs, parse_query, parse_urlencoded, parse_urlencoded_inspected,
190    parse_urlencoded_with,
191};
192
193#[cfg(feature = "std")]
194#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
195pub use io::{MultipartReader, PartReader};
196#[cfg(feature = "fs")]
197#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
198pub use store::{
199    SpillBudget, SpillMode, SpillQuota, Store, StoreError, StoreSink, StoreStats, StoredFile,
200    StoredReader, Upload, UploadSession, read_multipart, sweep,
201};
202
203/// Crate version string, populated by Cargo at build time.
204pub const VERSION: &str = env!("CARGO_PKG_VERSION");
205
206#[cfg(test)]
207mod tests {
208    use super::VERSION;
209
210    #[test]
211    fn test_version_matches_manifest() {
212        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
213        assert_eq!(VERSION.split('.').count(), 3, "expected MAJOR.MINOR.PATCH");
214    }
215
216    #[test]
217    fn test_public_types_are_send_and_sync() {
218        fn send_sync<T: Send + Sync>() {}
219        send_sync::<super::Limits>();
220        send_sync::<super::Policy>();
221        send_sync::<super::Boundary>();
222        send_sync::<super::FormError>();
223        send_sync::<super::MultipartParser<&mut [u8]>>();
224        #[cfg(feature = "alloc")]
225        {
226            send_sync::<super::MultipartParser<alloc::vec::Vec<u8>>>();
227            send_sync::<super::Form>();
228            send_sync::<super::Multipart<'static>>();
229            send_sync::<super::OwnedPartHead>();
230            send_sync::<super::MemorySink>();
231            send_sync::<super::Driver<alloc::vec::Vec<u8>, super::MemorySink>>();
232            send_sync::<super::FileData>();
233            send_sync::<super::Secret>();
234        }
235        #[cfg(feature = "std")]
236        send_sync::<super::MultipartReader<std::fs::File>>();
237        #[cfg(feature = "fs")]
238        {
239            send_sync::<super::Store>();
240            send_sync::<super::StoreSink>();
241            send_sync::<super::StoredFile>();
242            send_sync::<super::Upload>();
243            send_sync::<super::UploadSession>();
244        }
245    }
246}
247
248/// Every example of `docs/API.md`, compiled and run as a doctest (D-100).
249/// They use every feature, so they run with `--all-features`.
250#[cfg(all(doctest, feature = "fs", feature = "unicode"))]
251#[doc = include_str!("../docs/API.md")]
252struct ApiExamples;