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//! [`Boundary`], [`MultipartParser`]), which builds without `alloc`.
74//!
75//! ## Features
76//!
77//! | Feature | Default | Adds |
78//! |---|---|---|
79//! | (none) | | the allocation-free core; `no_std` without `alloc` |
80//! | `alloc` | | owned results, the Tier 1 functions, `form!`, `Driver`, `MemorySink` |
81//! | `std` | yes | `MultipartReader`, `FormError::Io`, `FormError::Random`; implies `alloc` |
82//! | `random` | | the OS random source; implies `std` |
83//! | `fs` | | `Store`, `StoredFile`, `Upload`, `UploadSession`, `read_multipart`, `FileName::sanitized`; implies `random` |
84//!
85//! The full contract is `docs/API.md` in the
86//! [repository](https://github.com/jamesgober/form-net). This release
87//! (0.4) adds upload storage, inspection hooks, blocking readers, and typed
88//! extraction to the 0.3 core; the multipart writer, the shared disk budget,
89//! and `sweep` arrive in 0.5.
90
91#![no_std]
92#![doc(html_root_url = "https://docs.rs/form-net")]
93#![cfg_attr(docsrs, feature(doc_cfg))]
94#![forbid(unsafe_code)]
95#![deny(missing_docs)]
96#![cfg_attr(
97    not(test),
98    deny(
99        clippy::unwrap_used,
100        clippy::expect_used,
101        clippy::panic,
102        clippy::indexing_slicing,
103        clippy::arithmetic_side_effects,
104        clippy::todo,
105        clippy::unimplemented,
106        clippy::unreachable,
107        clippy::dbg_macro,
108        clippy::print_stdout,
109        clippy::print_stderr
110    )
111)]
112
113#[cfg(any(feature = "alloc", test))]
114extern crate alloc;
115#[cfg(any(feature = "std", test))]
116extern crate std;
117
118mod error;
119#[cfg(feature = "alloc")]
120mod extract;
121mod hook;
122#[cfg(feature = "std")]
123mod io;
124mod kind;
125mod limits;
126mod multipart;
127mod scan;
128#[cfg(feature = "fs")]
129mod store;
130mod urlencoded;
131mod wipe;
132
133pub use error::{
134    EncodingError, ExtractError, FormError, Limit, Location, PolicyRefusal, SyntaxError,
135};
136#[cfg(feature = "alloc")]
137#[doc(hidden)]
138pub use extract::{__unknown, __value_error};
139#[cfg(feature = "alloc")]
140#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
141pub use extract::{FileData, FileValue, FormBuilder, FromField, FromForm, Secret, ValueError};
142#[cfg(feature = "alloc")]
143#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
144pub use hook::MemorySink;
145pub use hook::{DiscardSink, Inspector, NoInspector, Refusal, Sink, Verdict};
146pub use kind::FormKind;
147pub use limits::{
148    EmptyFilePolicy, ExtendedFilenamePolicy, HeaderPolicy, Limits, PercentPolicy, Policy,
149    TokenField, TokenPlacement,
150};
151pub use multipart::boundary::{Boundary, MAX_BOUNDARY_LEN, MAX_DELIMITER_LEN};
152#[cfg(feature = "alloc")]
153#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
154pub use multipart::driver::{Driver, Progress};
155pub use multipart::filename::{FileName, FileNameSource};
156#[cfg(feature = "alloc")]
157#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
158pub use multipart::owned_head::OwnedPartHead;
159pub use multipart::parser::{
160    Charset, ContentType, Event, Headers, MultipartParser, PartHead, PartKind, PartSummary, Step,
161};
162#[cfg(feature = "alloc")]
163#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
164pub use multipart::{
165    Multipart, Part, parse_multipart, parse_multipart_inspected, parse_multipart_with,
166};
167pub use urlencoded::decode::decode_into;
168pub use urlencoded::encode::encode_into;
169#[cfg(feature = "alloc")]
170#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
171pub use urlencoded::encode::{Serializer, serialize_urlencoded};
172pub use urlencoded::raw::{RawPair, RawPairs, raw_pairs};
173#[cfg(feature = "alloc")]
174#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
175pub use urlencoded::{
176    Form, Pairs, pairs, parse_query, parse_urlencoded, parse_urlencoded_inspected,
177    parse_urlencoded_with,
178};
179
180#[cfg(feature = "std")]
181#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
182pub use io::{MultipartReader, PartReader};
183#[cfg(feature = "fs")]
184#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
185pub use store::{
186    SpillMode, Store, StoreError, StoreSink, StoreStats, StoredFile, StoredReader, Upload,
187    UploadSession, read_multipart,
188};
189
190/// Crate version string, populated by Cargo at build time.
191pub const VERSION: &str = env!("CARGO_PKG_VERSION");
192
193#[cfg(test)]
194mod tests {
195    use super::VERSION;
196
197    #[test]
198    fn test_version_matches_manifest() {
199        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
200        assert_eq!(VERSION.split('.').count(), 3, "expected MAJOR.MINOR.PATCH");
201    }
202
203    #[test]
204    fn test_public_types_are_send_and_sync() {
205        fn send_sync<T: Send + Sync>() {}
206        send_sync::<super::Limits>();
207        send_sync::<super::Policy>();
208        send_sync::<super::Boundary>();
209        send_sync::<super::FormError>();
210        send_sync::<super::MultipartParser<&mut [u8]>>();
211        #[cfg(feature = "alloc")]
212        {
213            send_sync::<super::MultipartParser<alloc::vec::Vec<u8>>>();
214            send_sync::<super::Form>();
215            send_sync::<super::Multipart<'static>>();
216            send_sync::<super::OwnedPartHead>();
217            send_sync::<super::MemorySink>();
218            send_sync::<super::Driver<alloc::vec::Vec<u8>, super::MemorySink>>();
219            send_sync::<super::FileData>();
220            send_sync::<super::Secret>();
221        }
222        #[cfg(feature = "std")]
223        send_sync::<super::MultipartReader<std::fs::File>>();
224        #[cfg(feature = "fs")]
225        {
226            send_sync::<super::Store>();
227            send_sync::<super::StoreSink>();
228            send_sync::<super::StoredFile>();
229            send_sync::<super::Upload>();
230            send_sync::<super::UploadSession>();
231        }
232    }
233}