rocket/request/from_param.rs
1use std::str::FromStr;
2use std::path::PathBuf;
3
4use crate::error::Empty;
5use crate::either::Either;
6use crate::http::uri::{Segments, error::PathError, fmt::Path};
7
8/// Trait to convert a dynamic path segment string to a concrete value.
9///
10/// This trait is used by Rocket's code generation facilities to parse dynamic
11/// path segment string values into a given type. That is, when a path contains
12/// a dynamic segment `<param>` where `param` has some type `T` that implements
13/// `FromParam`, `T::from_param` will be called.
14///
15/// # Deriving
16///
17/// The `FromParam` trait can be automatically derived for C-like enums. See
18/// [`FromParam` derive](macro@rocket::FromParam) for more information.
19///
20/// # Forwarding
21///
22/// If the conversion fails, the incoming request will be forwarded to the next
23/// matching route, if any. For instance, consider the following route and
24/// handler for the dynamic `"/<id>"` path:
25///
26/// ```rust
27/// # #[macro_use] extern crate rocket;
28/// #[get("/<id>")]
29/// fn hello(id: usize) -> String {
30/// # let _id = id;
31/// # /*
32/// ...
33/// # */
34/// # "".to_string()
35/// }
36/// # fn main() { }
37/// ```
38///
39/// If `usize::from_param` returns an `Ok(usize)` variant, the encapsulated
40/// value is used as the `id` function parameter. If not, the request is
41/// forwarded to the next matching route. Since there are no additional matching
42/// routes, this example will result in a 422 error for requests with invalid
43/// `id` values.
44///
45/// # Catching Errors
46///
47/// Sometimes, a forward is not desired, and instead, we simply want to know
48/// that the dynamic path segment could not be parsed into some desired type
49/// `T`. In these cases, types of `Option<T>`, `Result<T, T::Error>`, or
50/// `Either<A, B>` can be used, which implement `FromParam` themselves.
51///
52/// * **`Option<T>`** _where_ **`T: FromParam`**
53///
54/// Always returns successfully.
55///
56/// If the conversion to `T` fails, `None` is returned. If the conversion
57/// succeeds, `Some(value)` is returned.
58///
59/// * **`Result<T, T::Error>`** _where_ **`T: FromParam`**
60///
61/// Always returns successfully.
62///
63/// If the conversion to `T` fails, `Err(error)` is returned. If the
64/// conversion succeeds, `Ok(value)` is returned.
65///
66/// * **`Either<A, B>`** _where_ **`A: FromParam`** _and_ **`B: FromParam`**
67///
68/// Fails only when both `A::from_param` and `B::from_param` fail. If one
69/// of the two succeeds, the successful value is returned in
70/// `Either::Left(A)` or `Either::Right(B)` variant, respectively. If both
71/// fail, the error values from both calls are returned in a tuple in the
72/// `Err` variant.
73///
74/// `Either<A, B>` is particularly useful with a `B` type of `&str`, allowing
75/// you to retrieve the invalid path segment. Because `&str`'s implementation of
76/// `FromParam` succeeds for every non-empty segment, the `Right` variant of the
77/// `Either` will contain the path segment in case of failure unless the segment
78/// is empty.
79///
80/// For instance, consider the following route and handler:
81///
82/// ```rust
83/// # #[macro_use] extern crate rocket;
84/// use rocket::either::{Either, Left, Right};
85///
86/// #[get("/<id>")]
87/// fn hello(id: Either<usize, &str>) -> String {
88/// match id {
89/// Left(id_num) => format!("usize: {}", id_num),
90/// Right(string) => format!("Not a usize: {}", string)
91/// }
92/// }
93/// # fn main() { }
94/// ```
95///
96/// In the above example, if the dynamic path segment cannot be parsed into a
97/// `usize`, the raw path segment is returned in the `Right` variant of the
98/// `Either<usize, &str>` value.
99///
100/// # Provided Implementations
101///
102/// Rocket implements `FromParam` for several standard library types. Their
103/// behavior is documented here.
104///
105/// *
106/// * Primitive types: **f32, f64, isize, i8, i16, i32, i64, i128,
107/// usize, u8, u16, u32, u64, u128, bool**
108/// * `IpAddr` and `SocketAddr` types: **IpAddr, Ipv4Addr, Ipv6Addr,
109/// SocketAddrV4, SocketAddrV6, SocketAddr**
110/// * `NonZero*` types: **NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64,
111/// NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32,
112/// NonZeroU64, NonZeroU128, NonZeroUsize**
113///
114/// A value is parsed successfully if the `from_str` method from the given
115/// type returns successfully. Otherwise, the error returned by `from_str`
116/// is returned in the `Err` value.
117///
118/// * **&str, String**
119///
120/// _This implementation fails only if the path segment is empty._
121///
122/// Returns the percent-decoded path segment with invalid UTF-8 byte
123/// sequences replaced by � U+FFFD. If the segment is empty, as it is for
124/// the trailing slash in a request to `/foo/` matched against `/foo/<bar>`,
125/// an [`Empty`] error is returned.
126///
127/// * **Option<T>** _where_ **T: FromParam**
128///
129/// _This implementation always returns successfully._
130///
131/// The path segment is parsed by `T`'s `FromParam` implementation. If the
132/// parse succeeds, a `Some(parsed_value)` is returned. Otherwise, a `None`
133/// is returned.
134///
135/// * **Result<T, T::Error>** _where_ **T: FromParam**
136///
137/// _This implementation always returns successfully._
138///
139/// The path segment is parsed by `T`'s `FromParam` implementation. The
140/// returned `Result` value is returned.
141///
142/// # Example
143///
144/// Say you want to parse a segment of the form:
145///
146/// ```text
147/// [a-zA-Z]+:[0-9]+
148/// ```
149///
150/// into the following structure, where the string before the `:` is stored in
151/// `key` and the number after the colon is stored in `value`:
152///
153/// ```rust
154/// struct MyParam<'r> {
155/// key: &'r str,
156/// value: usize
157/// }
158/// ```
159///
160/// The following implementation accomplishes this:
161///
162/// ```rust
163/// use rocket::request::FromParam;
164/// # #[allow(dead_code)]
165/// # struct MyParam<'r> { key: &'r str, value: usize }
166///
167/// impl<'r> FromParam<'r> for MyParam<'r> {
168/// type Error = &'r str;
169///
170/// fn from_param(param: &'r str) -> Result<Self, Self::Error> {
171/// // We can convert `param` into a `str` since we'll check every
172/// // character for safety later.
173/// let (key, val_str) = match param.find(':') {
174/// Some(i) if i > 0 => (¶m[..i], ¶m[(i + 1)..]),
175/// _ => return Err(param)
176/// };
177///
178/// if !key.chars().all(|c| c.is_ascii_alphabetic()) {
179/// return Err(param);
180/// }
181///
182/// val_str.parse()
183/// .map(|value| MyParam { key, value })
184/// .map_err(|_| param)
185/// }
186/// }
187/// ```
188///
189/// With the implementation, the `MyParam` type can be used as the target of a
190/// dynamic path segment:
191///
192/// ```rust
193/// # #[macro_use] extern crate rocket;
194/// # use rocket::request::FromParam;
195/// # #[allow(dead_code)]
196/// # struct MyParam<'r> { key: &'r str, value: usize }
197/// # impl<'r> FromParam<'r> for MyParam<'r> {
198/// # type Error = &'r str;
199/// # fn from_param(param: &'r str) -> Result<Self, Self::Error> {
200/// # Err(param)
201/// # }
202/// # }
203/// #
204/// #[get("/<key_val>")]
205/// fn hello(key_val: MyParam) -> String {
206/// # let _kv = key_val;
207/// # /*
208/// ...
209/// # */
210/// # "".to_string()
211/// }
212/// # fn main() { }
213/// ```
214pub trait FromParam<'a>: Sized {
215 /// The associated error to be returned if parsing/validation fails.
216 type Error: std::fmt::Debug;
217
218 /// Parses and validates an instance of `Self` from a path parameter string
219 /// or returns an `Error` if parsing or validation fails.
220 fn from_param(param: &'a str) -> Result<Self, Self::Error>;
221}
222
223impl<'a> FromParam<'a> for &'a str {
224 type Error = Empty;
225
226 #[inline(always)]
227 fn from_param(param: &'a str) -> Result<&'a str, Self::Error> {
228 if param.is_empty() {
229 return Err(Empty);
230 }
231
232 Ok(param)
233 }
234}
235
236impl<'a> FromParam<'a> for String {
237 type Error = Empty;
238
239 #[track_caller]
240 #[inline(always)]
241 fn from_param(param: &'a str) -> Result<String, Self::Error> {
242 #[cfg(debug_assertions)] {
243 let location = std::panic::Location::caller();
244 warn!(%location, "`String` as a parameter is inefficient. Use `&str` instead.");
245 }
246
247 if param.is_empty() {
248 return Err(Empty);
249 }
250
251 Ok(param.to_string())
252 }
253}
254
255macro_rules! impl_with_fromstr {
256 ($($T:ty),+) => ($(
257 impl<'a> FromParam<'a> for $T {
258 type Error = <$T as FromStr>::Err;
259
260 #[inline(always)]
261 fn from_param(param: &'a str) -> Result<Self, Self::Error> {
262 <$T as FromStr>::from_str(param)
263 }
264 }
265 )+)
266}
267
268use std::num::{
269 NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize,
270 NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
271};
272use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr};
273
274impl_with_fromstr! {
275 i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64,
276 NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize,
277 NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
278 bool, IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr
279}
280
281impl<'a> FromParam<'a> for PathBuf {
282 type Error = PathError;
283
284 #[inline]
285 fn from_param(param: &'a str) -> Result<Self, Self::Error> {
286 use crate::http::private::Indexed;
287
288 let segments = &[Indexed::Indexed(0, param.len())];
289 Segments::new(param.into(), segments).to_path_buf(false)
290 }
291}
292
293impl<'a, T: FromParam<'a>> FromParam<'a> for Result<T, T::Error> {
294 type Error = std::convert::Infallible;
295
296 #[inline]
297 fn from_param(param: &'a str) -> Result<Self, Self::Error> {
298 match T::from_param(param) {
299 Ok(val) => Ok(Ok(val)),
300 Err(e) => Ok(Err(e)),
301 }
302 }
303}
304
305impl<'a, T: FromParam<'a>> FromParam<'a> for Option<T> {
306 type Error = std::convert::Infallible;
307
308 #[inline]
309 fn from_param(param: &'a str) -> Result<Self, Self::Error> {
310 match T::from_param(param) {
311 Ok(val) => Ok(Some(val)),
312 Err(_) => Ok(None)
313 }
314 }
315}
316
317/// Trait to convert _many_ dynamic path segment strings to a concrete value.
318///
319/// This is the `..` analog to [`FromParam`], and its functionality is identical
320/// to it with one exception: this trait applies to segment parameters of the
321/// form `<param..>`, where `param` is of some type `T` that implements
322/// `FromSegments`. `T::from_segments` is called to convert the matched segments
323/// (via the [`Segments`] iterator) into the implementing type.
324///
325/// # Provided Implementations
326///
327/// **`PathBuf`**
328///
329/// The `PathBuf` implementation constructs a path from the segments iterator.
330/// Each segment is percent-decoded. If a segment equals ".." before or after
331/// decoding, the previous segment (if any) is omitted. For security purposes,
332/// any other segments that begin with "*" or "." are ignored. If a
333/// percent-decoded segment results in invalid UTF8, an `Err` is returned with
334/// the `Utf8Error`.
335pub trait FromSegments<'r>: Sized {
336 /// The associated error to be returned when parsing fails.
337 type Error: std::fmt::Debug;
338
339 /// Parses an instance of `Self` from many dynamic path parameter strings or
340 /// returns an `Error` if one cannot be parsed.
341 fn from_segments(segments: Segments<'r, Path>) -> Result<Self, Self::Error>;
342}
343
344impl<'r> FromSegments<'r> for Segments<'r, Path> {
345 type Error = std::convert::Infallible;
346
347 #[inline(always)]
348 fn from_segments(segments: Self) -> Result<Self, Self::Error> {
349 Ok(segments)
350 }
351}
352
353/// Creates a `PathBuf` from a `Segments` iterator. The returned `PathBuf` is
354/// percent-decoded. If a segment is equal to "..", the previous segment (if
355/// any) is skipped.
356///
357/// For security purposes, if a segment meets any of the following conditions,
358/// an `Err` is returned indicating the condition met:
359///
360/// * Decoded segment starts with any of: `.` (except `..`), `*`
361/// * Decoded segment ends with any of: `:`, `>`, `<`
362/// * Decoded segment contains any of: `/`
363/// * On Windows, decoded segment contains any of: `\`
364/// * Percent-encoding results in invalid UTF8.
365///
366/// As a result of these conditions, a `PathBuf` derived via `FromSegments` is
367/// safe to interpolate within, or use as a suffix of, a path without additional
368/// checks.
369impl FromSegments<'_> for PathBuf {
370 type Error = PathError;
371
372 fn from_segments(segments: Segments<'_, Path>) -> Result<Self, Self::Error> {
373 segments.to_path_buf(false)
374 }
375}
376
377impl<'r, T: FromSegments<'r>> FromSegments<'r> for Result<T, T::Error> {
378 type Error = std::convert::Infallible;
379
380 #[inline]
381 fn from_segments(segments: Segments<'r, Path>) -> Result<Result<T, T::Error>, Self::Error> {
382 match T::from_segments(segments) {
383 Ok(val) => Ok(Ok(val)),
384 Err(e) => Ok(Err(e)),
385 }
386 }
387}
388
389impl<'r, T: FromSegments<'r>> FromSegments<'r> for Option<T> {
390 type Error = std::convert::Infallible;
391
392 #[inline]
393 fn from_segments(segments: Segments<'r, Path>) -> Result<Option<T>, Self::Error> {
394 match T::from_segments(segments) {
395 Ok(val) => Ok(Some(val)),
396 Err(_) => Ok(None)
397 }
398 }
399}
400
401/// Implements `FromParam` for `Either<A, B>`, where `A` and `B` both implement
402/// `FromParam`. If `A::from_param` returns `Ok(a)`, `Either::Left(a)` is
403/// returned. If `B::from_param` returns `Ok(b)`, `Either::Right(b)` is
404/// returned. If both `A::from_param` and `B::from_param` return `Err(a)` and
405/// `Err(b)`, respectively, then `Err((a, b))` is returned.
406impl<'v, A: FromParam<'v>, B: FromParam<'v>> FromParam<'v> for Either<A, B> {
407 type Error = (A::Error, B::Error);
408
409 #[inline(always)]
410 fn from_param(param: &'v str) -> Result<Self, Self::Error> {
411 match A::from_param(param) {
412 Ok(a) => Ok(Either::Left(a)),
413 Err(a) => match B::from_param(param) {
414 Ok(b) => Ok(Either::Right(b)),
415 Err(b) => Err((a, b)),
416 }
417 }
418 }
419}