1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//!Anything related to reading the request body.

#[cfg(feature = "multipart")]
use multipart::server::{HttpRequest, Multipart};

use std::io::{self, Read};

use hyper::buffer::BufReader;
use hyper::http::h1::HttpReader;
use hyper::net::NetworkStream;

use context::Parameters;
use header::Headers;

///A reader for a request body.
pub struct BodyReader<'a, 'b: 'a> {
    reader: MaybeMock<HttpReader<&'a mut BufReader<&'b mut NetworkStream>>>,

    #[cfg(feature = "multipart")]
    multipart_boundary: Option<String>
}

impl<'a, 'b> BodyReader<'a, 'b> {
    #[doc(hidden)]
    #[cfg(feature = "multipart")]
    ///Internal and may change without warning.
    pub fn from_reader(reader: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>, headers: &Headers) -> BodyReader<'a, 'b> {
        use header::ContentType;
        use mime::{Mime, TopLevel, SubLevel, Attr, Value};

        let boundary = match headers.get() {
            Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, ref attrs))) => {
                attrs.iter()
                    .find(|&&(ref attr, _)| attr == &Attr::Boundary)
                    .and_then(|&(_, ref val)| if let Value::Ext(ref boundary) = *val {
                        Some(boundary.clone())
                    } else {
                        None
                    })
            },
            _ => None
        };

        BodyReader {
            reader: MaybeMock::Actual(reader),
            multipart_boundary: boundary
        }
    }

    #[doc(hidden)]
    #[cfg(not(feature = "multipart"))]
    ///Internal and may change without warning.
    pub fn from_reader(reader: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>, _headers: &Headers) -> BodyReader<'a, 'b> {
        BodyReader {
            reader: MaybeMock::Actual(reader)
        }
    }

    ///Create a non-functional body reader for testing purposes.
    #[cfg(feature = "multipart")]
    pub fn mock(headers: &'b Headers) -> BodyReader<'static, 'static> {
        use header::ContentType;
        use mime::{Mime, TopLevel, SubLevel, Attr, Value};

        let boundary = match headers.get() {
            Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, ref attrs))) => {
                attrs.iter()
                    .find(|&&(ref attr, _)| attr == &Attr::Boundary)
                    .and_then(|&(_, ref val)| if let Value::Ext(ref boundary) = *val {
                        Some(boundary.clone())
                    } else {
                        None
                    })
            },
            _ => None
        };

        BodyReader {
            reader: MaybeMock::Mock,
            multipart_boundary: boundary,
        }
    }

    ///Create a non-functional body reader for testing purposes.
    #[cfg(not(feature = "multipart"))]
    pub fn mock(_headers: &'b Headers) -> BodyReader<'static, 'static> {
        BodyReader {
            reader: MaybeMock::Mock
        }
    }
}

impl<'a, 'b> BodyReader<'a, 'b> {
    ///Try to create a `multipart/form-data` reader from the request body.
    ///
    ///```
    ///# extern crate rustful;
    ///# extern crate mime;
    ///# extern crate multipart;
    ///use std::fmt::Write;
    ///use std::io::Read;
    ///use rustful::{Context, Response};
    ///use rustful::StatusCode::BadRequest;
    ///use multipart::server::MultipartData;
    ///
    ///fn my_handler(mut context: Context, mut response: Response) {
    ///    if let Some(mut multipart) = context.body.as_multipart() {
    ///        let mut result = String::new();
    ///
    ///        //Iterate over the multipart entries and print info about them in `result`
    ///        multipart.foreach_entry(|mut entry| {
    ///            if let Some(content_mime) = entry.headers.content_type {
    ///                if content_mime.type_() == mime::TEXT {
    ///                    //Found data from a text field
    ///                    let mut text = String::new();
    ///                    entry.data.read_to_string(&mut text);
    ///                    writeln!(&mut result, "{}: '{}'", entry.headers.name, text);
    ///                }
    ///                else {
    ///                    //Found an uploaded file
    ///                    if let Some(file_name) = entry.headers.filename {
    ///                        writeln!(&mut result, "{}: a file called '{}'", entry.headers.name, file_name);
    ///                    } else {
    ///                        writeln!(&mut result, "{}: a nameless file", entry.headers.name);
    ///                    }
    ///                }
    ///             }
    ///             else {
    ///                 //Content-type not supplied, default to text/plain as per IETF RFC 7578, section 4.4
    ///                 let mut text = String::new();
    ///                 entry.data.read_to_string(&mut text);
    ///                 writeln!(&mut result, "{}: '{}'", entry.headers.name, text);
    ///             }
    ///        });
    ///
    ///        response.send(result);
    ///    } else {
    ///        //We expected it to be a valid `multipart/form-data` request, but it was not
    ///        response.set_status(BadRequest);
    ///    }
    ///}
    ///# fn main() {}
    ///```
    #[cfg(feature = "multipart")]
    pub fn as_multipart<'r>(&'r mut self) -> Option<Multipart<MultipartRequest<'r, 'a, 'b>>> {
        if let MaybeMock::Actual(ref mut reader) = self.reader {
            self.multipart_boundary.as_ref().and_then(move |boundary|
                Multipart::from_request(MultipartRequest {
                    boundary: boundary,
                    reader: reader
                }).ok()
            )
        } else {
            None
        }
    }

    ///Read and parse the request body as a query string. The body will be
    ///decoded as UTF-8 and plain '+' characters will be replaced with spaces.
    ///
    ///A simplified example of how to parse `a=number&b=number`:
    ///
    ///```
    ///use rustful::{Context, Response};
    ///
    ///fn my_handler(mut context: Context, response: Response) {
    ///    //Parse the request body as a query string
    ///    let query = context.body.read_query_body().unwrap();
    ///
    ///    //Find "a" and "b" and assume that they are numbers
    ///    let a: f64 = query.get("a").and_then(|number| number.parse().ok()).unwrap();
    ///    let b: f64 = query.get("b").and_then(|number| number.parse().ok()).unwrap();
    ///
    ///    response.send(format!("{} + {} = {}", a, b, a + b));
    ///}
    ///```
    #[inline]
    pub fn read_query_body(&mut self) -> io::Result<Parameters> {
        let mut buf = Vec::new();
        try!(self.read_to_end(&mut buf));
        Ok(::utils::parse_parameters(&buf))
    }

    }

impl<'a, 'b> Read for BodyReader<'a, 'b> {
    ///Read the request body.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

///A specialized request representation for the multipart interface.
#[cfg(feature = "multipart")]
pub struct MultipartRequest<'r, 'a: 'r, 'b: 'a> {
    boundary: &'r str,
    reader: &'r mut HttpReader<&'a mut BufReader<&'b mut NetworkStream>>
}

#[cfg(feature = "multipart")]
impl<'r, 'a, 'b> HttpRequest for MultipartRequest<'r, 'a, 'b> {
    type Body = Self;

    fn body(self) -> Self {
        self
    }

    fn multipart_boundary(&self) -> Option<&str> {
        Some(self.boundary)
    }
}

#[cfg(feature = "multipart")]
impl<'r, 'a, 'b> Read for MultipartRequest<'r, 'a, 'b> {
    ///Read the request body.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

enum MaybeMock<R: Read> {
    Actual(R),
    Mock
}

impl<R: Read> Read for MaybeMock<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let &mut MaybeMock::Actual(ref mut reader) = self {
            reader.read(buf)
        } else {
            Ok(0)
        }
    }
}