multer/
size_limit.rs

1use std::collections::HashMap;
2
3use crate::constants;
4
5/// Represents size limit of the stream to prevent DoS attacks.
6///
7/// Please refer [`Constraints`](crate::Constraints) for more info.
8#[derive(Debug)]
9pub struct SizeLimit {
10    pub(crate) whole_stream: u64,
11    pub(crate) per_field: u64,
12    pub(crate) field_map: HashMap<String, u64>,
13}
14
15impl SizeLimit {
16    /// Creates a default size limit which is [`u64::MAX`] for the whole stream
17    /// and for each field.
18    pub fn new() -> SizeLimit {
19        SizeLimit::default()
20    }
21
22    /// Sets size limit for the whole stream.
23    pub fn whole_stream(mut self, limit: u64) -> SizeLimit {
24        self.whole_stream = limit;
25        self
26    }
27
28    /// Sets size limit for each field.
29    pub fn per_field(mut self, limit: u64) -> SizeLimit {
30        self.per_field = limit;
31        self
32    }
33
34    /// Sets size limit for a specific field, it overrides the
35    /// [`per_field`](Self::per_field) value for this field.
36    ///
37    /// It is useful when you want to set a size limit on a textual field which
38    /// will be stored in memory to avoid potential DoS attacks from
39    /// attackers running the server out of memory.
40    pub fn for_field<N: Into<String>>(mut self, field_name: N, limit: u64) -> SizeLimit {
41        self.field_map.insert(field_name.into(), limit);
42        self
43    }
44
45    pub(crate) fn extract_size_limit_for(&self, field: Option<&str>) -> u64 {
46        field
47            .and_then(|field| self.field_map.get(&field.to_owned()))
48            .copied()
49            .unwrap_or(self.per_field)
50    }
51}
52
53impl Default for SizeLimit {
54    fn default() -> Self {
55        SizeLimit {
56            whole_stream: constants::DEFAULT_WHOLE_STREAM_SIZE_LIMIT,
57            per_field: constants::DEFAULT_PER_FIELD_SIZE_LIMIT,
58            field_map: HashMap::default(),
59        }
60    }
61}