Skip to main content

multipart_any/client/
mod.rs

1// Copyright 2016 `multipart` Crate Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7//! The client-side abstraction for multipart requests. Enabled with the `client` feature.
8//!
9//! Use this when sending POST requests with files to a server.
10use mime::Mime;
11
12use std::borrow::Cow;
13use std::fs::File;
14use std::io;
15use std::io::prelude::*;
16
17use std::path::Path;
18
19#[cfg(feature = "hyper")]
20pub mod hyper;
21
22pub mod lazy;
23
24mod sized;
25
26pub use self::sized::SizedRequest;
27
28const BOUNDARY_LEN: usize = 16;
29
30macro_rules! map_self {
31    ($selff:expr, $try:expr) => (
32        match $try {
33            Ok(_) => Ok($selff),
34            Err(err) => Err(err.into()),
35        }
36    )
37}
38
39/// The entry point of the client-side multipart API.
40///
41/// Though they perform I/O, the `.write_*()` methods do not return `io::Result<_>` in order to
42/// facilitate method chaining. Upon the first error, all subsequent API calls will be no-ops until
43/// `.send()` is called, at which point the error will be reported.
44pub struct Multipart<S> {
45    writer: MultipartWriter<'static, S>,
46}
47
48impl Multipart<()> {
49    /// Create a new `Multipart` to wrap a request.
50    ///
51    /// ## Returns Error
52    /// If `req.open_stream()` returns an error.
53    pub fn from_request<R: HttpRequest>(req: R) -> Result<Multipart<R::Stream>, R::Error> {
54        let (boundary, stream) = open_stream(req, None)?;
55
56        Ok(Multipart {
57            writer: MultipartWriter::new(stream, boundary),
58        })
59    }
60}
61
62impl<S: HttpStream> Multipart<S> { 
63    /// Write a text field to this multipart request.
64    /// `name` and `val` can be either owned `String` or `&str`.
65    ///
66    /// ## Errors
67    /// If something went wrong with the HTTP stream.
68    pub fn write_text<N: AsRef<str>, V: AsRef<str>>(&mut self, name: N, val: V) -> Result<&mut Self, S::Error> {
69        map_self!(self, self.writer.write_text(name.as_ref(), val.as_ref()))
70    }
71    
72    /// Open a file pointed to by `path` and write its contents to the multipart request, 
73    /// supplying its filename and guessing its `Content-Type` from its extension.
74    ///
75    /// If you want to set these values manually, or use another type that implements `Read`, 
76    /// use `.write_stream()`.
77    ///
78    /// `name` can be either `String` or `&str`, and `path` can be `PathBuf` or `&Path`.
79    ///
80    /// ## Errors
81    /// If there was a problem opening the file (was a directory or didn't exist),
82    /// or if something went wrong with the HTTP stream.
83    pub fn write_file<N: AsRef<str>, P: AsRef<Path>>(&mut self, name: N, path: P) -> Result<&mut Self, S::Error> {
84        let name = name.as_ref();
85        let path = path.as_ref();
86
87        map_self!(self, self.writer.write_file(name, path))
88    }
89
90    /// Write a byte stream to the multipart request as a file field, supplying `filename` if given,
91    /// and `content_type` if given or `"application/octet-stream"` if not.
92    ///
93    /// `name` can be either `String` or `&str`, and `read` can take the `Read` by-value or
94    /// with an `&mut` borrow.
95    ///
96    /// ## Warning
97    /// The given `Read` **must** be able to read to EOF (end of file/no more data), meaning
98    /// `Read::read()` returns `Ok(0)`. If it never returns EOF it will be read to infinity 
99    /// and the request will never be completed.
100    ///
101    /// When using `SizedRequest` this also can cause out-of-control memory usage as the
102    /// multipart data has to be written to an in-memory buffer so its size can be calculated.
103    ///
104    /// Use `Read::take()` if you wish to send data from a `Read` 
105    /// that will never return EOF otherwise.
106    ///
107    /// ## Errors
108    /// If the reader returned an error, or if something went wrong with the HTTP stream.
109    // RFC: How to format this declaration?
110    pub fn write_stream<N: AsRef<str>, St: Read>(
111        &mut self, name: N, stream: &mut St, filename: Option<&str>, content_type: Option<Mime>
112    ) -> Result<&mut Self, S::Error> {
113        let name = name.as_ref();
114
115        map_self!(self, self.writer.write_stream(stream, name, filename, content_type))
116    } 
117
118    /// Finalize the request and return the response from the server, or the last error if set.
119    pub fn send(self) -> Result<S::Response, S::Error> {
120        self.writer.finish().map_err(io::Error::into).and_then(|body| body.finish())
121    }    
122}
123
124impl<R: HttpRequest> Multipart<SizedRequest<R>>
125where <R::Stream as HttpStream>::Error: From<R::Error> {
126    /// Create a new `Multipart` using the `SizedRequest` wrapper around `req`.
127    pub fn from_request_sized(req: R) -> Result<Self, R::Error> {
128        Multipart::from_request(SizedRequest::from_request(req))
129    }
130}
131
132/// A trait describing an HTTP request that can be used to send multipart data.
133pub trait HttpRequest {
134    /// The HTTP stream type that can be opend by this request, to which the multipart data will be
135    /// written.
136    type Stream: HttpStream;
137    /// The error type for this request. 
138    /// Must be compatible with `io::Error` as well as `Self::HttpStream::Error`
139    type Error: From<io::Error> + Into<<Self::Stream as HttpStream>::Error>;
140
141    /// Set the `Content-Type` header to `multipart/form-data` and supply the `boundary` value.
142    /// If `content_len` is given, set the `Content-Length` header to its value.
143    /// 
144    /// Return `true` if any and all sanity checks passed and the stream is ready to be opened, 
145    /// or `false` otherwise.
146    fn apply_headers(&mut self, boundary: &str, content_len: Option<u64>) -> bool;
147
148    /// Open the request stream and return it or any error otherwise. 
149    fn open_stream(self) -> Result<Self::Stream, Self::Error>;
150}
151
152/// A trait describing an open HTTP stream that can be written to.
153pub trait HttpStream: Write {
154    /// The request type that opened this stream.
155    type Request: HttpRequest;
156    /// The response type that will be returned after the request is completed.
157    type Response;
158    /// The error type for this stream.
159    /// Must be compatible with `io::Error` as well as `Self::Request::Error`.
160    type Error: From<io::Error> + From<<Self::Request as HttpRequest>::Error>; 
161
162    /// Finalize and close the stream and return the response object, or any error otherwise.
163    fn finish(self) -> Result<Self::Response, Self::Error>;
164}
165
166impl HttpRequest for () {
167    type Stream = io::Sink;
168    type Error = io::Error;
169
170    fn apply_headers(&mut self, _: &str, _: Option<u64>) -> bool { true }
171    fn open_stream(self) -> Result<Self::Stream, Self::Error> { Ok(io::sink()) }
172}
173
174impl HttpStream for io::Sink {
175    type Request = ();
176    type Response = ();
177    type Error = io::Error;
178
179    fn finish(self) -> Result<Self::Response, Self::Error> { Ok(()) }
180}
181
182fn gen_boundary() -> String {
183    ::random_alphanumeric(BOUNDARY_LEN)
184}
185
186fn open_stream<R: HttpRequest>(mut req: R, content_len: Option<u64>) -> Result<(String, R::Stream), R::Error> {
187    let boundary = gen_boundary();
188    req.apply_headers(&boundary, content_len);
189    req.open_stream().map(|stream| (boundary, stream))
190}
191
192struct MultipartWriter<'a, W> {
193    inner: W,
194    boundary: Cow<'a, str>,
195    data_written: bool,
196}
197
198impl<'a, W: Write> MultipartWriter<'a, W> {
199    fn new<B: Into<Cow<'a, str>>>(inner: W, boundary: B) -> Self {
200        MultipartWriter {
201            inner,
202            boundary: boundary.into(),
203            data_written: false,
204        }
205    }
206
207    fn write_boundary(&mut self) -> io::Result<()> {
208        if self.data_written {
209            self.inner.write_all(b"\r\n")?;
210        }
211
212        write!(self.inner, "--{}\r\n", self.boundary)
213    }
214
215    fn write_text(&mut self, name: &str, text: &str) -> io::Result<()> {
216        chain_result! {
217            self.write_field_headers(name, None, None),
218            self.inner.write_all(text.as_bytes())
219        }
220    }
221
222    fn write_file(&mut self, name: &str, path: &Path) -> io::Result<()> {
223        let (content_type, filename) = mime_filename(path);
224        let mut file = File::open(path)?;
225        self.write_stream(&mut file, name, filename, Some(content_type))
226    }
227
228    fn write_stream<S: Read>(&mut self, stream: &mut S, name: &str, filename: Option<&str>, content_type: Option<Mime>) -> io::Result<()> {
229        // This is necessary to make sure it is interpreted as a file on the server end.
230        let content_type = Some(content_type.unwrap_or(mime::APPLICATION_OCTET_STREAM));
231
232        chain_result! {
233            self.write_field_headers(name, filename, content_type),
234            io::copy(stream, &mut self.inner),
235            Ok(()) 
236        }
237    }
238
239    fn write_field_headers(&mut self, name: &str, filename: Option<&str>, content_type: Option<Mime>) 
240    -> io::Result<()> {
241        chain_result! {
242            // Write the first boundary, or the boundary for the previous field.
243            self.write_boundary(),
244            { self.data_written = true; Ok(()) },
245            write!(self.inner, "Content-Disposition: form-data; name=\"{}\"", name),
246            filename.map(|filename| write!(self.inner, "; filename=\"{}\"", filename))
247                .unwrap_or(Ok(())),
248            content_type.map(|content_type| write!(self.inner, "\r\nContent-Type: {}", content_type))
249                .unwrap_or(Ok(())),
250            self.inner.write_all(b"\r\n\r\n")
251        }
252    }
253
254    fn finish(mut self) -> io::Result<W> {
255        if self.data_written {
256            self.inner.write_all(b"\r\n")?;
257        }
258
259        // always write the closing boundary, even for empty bodies
260        // trailing CRLF is optional but Actix requires it due to a naive implementation:
261        // https://github.com/actix/actix-web/issues/598
262        write!(self.inner, "--{}--\r\n", self.boundary)?;
263        Ok(self.inner)
264    }
265}
266
267fn mime_filename(path: &Path) -> (Mime, Option<&str>) {
268    let content_type = ::mime_guess::from_path(path).first_or_octet_stream();
269    let filename = opt_filename(path);
270    (content_type, filename)
271}
272
273fn opt_filename(path: &Path) -> Option<&str> {
274    path.file_name().and_then(|filename| filename.to_str())
275}