multipart_2021/server/
iron.rs

1//! Integration with the [Iron](https://github.com/iron/iron) framework, enabled with the `iron` feature (optional). Includes a `BeforeMiddleware` implementation.
2//!
3//! Not shown here: `impl `[`HttpRequest`](../trait.HttpRequest.html#implementors)` for
4//! iron::Request`.
5
6use iron::headers::ContentType;
7use iron::mime::{Mime, TopLevel, SubLevel};
8use iron::request::{Body as IronBody, Request as IronRequest};
9use iron::typemap::Key;
10use iron::{BeforeMiddleware, IronError, IronResult};
11
12use std::path::PathBuf;
13use std::{error, fmt, io};
14use tempfile;
15
16use super::{FieldHeaders, HttpRequest, Multipart};
17use super::save::{Entries, PartialReason, TempDir};
18use super::save::SaveResult::*;
19
20impl<'r, 'a, 'b> HttpRequest for &'r mut IronRequest<'a, 'b> {
21    type Body = &'r mut IronBody<'a, 'b>;
22
23    fn multipart_boundary(&self) -> Option<&str> {
24        let content_type = try_opt!(self.headers.get::<ContentType>());
25        if let Mime(TopLevel::Multipart, SubLevel::FormData, _) = **content_type {
26            content_type.get_param("boundary").map(|b| b.as_str())
27        } else {
28            None
29        }
30    }
31
32    fn body(self) -> &'r mut IronBody<'a, 'b> {
33        &mut self.body
34    }
35}
36
37/// The default file size limit for [`Intercept`](struct.Intercept.html), in bytes.
38pub const DEFAULT_FILE_SIZE_LIMIT: u64 = 2 * 1024 * 1024;
39
40/// The default file count limit for [`Intercept`](struct.Intercept.html).
41pub const DEFAULT_FILE_COUNT_LIMIT: u32 = 16;
42
43/// A `BeforeMiddleware` for Iron which will intercept and read-out multipart requests and store
44/// the result in the request.
45///
46/// Successful reads will be placed in the `extensions: TypeMap` field of `iron::Request` as an
47/// [`Entries`](../struct.Entries.html) instance (as both key-type and value):
48///
49/// ```no_run
50/// extern crate iron;
51/// extern crate multipart;
52///
53/// use iron::prelude::*;
54///
55/// use multipart::server::Entries;
56/// use multipart::server::iron::Intercept;
57///
58/// fn main() {
59///     let mut chain = Chain::new(|req: &mut Request| if let Some(entries) =
60///         req.extensions.get::<Entries>() {
61///
62///         Ok(Response::with(format!("{:?}", entries)))
63///     } else {
64///         Ok(Response::with("Not a multipart request"))
65///     });
66///
67///     chain.link_before(Intercept::default());
68///
69///     Iron::new(chain).http("localhost:80").unwrap();
70/// }
71/// ```
72///
73/// Any errors during which occur during reading will be passed on as `IronError`.
74#[derive(Debug)]
75pub struct Intercept {
76    /// The parent directory for all temporary directories created by this middleware.
77    /// Will be created if it doesn't exist (lazy).
78    ///
79    /// If omitted, uses the OS temporary directory.
80    ///
81    /// Default value: `None`.
82    pub temp_dir_path: Option<PathBuf>,
83    /// The size limit of uploaded files, in bytes.
84    ///
85    /// Files which exceed this size will be rejected.
86    /// See the `limit_behavior` field for more info.
87    ///
88    /// Default value: [`DEFAULT_FILE_SIZE_LIMIT`](constant.default_file_size_limit.html)
89    pub file_size_limit: u64,
90    /// The limit on the number of files which will be saved from
91    /// the request. Requests which exceed this count will be rejected.
92    ///
93    /// Default value: [`DEFAULT_FILE_COUNT_LIMT`](constant.default_file_count_limit.html)
94    pub file_count_limit: u32,
95    /// What to do when a file count or size limit has been exceeded.
96    ///
97    /// See [`LimitBehavior`](enum.limitbehavior.html) for more info.
98    pub limit_behavior: LimitBehavior,
99}
100
101impl Intercept {
102    /// Set the `temp_dir_path` for this middleware.
103    pub fn temp_dir_path<P: Into<PathBuf>>(self, path: P) -> Self {
104        Intercept { temp_dir_path: Some(path.into()), .. self }
105    }
106
107    /// Set the `file_size_limit` for this middleware.
108    pub fn file_size_limit(self, limit: u64) -> Self {
109        Intercept { file_size_limit: limit, .. self }
110    }
111
112    /// Set the `file_count_limit` for this middleware.
113    pub fn file_count_limit(self, limit: u32) -> Self {
114        Intercept { file_count_limit: limit, .. self }
115    }
116
117    /// Set the `limit_behavior` for this middleware.
118    pub fn limit_behavior(self, behavior: LimitBehavior) -> Self {
119        Intercept { limit_behavior: behavior, .. self }
120    }
121
122    fn read_request(&self, req: &mut IronRequest) -> IronResult<Option<Entries>> {
123        let multipart = match Multipart::from_request(req) {
124            Ok(multipart) => multipart,
125            Err(_) => return Ok(None),
126        };
127
128        let tempdir = self.temp_dir_path.as_ref()
129                .map_or_else(
130                    || tempfile::Builder::new().prefix("multipart-iron").tempdir(),
131                    |path| tempfile::Builder::new().prefix("multipart-iron").tempdir_in(path)
132                )
133                .map_err(|e| io_to_iron(e, "Error opening temporary directory for request."))?;
134
135        match self.limit_behavior {
136            LimitBehavior::ThrowError => self.read_request_strict(multipart, tempdir),
137            LimitBehavior::Continue => self.read_request_lenient(multipart, tempdir),
138        }
139    }
140
141    fn read_request_strict(&self, mut multipart: IronMultipart, tempdir: TempDir) -> IronResult<Option<Entries>> {
142        match multipart.save().size_limit(self.file_size_limit)
143                              .count_limit(self.file_count_limit)
144                              .with_temp_dir(tempdir) {
145            Full(entries) => Ok(Some(entries)),
146            Partial(_, PartialReason::Utf8Error(_)) => unreachable!(),
147            Partial(_, PartialReason::IoError(err)) => Err(io_to_iron(err, "Error midway through request")),
148            Partial(_, PartialReason::CountLimit) => Err(FileCountLimitError(self.file_count_limit).into()),
149            Partial(partial, PartialReason::SizeLimit) =>  {
150                let partial = partial.partial.expect(EXPECT_PARTIAL_FILE);
151                Err(
152                    FileSizeLimitError {
153                        field: partial.source.headers,
154                    }.into()
155                )
156            },
157            Error(err) => Err(io_to_iron(err, "Error at start of request")),
158        }
159    }
160
161    fn read_request_lenient(&self, mut multipart: IronMultipart, tempdir: TempDir) -> IronResult<Option<Entries>> {
162        let mut entries = match multipart.save().size_limit(self.file_size_limit)
163                                                .count_limit(self.file_count_limit)
164                                                .with_temp_dir(tempdir) {
165            Full(entries) => return Ok(Some(entries)),
166            Partial(_, PartialReason::IoError(err)) => return Err(io_to_iron(err, "Error midway through request")),
167            Partial(partial, _) =>  partial.keep_partial(),
168            Error(err) => return Err(io_to_iron(err, "Error at start of request")),
169        };
170
171        loop {
172            entries = match multipart.save().size_limit(self.file_size_limit)
173                                            .count_limit(self.file_count_limit)
174                                            .with_entries(entries) {
175                Full(entries) => return Ok(Some(entries)),
176                Partial(_, PartialReason::IoError(err)) => return Err(io_to_iron(err, "Error midway through request")),
177                Partial(partial, _) => partial.keep_partial(),
178                Error(err) => return Err(io_to_iron(err, "Error at start of request")),
179            };
180        }
181    }
182}
183
184type IronMultipart<'r, 'a, 'b> = Multipart<&'r mut IronBody<'a, 'b>>;
185
186const EXPECT_PARTIAL_FILE: &str = "File size limit hit but the offending \
187                                   file was not available; this is a bug.";
188
189impl Default for Intercept {
190    fn default() -> Self {
191        Intercept {
192            temp_dir_path: None,
193            file_size_limit: DEFAULT_FILE_SIZE_LIMIT,
194            file_count_limit: DEFAULT_FILE_COUNT_LIMIT,
195            limit_behavior: LimitBehavior::ThrowError,
196        }
197    }
198}
199
200impl BeforeMiddleware for Intercept {
201    fn before(&self, req: &mut IronRequest) -> IronResult<()> {
202        self.read_request(req)?
203            .map(|entries| req.extensions.insert::<Entries>(entries));
204
205        Ok(())
206    }
207}
208
209impl Key for Entries {
210    type Value = Self;
211}
212
213/// The behavior of `Intercept` when a file size or count limit is exceeded.
214#[derive(Clone, Copy, Debug)]
215#[repr(u32)]
216pub enum LimitBehavior {
217    /// Return an error from the middleware describing the issue.
218    ThrowError,
219    /// Ignore the limit.
220    ///
221    /// In the case of file size limits, the offending file will be truncated
222    /// in the result.
223    ///
224    /// In the case of file count limits, the request will be completed.
225    Continue,
226}
227
228/// An error returned from `Intercept` when the size limit
229/// for an individual file is exceeded.
230#[derive(Debug)]
231pub struct FileSizeLimitError {
232    /// The field where the error occurred.
233    pub field: FieldHeaders,
234}
235
236impl error::Error for FileSizeLimitError {
237    fn description(&self) -> &str {
238        "file size limit reached"
239    }
240}
241
242impl fmt::Display for FileSizeLimitError {
243    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244        match self.field.filename {
245            Some(ref filename) => write!(f, "File size limit reached for field \"{}\" (filename: \"{}\")", self.field.name, filename),
246            None => write!(f, "File size limit reached for field \"{}\" (no filename)", self.field.name),
247        }
248    }
249}
250
251impl Into<IronError> for FileSizeLimitError {
252    fn into(self) -> IronError {
253        let desc_str = self.to_string();
254        IronError::new(self, desc_str)
255    }
256}
257
258/// An error returned from `Intercept` when the file count limit
259/// for a single request was exceeded.
260#[derive(Debug)]
261pub struct FileCountLimitError(u32);
262
263impl error::Error for FileCountLimitError {
264    fn description(&self) -> &str {
265        "file count limit reached"
266    }
267}
268
269impl fmt::Display for FileCountLimitError {
270    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271        write!(f, "File count limit reached for request. Limit: {}", self.0)
272    }
273}
274
275impl Into<IronError> for FileCountLimitError {
276    fn into(self) -> IronError {
277        let desc_string = self.to_string();
278        IronError::new(self, desc_string)
279    }
280}
281
282fn io_to_iron<M: Into<String>>(err: io::Error, msg: M) -> IronError {
283    IronError::new(err, msg.into())
284}