1 use std::cell::RefCell;
2 use std::ffi::{CStr, CString};
3 use std::fmt;
4 use std::io::{self, SeekFrom, Write};
5 use std::path::Path;
6 use std::slice;
7 use std::str;
8 use std::time::Duration;
9 
10 use curl_sys;
11 use libc::{self, c_char, c_double, c_int, c_long, c_ulong, c_void, size_t};
12 use socket2::Socket;
13 
14 use easy::form;
15 use easy::list;
16 use easy::windows;
17 use easy::{Form, List};
18 use panic;
19 use Error;
20 
21 /// A trait for the various callbacks used by libcurl to invoke user code.
22 ///
23 /// This trait represents all operations that libcurl can possibly invoke a
24 /// client for code during an HTTP transaction. Each callback has a default
25 /// "noop" implementation, the same as in libcurl. Types implementing this trait
26 /// may simply override the relevant functions to learn about the callbacks
27 /// they're interested in.
28 ///
29 /// # Examples
30 ///
31 /// ```
32 /// use curl::easy::{Easy2, Handler, WriteError};
33 ///
34 /// struct Collector(Vec<u8>);
35 ///
36 /// impl Handler for Collector {
37 ///     fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
38 ///         self.0.extend_from_slice(data);
39 ///         Ok(data.len())
40 ///     }
41 /// }
42 ///
43 /// let mut easy = Easy2::new(Collector(Vec::new()));
44 /// easy.get(true).unwrap();
45 /// easy.url("https://www.rust-lang.org/").unwrap();
46 /// easy.perform().unwrap();
47 ///
48 /// assert_eq!(easy.response_code().unwrap(), 200);
49 /// let contents = easy.get_ref();
50 /// println!("{}", String::from_utf8_lossy(&contents.0));
51 /// ```
52 pub trait Handler {
53     /// Callback invoked whenever curl has downloaded data for the application.
54     ///
55     /// This callback function gets called by libcurl as soon as there is data
56     /// received that needs to be saved.
57     ///
58     /// The callback function will be passed as much data as possible in all
59     /// invokes, but you must not make any assumptions. It may be one byte, it
60     /// may be thousands. If `show_header` is enabled, which makes header data
61     /// get passed to the write callback, you can get up to
62     /// `CURL_MAX_HTTP_HEADER` bytes of header data passed into it.  This
63     /// usually means 100K.
64     ///
65     /// This function may be called with zero bytes data if the transferred file
66     /// is empty.
67     ///
68     /// The callback should return the number of bytes actually taken care of.
69     /// If that amount differs from the amount passed to your callback function,
70     /// it'll signal an error condition to the library. This will cause the
71     /// transfer to get aborted and the libcurl function used will return
72     /// an error with `is_write_error`.
73     ///
74     /// If your callback function returns `Err(WriteError::Pause)` it will cause
75     /// this transfer to become paused. See `unpause_write` for further details.
76     ///
77     /// By default data is sent into the void, and this corresponds to the
78     /// `CURLOPT_WRITEFUNCTION` and `CURLOPT_WRITEDATA` options.
write(&mut self, data: &[u8]) -> Result<usize, WriteError>79     fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
80         Ok(data.len())
81     }
82 
83     /// Read callback for data uploads.
84     ///
85     /// This callback function gets called by libcurl as soon as it needs to
86     /// read data in order to send it to the peer - like if you ask it to upload
87     /// or post data to the server.
88     ///
89     /// Your function must then return the actual number of bytes that it stored
90     /// in that memory area. Returning 0 will signal end-of-file to the library
91     /// and cause it to stop the current transfer.
92     ///
93     /// If you stop the current transfer by returning 0 "pre-maturely" (i.e
94     /// before the server expected it, like when you've said you will upload N
95     /// bytes and you upload less than N bytes), you may experience that the
96     /// server "hangs" waiting for the rest of the data that won't come.
97     ///
98     /// The read callback may return `Err(ReadError::Abort)` to stop the
99     /// current operation immediately, resulting in a `is_aborted_by_callback`
100     /// error code from the transfer.
101     ///
102     /// The callback can return `Err(ReadError::Pause)` to cause reading from
103     /// this connection to pause. See `unpause_read` for further details.
104     ///
105     /// By default data not input, and this corresponds to the
106     /// `CURLOPT_READFUNCTION` and `CURLOPT_READDATA` options.
107     ///
108     /// Note that the lifetime bound on this function is `'static`, but that
109     /// is often too restrictive. To use stack data consider calling the
110     /// `transfer` method and then using `read_function` to configure a
111     /// callback that can reference stack-local data.
read(&mut self, data: &mut [u8]) -> Result<usize, ReadError>112     fn read(&mut self, data: &mut [u8]) -> Result<usize, ReadError> {
113         drop(data);
114         Ok(0)
115     }
116 
117     /// User callback for seeking in input stream.
118     ///
119     /// This function gets called by libcurl to seek to a certain position in
120     /// the input stream and can be used to fast forward a file in a resumed
121     /// upload (instead of reading all uploaded bytes with the normal read
122     /// function/callback). It is also called to rewind a stream when data has
123     /// already been sent to the server and needs to be sent again. This may
124     /// happen when doing a HTTP PUT or POST with a multi-pass authentication
125     /// method, or when an existing HTTP connection is reused too late and the
126     /// server closes the connection.
127     ///
128     /// The callback function must return `SeekResult::Ok` on success,
129     /// `SeekResult::Fail` to cause the upload operation to fail or
130     /// `SeekResult::CantSeek` to indicate that while the seek failed, libcurl
131     /// is free to work around the problem if possible. The latter can sometimes
132     /// be done by instead reading from the input or similar.
133     ///
134     /// By default data this option is not set, and this corresponds to the
135     /// `CURLOPT_SEEKFUNCTION` and `CURLOPT_SEEKDATA` options.
seek(&mut self, whence: SeekFrom) -> SeekResult136     fn seek(&mut self, whence: SeekFrom) -> SeekResult {
137         drop(whence);
138         SeekResult::CantSeek
139     }
140 
141     /// Specify a debug callback
142     ///
143     /// `debug_function` replaces the standard debug function used when
144     /// `verbose` is in effect. This callback receives debug information,
145     /// as specified in the type argument.
146     ///
147     /// By default this option is not set and corresponds to the
148     /// `CURLOPT_DEBUGFUNCTION` and `CURLOPT_DEBUGDATA` options.
debug(&mut self, kind: InfoType, data: &[u8])149     fn debug(&mut self, kind: InfoType, data: &[u8]) {
150         debug(kind, data)
151     }
152 
153     /// Callback that receives header data
154     ///
155     /// This function gets called by libcurl as soon as it has received header
156     /// data. The header callback will be called once for each header and only
157     /// complete header lines are passed on to the callback. Parsing headers is
158     /// very easy using this. If this callback returns `false` it'll signal an
159     /// error to the library. This will cause the transfer to get aborted and
160     /// the libcurl function in progress will return `is_write_error`.
161     ///
162     /// A complete HTTP header that is passed to this function can be up to
163     /// CURL_MAX_HTTP_HEADER (100K) bytes.
164     ///
165     /// It's important to note that the callback will be invoked for the headers
166     /// of all responses received after initiating a request and not just the
167     /// final response. This includes all responses which occur during
168     /// authentication negotiation. If you need to operate on only the headers
169     /// from the final response, you will need to collect headers in the
170     /// callback yourself and use HTTP status lines, for example, to delimit
171     /// response boundaries.
172     ///
173     /// When a server sends a chunked encoded transfer, it may contain a
174     /// trailer. That trailer is identical to a HTTP header and if such a
175     /// trailer is received it is passed to the application using this callback
176     /// as well. There are several ways to detect it being a trailer and not an
177     /// ordinary header: 1) it comes after the response-body. 2) it comes after
178     /// the final header line (CR LF) 3) a Trailer: header among the regular
179     /// response-headers mention what header(s) to expect in the trailer.
180     ///
181     /// For non-HTTP protocols like FTP, POP3, IMAP and SMTP this function will
182     /// get called with the server responses to the commands that libcurl sends.
183     ///
184     /// By default this option is not set and corresponds to the
185     /// `CURLOPT_HEADERFUNCTION` and `CURLOPT_HEADERDATA` options.
header(&mut self, data: &[u8]) -> bool186     fn header(&mut self, data: &[u8]) -> bool {
187         drop(data);
188         true
189     }
190 
191     /// Callback to progress meter function
192     ///
193     /// This function gets called by libcurl instead of its internal equivalent
194     /// with a frequent interval. While data is being transferred it will be
195     /// called very frequently, and during slow periods like when nothing is
196     /// being transferred it can slow down to about one call per second.
197     ///
198     /// The callback gets told how much data libcurl will transfer and has
199     /// transferred, in number of bytes. The first argument is the total number
200     /// of bytes libcurl expects to download in this transfer. The second
201     /// argument is the number of bytes downloaded so far. The third argument is
202     /// the total number of bytes libcurl expects to upload in this transfer.
203     /// The fourth argument is the number of bytes uploaded so far.
204     ///
205     /// Unknown/unused argument values passed to the callback will be set to
206     /// zero (like if you only download data, the upload size will remain 0).
207     /// Many times the callback will be called one or more times first, before
208     /// it knows the data sizes so a program must be made to handle that.
209     ///
210     /// Returning `false` from this callback will cause libcurl to abort the
211     /// transfer and return `is_aborted_by_callback`.
212     ///
213     /// If you transfer data with the multi interface, this function will not be
214     /// called during periods of idleness unless you call the appropriate
215     /// libcurl function that performs transfers.
216     ///
217     /// `progress` must be set to `true` to make this function actually get
218     /// called.
219     ///
220     /// By default this function calls an internal method and corresponds to
221     /// `CURLOPT_PROGRESSFUNCTION` and `CURLOPT_PROGRESSDATA`.
progress(&mut self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) -> bool222     fn progress(&mut self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) -> bool {
223         drop((dltotal, dlnow, ultotal, ulnow));
224         true
225     }
226 
227     /// Callback to SSL context
228     ///
229     /// This callback function gets called by libcurl just before the
230     /// initialization of an SSL connection after having processed all
231     /// other SSL related options to give a last chance to an
232     /// application to modify the behaviour of the SSL
233     /// initialization. The `ssl_ctx` parameter is actually a pointer
234     /// to the SSL library's SSL_CTX. If an error is returned from the
235     /// callback no attempt to establish a connection is made and the
236     /// perform operation will return the callback's error code.
237     ///
238     /// This function will get called on all new connections made to a
239     /// server, during the SSL negotiation. The SSL_CTX pointer will
240     /// be a new one every time.
241     ///
242     /// To use this properly, a non-trivial amount of knowledge of
243     /// your SSL library is necessary. For example, you can use this
244     /// function to call library-specific callbacks to add additional
245     /// validation code for certificates, and even to change the
246     /// actual URI of a HTTPS request.
247     ///
248     /// By default this function calls an internal method and
249     /// corresponds to `CURLOPT_SSL_CTX_FUNCTION` and
250     /// `CURLOPT_SSL_CTX_DATA`.
251     ///
252     /// Note that this callback is not guaranteed to be called, not all versions
253     /// of libcurl support calling this callback.
ssl_ctx(&mut self, cx: *mut c_void) -> Result<(), Error>254     fn ssl_ctx(&mut self, cx: *mut c_void) -> Result<(), Error> {
255         // By default, if we're on an OpenSSL enabled libcurl and we're on
256         // Windows, add the system's certificate store to OpenSSL's certificate
257         // store.
258         ssl_ctx(cx)
259     }
260 
261     /// Callback to open sockets for libcurl.
262     ///
263     /// This callback function gets called by libcurl instead of the socket(2)
264     /// call. The callback function should return the newly created socket
265     /// or `None` in case no connection could be established or another
266     /// error was detected. Any additional `setsockopt(2)` calls can of course
267     /// be done on the socket at the user's discretion. A `None` return
268     /// value from the callback function will signal an unrecoverable error to
269     /// libcurl and it will return `is_couldnt_connect` from the function that
270     /// triggered this callback.
271     ///
272     /// By default this function opens a standard socket and
273     /// corresponds to `CURLOPT_OPENSOCKETFUNCTION `.
open_socket( &mut self, family: c_int, socktype: c_int, protocol: c_int, ) -> Option<curl_sys::curl_socket_t>274     fn open_socket(
275         &mut self,
276         family: c_int,
277         socktype: c_int,
278         protocol: c_int,
279     ) -> Option<curl_sys::curl_socket_t> {
280         // Note that we override this to calling a function in `socket2` to
281         // ensure that we open all sockets with CLOEXEC. Otherwise if we rely on
282         // libcurl to open sockets it won't use CLOEXEC.
283         return Socket::new(family.into(), socktype.into(), Some(protocol.into()))
284             .ok()
285             .map(cvt);
286 
287         #[cfg(unix)]
288         fn cvt(socket: Socket) -> curl_sys::curl_socket_t {
289             use std::os::unix::prelude::*;
290             socket.into_raw_fd()
291         }
292 
293         #[cfg(windows)]
294         fn cvt(socket: Socket) -> curl_sys::curl_socket_t {
295             use std::os::windows::prelude::*;
296             socket.into_raw_socket()
297         }
298     }
299 }
300 
debug(kind: InfoType, data: &[u8])301 pub fn debug(kind: InfoType, data: &[u8]) {
302     let out = io::stderr();
303     let prefix = match kind {
304         InfoType::Text => "*",
305         InfoType::HeaderIn => "<",
306         InfoType::HeaderOut => ">",
307         InfoType::DataIn | InfoType::SslDataIn => "{",
308         InfoType::DataOut | InfoType::SslDataOut => "}",
309         InfoType::__Nonexhaustive => " ",
310     };
311     let mut out = out.lock();
312     drop(write!(out, "{} ", prefix));
313     match str::from_utf8(data) {
314         Ok(s) => drop(out.write_all(s.as_bytes())),
315         Err(_) => drop(write!(out, "({} bytes of data)\n", data.len())),
316     }
317 }
318 
ssl_ctx(cx: *mut c_void) -> Result<(), Error>319 pub fn ssl_ctx(cx: *mut c_void) -> Result<(), Error> {
320     windows::add_certs_to_context(cx);
321     Ok(())
322 }
323 
324 /// Raw bindings to a libcurl "easy session".
325 ///
326 /// This type corresponds to the `CURL` type in libcurl, and is probably what
327 /// you want for just sending off a simple HTTP request and fetching a response.
328 /// Each easy handle can be thought of as a large builder before calling the
329 /// final `perform` function.
330 ///
331 /// There are many many configuration options for each `Easy2` handle, and they
332 /// should all have their own documentation indicating what it affects and how
333 /// it interacts with other options. Some implementations of libcurl can use
334 /// this handle to interact with many different protocols, although by default
335 /// this crate only guarantees the HTTP/HTTPS protocols working.
336 ///
337 /// Note that almost all methods on this structure which configure various
338 /// properties return a `Result`. This is largely used to detect whether the
339 /// underlying implementation of libcurl actually implements the option being
340 /// requested. If you're linked to a version of libcurl which doesn't support
341 /// the option, then an error will be returned. Some options also perform some
342 /// validation when they're set, and the error is returned through this vector.
343 ///
344 /// Note that historically this library contained an `Easy` handle so this one's
345 /// called `Easy2`. The major difference between the `Easy` type is that an
346 /// `Easy2` structure uses a trait instead of closures for all of the callbacks
347 /// that curl can invoke. The `Easy` type is actually built on top of this
348 /// `Easy` type, and this `Easy2` type can be more flexible in some situations
349 /// due to the generic parameter.
350 ///
351 /// There's not necessarily a right answer for which type is correct to use, but
352 /// as a general rule of thumb `Easy` is typically a reasonable choice for
353 /// synchronous I/O and `Easy2` is a good choice for asynchronous I/O.
354 ///
355 /// # Examples
356 ///
357 /// ```
358 /// use curl::easy::{Easy2, Handler, WriteError};
359 ///
360 /// struct Collector(Vec<u8>);
361 ///
362 /// impl Handler for Collector {
363 ///     fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
364 ///         self.0.extend_from_slice(data);
365 ///         Ok(data.len())
366 ///     }
367 /// }
368 ///
369 /// let mut easy = Easy2::new(Collector(Vec::new()));
370 /// easy.get(true).unwrap();
371 /// easy.url("https://www.rust-lang.org/").unwrap();
372 /// easy.perform().unwrap();
373 ///
374 /// assert_eq!(easy.response_code().unwrap(), 200);
375 /// let contents = easy.get_ref();
376 /// println!("{}", String::from_utf8_lossy(&contents.0));
377 /// ```
378 pub struct Easy2<H> {
379     inner: Box<Inner<H>>,
380 }
381 
382 struct Inner<H> {
383     handle: *mut curl_sys::CURL,
384     header_list: Option<List>,
385     resolve_list: Option<List>,
386     connect_to_list: Option<List>,
387     form: Option<Form>,
388     error_buf: RefCell<Vec<u8>>,
389     handler: H,
390 }
391 
392 unsafe impl<H: Send> Send for Inner<H> {}
393 
394 /// Possible proxy types that libcurl currently understands.
395 #[allow(missing_docs)]
396 #[derive(Debug, Clone, Copy)]
397 pub enum ProxyType {
398     Http = curl_sys::CURLPROXY_HTTP as isize,
399     Http1 = curl_sys::CURLPROXY_HTTP_1_0 as isize,
400     Socks4 = curl_sys::CURLPROXY_SOCKS4 as isize,
401     Socks5 = curl_sys::CURLPROXY_SOCKS5 as isize,
402     Socks4a = curl_sys::CURLPROXY_SOCKS4A as isize,
403     Socks5Hostname = curl_sys::CURLPROXY_SOCKS5_HOSTNAME as isize,
404 
405     /// Hidden variant to indicate that this enum should not be matched on, it
406     /// may grow over time.
407     #[doc(hidden)]
408     __Nonexhaustive,
409 }
410 
411 /// Possible conditions for the `time_condition` method.
412 #[allow(missing_docs)]
413 #[derive(Debug, Clone, Copy)]
414 pub enum TimeCondition {
415     None = curl_sys::CURL_TIMECOND_NONE as isize,
416     IfModifiedSince = curl_sys::CURL_TIMECOND_IFMODSINCE as isize,
417     IfUnmodifiedSince = curl_sys::CURL_TIMECOND_IFUNMODSINCE as isize,
418     LastModified = curl_sys::CURL_TIMECOND_LASTMOD as isize,
419 
420     /// Hidden variant to indicate that this enum should not be matched on, it
421     /// may grow over time.
422     #[doc(hidden)]
423     __Nonexhaustive,
424 }
425 
426 /// Possible values to pass to the `ip_resolve` method.
427 #[allow(missing_docs)]
428 #[derive(Debug, Clone, Copy)]
429 pub enum IpResolve {
430     V4 = curl_sys::CURL_IPRESOLVE_V4 as isize,
431     V6 = curl_sys::CURL_IPRESOLVE_V6 as isize,
432     Any = curl_sys::CURL_IPRESOLVE_WHATEVER as isize,
433 
434     /// Hidden variant to indicate that this enum should not be matched on, it
435     /// may grow over time.
436     #[doc(hidden)]
437     __Nonexhaustive = 500,
438 }
439 
440 /// Possible values to pass to the `http_version` method.
441 #[derive(Debug, Clone, Copy)]
442 pub enum HttpVersion {
443     /// We don't care what http version to use, and we'd like the library to
444     /// choose the best possible for us.
445     Any = curl_sys::CURL_HTTP_VERSION_NONE as isize,
446 
447     /// Please use HTTP 1.0 in the request
448     V10 = curl_sys::CURL_HTTP_VERSION_1_0 as isize,
449 
450     /// Please use HTTP 1.1 in the request
451     V11 = curl_sys::CURL_HTTP_VERSION_1_1 as isize,
452 
453     /// Please use HTTP 2 in the request
454     /// (Added in CURL 7.33.0)
455     V2 = curl_sys::CURL_HTTP_VERSION_2_0 as isize,
456 
457     /// Use version 2 for HTTPS, version 1.1 for HTTP
458     /// (Added in CURL 7.47.0)
459     V2TLS = curl_sys::CURL_HTTP_VERSION_2TLS as isize,
460 
461     /// Please use HTTP 2 without HTTP/1.1 Upgrade
462     /// (Added in CURL 7.49.0)
463     V2PriorKnowledge = curl_sys::CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE as isize,
464 
465     /// Setting this value will make libcurl attempt to use HTTP/3 directly to
466     /// server given in the URL. Note that this cannot gracefully downgrade to
467     /// earlier HTTP version if the server doesn't support HTTP/3.
468     ///
469     /// For more reliably upgrading to HTTP/3, set the preferred version to
470     /// something lower and let the server announce its HTTP/3 support via
471     /// Alt-Svc:.
472     ///
473     /// (Added in CURL 7.66.0)
474     V3 = curl_sys::CURL_HTTP_VERSION_3 as isize,
475 
476     /// Hidden variant to indicate that this enum should not be matched on, it
477     /// may grow over time.
478     #[doc(hidden)]
479     __Nonexhaustive = 500,
480 }
481 
482 /// Possible values to pass to the `ssl_version` and `ssl_min_max_version` method.
483 #[allow(missing_docs)]
484 #[derive(Debug, Clone, Copy)]
485 pub enum SslVersion {
486     Default = curl_sys::CURL_SSLVERSION_DEFAULT as isize,
487     Tlsv1 = curl_sys::CURL_SSLVERSION_TLSv1 as isize,
488     Sslv2 = curl_sys::CURL_SSLVERSION_SSLv2 as isize,
489     Sslv3 = curl_sys::CURL_SSLVERSION_SSLv3 as isize,
490     Tlsv10 = curl_sys::CURL_SSLVERSION_TLSv1_0 as isize,
491     Tlsv11 = curl_sys::CURL_SSLVERSION_TLSv1_1 as isize,
492     Tlsv12 = curl_sys::CURL_SSLVERSION_TLSv1_2 as isize,
493     Tlsv13 = curl_sys::CURL_SSLVERSION_TLSv1_3 as isize,
494 
495     /// Hidden variant to indicate that this enum should not be matched on, it
496     /// may grow over time.
497     #[doc(hidden)]
498     __Nonexhaustive = 500,
499 }
500 
501 /// Possible return values from the `seek_function` callback.
502 #[derive(Debug, Clone, Copy)]
503 pub enum SeekResult {
504     /// Indicates that the seek operation was a success
505     Ok = curl_sys::CURL_SEEKFUNC_OK as isize,
506 
507     /// Indicates that the seek operation failed, and the entire request should
508     /// fail as a result.
509     Fail = curl_sys::CURL_SEEKFUNC_FAIL as isize,
510 
511     /// Indicates that although the seek failed libcurl should attempt to keep
512     /// working if possible (for example "seek" through reading).
513     CantSeek = curl_sys::CURL_SEEKFUNC_CANTSEEK as isize,
514 
515     /// Hidden variant to indicate that this enum should not be matched on, it
516     /// may grow over time.
517     #[doc(hidden)]
518     __Nonexhaustive = 500,
519 }
520 
521 /// Possible data chunks that can be witnessed as part of the `debug_function`
522 /// callback.
523 #[derive(Debug, Clone, Copy)]
524 pub enum InfoType {
525     /// The data is informational text.
526     Text,
527 
528     /// The data is header (or header-like) data received from the peer.
529     HeaderIn,
530 
531     /// The data is header (or header-like) data sent to the peer.
532     HeaderOut,
533 
534     /// The data is protocol data received from the peer.
535     DataIn,
536 
537     /// The data is protocol data sent to the peer.
538     DataOut,
539 
540     /// The data is SSL/TLS (binary) data received from the peer.
541     SslDataIn,
542 
543     /// The data is SSL/TLS (binary) data sent to the peer.
544     SslDataOut,
545 
546     /// Hidden variant to indicate that this enum should not be matched on, it
547     /// may grow over time.
548     #[doc(hidden)]
549     __Nonexhaustive,
550 }
551 
552 /// Possible error codes that can be returned from the `read_function` callback.
553 #[derive(Debug)]
554 pub enum ReadError {
555     /// Indicates that the connection should be aborted immediately
556     Abort,
557 
558     /// Indicates that reading should be paused until `unpause` is called.
559     Pause,
560 
561     /// Hidden variant to indicate that this enum should not be matched on, it
562     /// may grow over time.
563     #[doc(hidden)]
564     __Nonexhaustive,
565 }
566 
567 /// Possible error codes that can be returned from the `write_function` callback.
568 #[derive(Debug)]
569 pub enum WriteError {
570     /// Indicates that reading should be paused until `unpause` is called.
571     Pause,
572 
573     /// Hidden variant to indicate that this enum should not be matched on, it
574     /// may grow over time.
575     #[doc(hidden)]
576     __Nonexhaustive,
577 }
578 
579 /// Options for `.netrc` parsing.
580 #[derive(Debug, Clone, Copy)]
581 pub enum NetRc {
582     /// Ignoring `.netrc` file and use information from url
583     ///
584     /// This option is default
585     Ignored = curl_sys::CURL_NETRC_IGNORED as isize,
586 
587     /// The  use of your `~/.netrc` file is optional, and information in the URL is to be
588     /// preferred. The file will be scanned for the host and user name (to find the password only)
589     /// or for the host only, to find the first user name and password after that machine, which
590     /// ever information is not specified in the URL.
591     Optional = curl_sys::CURL_NETRC_OPTIONAL as isize,
592 
593     /// This value tells the library that use of the file is required, to ignore the information in
594     /// the URL, and to search the file for the host only.
595     Required = curl_sys::CURL_NETRC_REQUIRED as isize,
596 }
597 
598 /// Structure which stores possible authentication methods to get passed to
599 /// `http_auth` and `proxy_auth`.
600 #[derive(Clone)]
601 pub struct Auth {
602     bits: c_long,
603 }
604 
605 /// Structure which stores possible ssl options to pass to `ssl_options`.
606 #[derive(Clone)]
607 pub struct SslOpt {
608     bits: c_long,
609 }
610 
611 impl<H: Handler> Easy2<H> {
612     /// Creates a new "easy" handle which is the core of almost all operations
613     /// in libcurl.
614     ///
615     /// To use a handle, applications typically configure a number of options
616     /// followed by a call to `perform`. Options are preserved across calls to
617     /// `perform` and need to be reset manually (or via the `reset` method) if
618     /// this is not desired.
new(handler: H) -> Easy2<H>619     pub fn new(handler: H) -> Easy2<H> {
620         ::init();
621         unsafe {
622             let handle = curl_sys::curl_easy_init();
623             assert!(!handle.is_null());
624             let mut ret = Easy2 {
625                 inner: Box::new(Inner {
626                     handle: handle,
627                     header_list: None,
628                     resolve_list: None,
629                     connect_to_list: None,
630                     form: None,
631                     error_buf: RefCell::new(vec![0; curl_sys::CURL_ERROR_SIZE]),
632                     handler: handler,
633                 }),
634             };
635             ret.default_configure();
636             return ret;
637         }
638     }
639 
640     /// Re-initializes this handle to the default values.
641     ///
642     /// This puts the handle to the same state as it was in when it was just
643     /// created. This does, however, keep live connections, the session id
644     /// cache, the dns cache, and cookies.
reset(&mut self)645     pub fn reset(&mut self) {
646         unsafe {
647             curl_sys::curl_easy_reset(self.inner.handle);
648         }
649         self.default_configure();
650     }
651 
default_configure(&mut self)652     fn default_configure(&mut self) {
653         self.setopt_ptr(
654             curl_sys::CURLOPT_ERRORBUFFER,
655             self.inner.error_buf.borrow().as_ptr() as *const _,
656         )
657         .expect("failed to set error buffer");
658         let _ = self.signal(false);
659         self.ssl_configure();
660 
661         let ptr = &*self.inner as *const _ as *const _;
662 
663         let cb: extern "C" fn(*mut c_char, size_t, size_t, *mut c_void) -> size_t = header_cb::<H>;
664         self.setopt_ptr(curl_sys::CURLOPT_HEADERFUNCTION, cb as *const _)
665             .expect("failed to set header callback");
666         self.setopt_ptr(curl_sys::CURLOPT_HEADERDATA, ptr)
667             .expect("failed to set header callback");
668 
669         let cb: curl_sys::curl_write_callback = write_cb::<H>;
670         self.setopt_ptr(curl_sys::CURLOPT_WRITEFUNCTION, cb as *const _)
671             .expect("failed to set write callback");
672         self.setopt_ptr(curl_sys::CURLOPT_WRITEDATA, ptr)
673             .expect("failed to set write callback");
674 
675         let cb: curl_sys::curl_read_callback = read_cb::<H>;
676         self.setopt_ptr(curl_sys::CURLOPT_READFUNCTION, cb as *const _)
677             .expect("failed to set read callback");
678         self.setopt_ptr(curl_sys::CURLOPT_READDATA, ptr)
679             .expect("failed to set read callback");
680 
681         let cb: curl_sys::curl_seek_callback = seek_cb::<H>;
682         self.setopt_ptr(curl_sys::CURLOPT_SEEKFUNCTION, cb as *const _)
683             .expect("failed to set seek callback");
684         self.setopt_ptr(curl_sys::CURLOPT_SEEKDATA, ptr)
685             .expect("failed to set seek callback");
686 
687         let cb: curl_sys::curl_progress_callback = progress_cb::<H>;
688         self.setopt_ptr(curl_sys::CURLOPT_PROGRESSFUNCTION, cb as *const _)
689             .expect("failed to set progress callback");
690         self.setopt_ptr(curl_sys::CURLOPT_PROGRESSDATA, ptr)
691             .expect("failed to set progress callback");
692 
693         let cb: curl_sys::curl_debug_callback = debug_cb::<H>;
694         self.setopt_ptr(curl_sys::CURLOPT_DEBUGFUNCTION, cb as *const _)
695             .expect("failed to set debug callback");
696         self.setopt_ptr(curl_sys::CURLOPT_DEBUGDATA, ptr)
697             .expect("failed to set debug callback");
698 
699         let cb: curl_sys::curl_ssl_ctx_callback = ssl_ctx_cb::<H>;
700         drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_FUNCTION, cb as *const _));
701         drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_DATA, ptr));
702 
703         let cb: curl_sys::curl_opensocket_callback = opensocket_cb::<H>;
704         self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETFUNCTION, cb as *const _)
705             .expect("failed to set open socket callback");
706         self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETDATA, ptr)
707             .expect("failed to set open socket callback");
708     }
709 
710     #[cfg(need_openssl_probe)]
ssl_configure(&mut self)711     fn ssl_configure(&mut self) {
712         let probe = ::openssl_probe::probe();
713         if let Some(ref path) = probe.cert_file {
714             let _ = self.cainfo(path);
715         }
716         if let Some(ref path) = probe.cert_dir {
717             let _ = self.capath(path);
718         }
719     }
720 
721     #[cfg(not(need_openssl_probe))]
ssl_configure(&mut self)722     fn ssl_configure(&mut self) {}
723 }
724 
725 impl<H> Easy2<H> {
726     // =========================================================================
727     // Behavior options
728 
729     /// Configures this handle to have verbose output to help debug protocol
730     /// information.
731     ///
732     /// By default output goes to stderr, but the `stderr` function on this type
733     /// can configure that. You can also use the `debug_function` method to get
734     /// all protocol data sent and received.
735     ///
736     /// By default, this option is `false`.
verbose(&mut self, verbose: bool) -> Result<(), Error>737     pub fn verbose(&mut self, verbose: bool) -> Result<(), Error> {
738         self.setopt_long(curl_sys::CURLOPT_VERBOSE, verbose as c_long)
739     }
740 
741     /// Indicates whether header information is streamed to the output body of
742     /// this request.
743     ///
744     /// This option is only relevant for protocols which have header metadata
745     /// (like http or ftp). It's not generally possible to extract headers
746     /// from the body if using this method, that use case should be intended for
747     /// the `header_function` method.
748     ///
749     /// To set HTTP headers, use the `http_header` method.
750     ///
751     /// By default, this option is `false` and corresponds to
752     /// `CURLOPT_HEADER`.
show_header(&mut self, show: bool) -> Result<(), Error>753     pub fn show_header(&mut self, show: bool) -> Result<(), Error> {
754         self.setopt_long(curl_sys::CURLOPT_HEADER, show as c_long)
755     }
756 
757     /// Indicates whether a progress meter will be shown for requests done with
758     /// this handle.
759     ///
760     /// This will also prevent the `progress_function` from being called.
761     ///
762     /// By default this option is `false` and corresponds to
763     /// `CURLOPT_NOPROGRESS`.
progress(&mut self, progress: bool) -> Result<(), Error>764     pub fn progress(&mut self, progress: bool) -> Result<(), Error> {
765         self.setopt_long(curl_sys::CURLOPT_NOPROGRESS, (!progress) as c_long)
766     }
767 
768     /// Inform libcurl whether or not it should install signal handlers or
769     /// attempt to use signals to perform library functions.
770     ///
771     /// If this option is disabled then timeouts during name resolution will not
772     /// work unless libcurl is built against c-ares. Note that enabling this
773     /// option, however, may not cause libcurl to work with multiple threads.
774     ///
775     /// By default this option is `false` and corresponds to `CURLOPT_NOSIGNAL`.
776     /// Note that this default is **different than libcurl** as it is intended
777     /// that this library is threadsafe by default. See the [libcurl docs] for
778     /// some more information.
779     ///
780     /// [libcurl docs]: https://curl.haxx.se/libcurl/c/threadsafe.html
signal(&mut self, signal: bool) -> Result<(), Error>781     pub fn signal(&mut self, signal: bool) -> Result<(), Error> {
782         self.setopt_long(curl_sys::CURLOPT_NOSIGNAL, (!signal) as c_long)
783     }
784 
785     /// Indicates whether multiple files will be transferred based on the file
786     /// name pattern.
787     ///
788     /// The last part of a filename uses fnmatch-like pattern matching.
789     ///
790     /// By default this option is `false` and corresponds to
791     /// `CURLOPT_WILDCARDMATCH`.
wildcard_match(&mut self, m: bool) -> Result<(), Error>792     pub fn wildcard_match(&mut self, m: bool) -> Result<(), Error> {
793         self.setopt_long(curl_sys::CURLOPT_WILDCARDMATCH, m as c_long)
794     }
795 
796     /// Provides the Unix domain socket which this handle will work with.
797     ///
798     /// The string provided must be a path to a Unix domain socket encoded with
799     /// the format:
800     ///
801     /// ```text
802     /// /path/file.sock
803     /// ```
804     ///
805     /// By default this option is not set and corresponds to
806     /// [`CURLOPT_UNIX_SOCKET_PATH`](https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html).
unix_socket(&mut self, unix_domain_socket: &str) -> Result<(), Error>807     pub fn unix_socket(&mut self, unix_domain_socket: &str) -> Result<(), Error> {
808         let socket = CString::new(unix_domain_socket)?;
809         self.setopt_str(curl_sys::CURLOPT_UNIX_SOCKET_PATH, &socket)
810     }
811 
812     /// Provides the Unix domain socket which this handle will work with.
813     ///
814     /// The string provided must be a path to a Unix domain socket encoded with
815     /// the format:
816     ///
817     /// ```text
818     /// /path/file.sock
819     /// ```
820     ///
821     /// This function is an alternative to [`Easy2::unix_socket`] that supports
822     /// non-UTF-8 paths and also supports disabling Unix sockets by setting the
823     /// option to `None`.
824     ///
825     /// By default this option is not set and corresponds to
826     /// [`CURLOPT_UNIX_SOCKET_PATH`](https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html).
unix_socket_path<P: AsRef<Path>>(&mut self, path: Option<P>) -> Result<(), Error>827     pub fn unix_socket_path<P: AsRef<Path>>(&mut self, path: Option<P>) -> Result<(), Error> {
828         if let Some(path) = path {
829             self.setopt_path(curl_sys::CURLOPT_UNIX_SOCKET_PATH, path.as_ref())
830         } else {
831             self.setopt_ptr(curl_sys::CURLOPT_UNIX_SOCKET_PATH, 0 as _)
832         }
833     }
834 
835     // =========================================================================
836     // Internal accessors
837 
838     /// Acquires a reference to the underlying handler for events.
get_ref(&self) -> &H839     pub fn get_ref(&self) -> &H {
840         &self.inner.handler
841     }
842 
843     /// Acquires a reference to the underlying handler for events.
get_mut(&mut self) -> &mut H844     pub fn get_mut(&mut self) -> &mut H {
845         &mut self.inner.handler
846     }
847 
848     // =========================================================================
849     // Error options
850 
851     // TODO: error buffer and stderr
852 
853     /// Indicates whether this library will fail on HTTP response codes >= 400.
854     ///
855     /// This method is not fail-safe especially when authentication is involved.
856     ///
857     /// By default this option is `false` and corresponds to
858     /// `CURLOPT_FAILONERROR`.
fail_on_error(&mut self, fail: bool) -> Result<(), Error>859     pub fn fail_on_error(&mut self, fail: bool) -> Result<(), Error> {
860         self.setopt_long(curl_sys::CURLOPT_FAILONERROR, fail as c_long)
861     }
862 
863     // =========================================================================
864     // Network options
865 
866     /// Provides the URL which this handle will work with.
867     ///
868     /// The string provided must be URL-encoded with the format:
869     ///
870     /// ```text
871     /// scheme://host:port/path
872     /// ```
873     ///
874     /// The syntax is not validated as part of this function and that is
875     /// deferred until later.
876     ///
877     /// By default this option is not set and `perform` will not work until it
878     /// is set. This option corresponds to `CURLOPT_URL`.
url(&mut self, url: &str) -> Result<(), Error>879     pub fn url(&mut self, url: &str) -> Result<(), Error> {
880         let url = CString::new(url)?;
881         self.setopt_str(curl_sys::CURLOPT_URL, &url)
882     }
883 
884     /// Configures the port number to connect to, instead of the one specified
885     /// in the URL or the default of the protocol.
port(&mut self, port: u16) -> Result<(), Error>886     pub fn port(&mut self, port: u16) -> Result<(), Error> {
887         self.setopt_long(curl_sys::CURLOPT_PORT, port as c_long)
888     }
889 
890     /// Connect to a specific host and port.
891     ///
892     /// Each single string should be written using the format
893     /// `HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT` where `HOST` is the host of
894     /// the request, `PORT` is the port of the request, `CONNECT-TO-HOST` is the
895     /// host name to connect to, and `CONNECT-TO-PORT` is the port to connect
896     /// to.
897     ///
898     /// The first string that matches the request's host and port is used.
899     ///
900     /// By default, this option is empty and corresponds to
901     /// [`CURLOPT_CONNECT_TO`](https://curl.haxx.se/libcurl/c/CURLOPT_CONNECT_TO.html).
connect_to(&mut self, list: List) -> Result<(), Error>902     pub fn connect_to(&mut self, list: List) -> Result<(), Error> {
903         let ptr = list::raw(&list);
904         self.inner.connect_to_list = Some(list);
905         self.setopt_ptr(curl_sys::CURLOPT_CONNECT_TO, ptr as *const _)
906     }
907 
908     // /// Indicates whether sequences of `/../` and `/./` will be squashed or not.
909     // ///
910     // /// By default this option is `false` and corresponds to
911     // /// `CURLOPT_PATH_AS_IS`.
912     // pub fn path_as_is(&mut self, as_is: bool) -> Result<(), Error> {
913     // }
914 
915     /// Provide the URL of a proxy to use.
916     ///
917     /// By default this option is not set and corresponds to `CURLOPT_PROXY`.
proxy(&mut self, url: &str) -> Result<(), Error>918     pub fn proxy(&mut self, url: &str) -> Result<(), Error> {
919         let url = CString::new(url)?;
920         self.setopt_str(curl_sys::CURLOPT_PROXY, &url)
921     }
922 
923     /// Provide port number the proxy is listening on.
924     ///
925     /// By default this option is not set (the default port for the proxy
926     /// protocol is used) and corresponds to `CURLOPT_PROXYPORT`.
proxy_port(&mut self, port: u16) -> Result<(), Error>927     pub fn proxy_port(&mut self, port: u16) -> Result<(), Error> {
928         self.setopt_long(curl_sys::CURLOPT_PROXYPORT, port as c_long)
929     }
930 
931     /// Set CA certificate to verify peer against for proxy.
932     ///
933     /// By default this value is not set and corresponds to
934     /// `CURLOPT_PROXY_CAINFO`.
proxy_cainfo(&mut self, cainfo: &str) -> Result<(), Error>935     pub fn proxy_cainfo(&mut self, cainfo: &str) -> Result<(), Error> {
936         let cainfo = CString::new(cainfo)?;
937         self.setopt_str(curl_sys::CURLOPT_PROXY_CAINFO, &cainfo)
938     }
939 
940     /// Specify a directory holding CA certificates for proxy.
941     ///
942     /// The specified directory should hold multiple CA certificates to verify
943     /// the HTTPS proxy with. If libcurl is built against OpenSSL, the
944     /// certificate directory must be prepared using the OpenSSL `c_rehash`
945     /// utility.
946     ///
947     /// By default this value is not set and corresponds to
948     /// `CURLOPT_PROXY_CAPATH`.
proxy_capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>949     pub fn proxy_capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
950         self.setopt_path(curl_sys::CURLOPT_PROXY_CAPATH, path.as_ref())
951     }
952 
953     /// Set client certificate for proxy.
954     ///
955     /// By default this value is not set and corresponds to
956     /// `CURLOPT_PROXY_SSLCERT`.
proxy_sslcert(&mut self, sslcert: &str) -> Result<(), Error>957     pub fn proxy_sslcert(&mut self, sslcert: &str) -> Result<(), Error> {
958         let sslcert = CString::new(sslcert)?;
959         self.setopt_str(curl_sys::CURLOPT_PROXY_SSLCERT, &sslcert)
960     }
961 
962     /// Set private key for HTTPS proxy.
963     ///
964     /// By default this value is not set and corresponds to
965     /// `CURLOPT_PROXY_SSLKEY`.
proxy_sslkey(&mut self, sslkey: &str) -> Result<(), Error>966     pub fn proxy_sslkey(&mut self, sslkey: &str) -> Result<(), Error> {
967         let sslkey = CString::new(sslkey)?;
968         self.setopt_str(curl_sys::CURLOPT_PROXY_SSLKEY, &sslkey)
969     }
970 
971     /// Indicates the type of proxy being used.
972     ///
973     /// By default this option is `ProxyType::Http` and corresponds to
974     /// `CURLOPT_PROXYTYPE`.
proxy_type(&mut self, kind: ProxyType) -> Result<(), Error>975     pub fn proxy_type(&mut self, kind: ProxyType) -> Result<(), Error> {
976         self.setopt_long(curl_sys::CURLOPT_PROXYTYPE, kind as c_long)
977     }
978 
979     /// Provide a list of hosts that should not be proxied to.
980     ///
981     /// This string is a comma-separated list of hosts which should not use the
982     /// proxy specified for connections. A single `*` character is also accepted
983     /// as a wildcard for all hosts.
984     ///
985     /// By default this option is not set and corresponds to
986     /// `CURLOPT_NOPROXY`.
noproxy(&mut self, skip: &str) -> Result<(), Error>987     pub fn noproxy(&mut self, skip: &str) -> Result<(), Error> {
988         let skip = CString::new(skip)?;
989         self.setopt_str(curl_sys::CURLOPT_NOPROXY, &skip)
990     }
991 
992     /// Inform curl whether it should tunnel all operations through the proxy.
993     ///
994     /// This essentially means that a `CONNECT` is sent to the proxy for all
995     /// outbound requests.
996     ///
997     /// By default this option is `false` and corresponds to
998     /// `CURLOPT_HTTPPROXYTUNNEL`.
http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error>999     pub fn http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error> {
1000         self.setopt_long(curl_sys::CURLOPT_HTTPPROXYTUNNEL, tunnel as c_long)
1001     }
1002 
1003     /// Tell curl which interface to bind to for an outgoing network interface.
1004     ///
1005     /// The interface name, IP address, or host name can be specified here.
1006     ///
1007     /// By default this option is not set and corresponds to
1008     /// `CURLOPT_INTERFACE`.
interface(&mut self, interface: &str) -> Result<(), Error>1009     pub fn interface(&mut self, interface: &str) -> Result<(), Error> {
1010         let s = CString::new(interface)?;
1011         self.setopt_str(curl_sys::CURLOPT_INTERFACE, &s)
1012     }
1013 
1014     /// Indicate which port should be bound to locally for this connection.
1015     ///
1016     /// By default this option is 0 (any port) and corresponds to
1017     /// `CURLOPT_LOCALPORT`.
set_local_port(&mut self, port: u16) -> Result<(), Error>1018     pub fn set_local_port(&mut self, port: u16) -> Result<(), Error> {
1019         self.setopt_long(curl_sys::CURLOPT_LOCALPORT, port as c_long)
1020     }
1021 
1022     /// Indicates the number of attempts libcurl will perform to find a working
1023     /// port number.
1024     ///
1025     /// By default this option is 1 and corresponds to
1026     /// `CURLOPT_LOCALPORTRANGE`.
local_port_range(&mut self, range: u16) -> Result<(), Error>1027     pub fn local_port_range(&mut self, range: u16) -> Result<(), Error> {
1028         self.setopt_long(curl_sys::CURLOPT_LOCALPORTRANGE, range as c_long)
1029     }
1030 
1031     /// Sets the DNS servers that wil be used.
1032     ///
1033     /// Provide a comma separated list, for example: `8.8.8.8,8.8.4.4`.
1034     ///
1035     /// By default this option is not set and the OS's DNS resolver is used.
1036     /// This option can only be used if libcurl is linked against
1037     /// [c-ares](https://c-ares.haxx.se), otherwise setting it will return
1038     /// an error.
dns_servers(&mut self, servers: &str) -> Result<(), Error>1039     pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> {
1040         let s = CString::new(servers)?;
1041         self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &s)
1042     }
1043 
1044     /// Sets the timeout of how long name resolves will be kept in memory.
1045     ///
1046     /// This is distinct from DNS TTL options and is entirely speculative.
1047     ///
1048     /// By default this option is 60s and corresponds to
1049     /// `CURLOPT_DNS_CACHE_TIMEOUT`.
dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error>1050     pub fn dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error> {
1051         self.setopt_long(curl_sys::CURLOPT_DNS_CACHE_TIMEOUT, dur.as_secs() as c_long)
1052     }
1053 
1054     /// Specify the preferred receive buffer size, in bytes.
1055     ///
1056     /// This is treated as a request, not an order, and the main point of this
1057     /// is that the write callback may get called more often with smaller
1058     /// chunks.
1059     ///
1060     /// By default this option is the maximum write size and corresopnds to
1061     /// `CURLOPT_BUFFERSIZE`.
buffer_size(&mut self, size: usize) -> Result<(), Error>1062     pub fn buffer_size(&mut self, size: usize) -> Result<(), Error> {
1063         self.setopt_long(curl_sys::CURLOPT_BUFFERSIZE, size as c_long)
1064     }
1065 
1066     // /// Enable or disable TCP Fast Open
1067     // ///
1068     // /// By default this options defaults to `false` and corresponds to
1069     // /// `CURLOPT_TCP_FASTOPEN`
1070     // pub fn fast_open(&mut self, enable: bool) -> Result<(), Error> {
1071     // }
1072 
1073     /// Configures whether the TCP_NODELAY option is set, or Nagle's algorithm
1074     /// is disabled.
1075     ///
1076     /// The purpose of Nagle's algorithm is to minimize the number of small
1077     /// packet's on the network, and disabling this may be less efficient in
1078     /// some situations.
1079     ///
1080     /// By default this option is `false` and corresponds to
1081     /// `CURLOPT_TCP_NODELAY`.
tcp_nodelay(&mut self, enable: bool) -> Result<(), Error>1082     pub fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error> {
1083         self.setopt_long(curl_sys::CURLOPT_TCP_NODELAY, enable as c_long)
1084     }
1085 
1086     /// Configures whether TCP keepalive probes will be sent.
1087     ///
1088     /// The delay and frequency of these probes is controlled by `tcp_keepidle`
1089     /// and `tcp_keepintvl`.
1090     ///
1091     /// By default this option is `false` and corresponds to
1092     /// `CURLOPT_TCP_KEEPALIVE`.
tcp_keepalive(&mut self, enable: bool) -> Result<(), Error>1093     pub fn tcp_keepalive(&mut self, enable: bool) -> Result<(), Error> {
1094         self.setopt_long(curl_sys::CURLOPT_TCP_KEEPALIVE, enable as c_long)
1095     }
1096 
1097     /// Configures the TCP keepalive idle time wait.
1098     ///
1099     /// This is the delay, after which the connection is idle, keepalive probes
1100     /// will be sent. Not all operating systems support this.
1101     ///
1102     /// By default this corresponds to `CURLOPT_TCP_KEEPIDLE`.
tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error>1103     pub fn tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error> {
1104         self.setopt_long(curl_sys::CURLOPT_TCP_KEEPIDLE, amt.as_secs() as c_long)
1105     }
1106 
1107     /// Configures the delay between keepalive probes.
1108     ///
1109     /// By default this corresponds to `CURLOPT_TCP_KEEPINTVL`.
tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error>1110     pub fn tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error> {
1111         self.setopt_long(curl_sys::CURLOPT_TCP_KEEPINTVL, amt.as_secs() as c_long)
1112     }
1113 
1114     /// Configures the scope for local IPv6 addresses.
1115     ///
1116     /// Sets the scope_id value to use when connecting to IPv6 or link-local
1117     /// addresses.
1118     ///
1119     /// By default this value is 0 and corresponds to `CURLOPT_ADDRESS_SCOPE`
address_scope(&mut self, scope: u32) -> Result<(), Error>1120     pub fn address_scope(&mut self, scope: u32) -> Result<(), Error> {
1121         self.setopt_long(curl_sys::CURLOPT_ADDRESS_SCOPE, scope as c_long)
1122     }
1123 
1124     // =========================================================================
1125     // Names and passwords
1126 
1127     /// Configures the username to pass as authentication for this connection.
1128     ///
1129     /// By default this value is not set and corresponds to `CURLOPT_USERNAME`.
username(&mut self, user: &str) -> Result<(), Error>1130     pub fn username(&mut self, user: &str) -> Result<(), Error> {
1131         let user = CString::new(user)?;
1132         self.setopt_str(curl_sys::CURLOPT_USERNAME, &user)
1133     }
1134 
1135     /// Configures the password to pass as authentication for this connection.
1136     ///
1137     /// By default this value is not set and corresponds to `CURLOPT_PASSWORD`.
password(&mut self, pass: &str) -> Result<(), Error>1138     pub fn password(&mut self, pass: &str) -> Result<(), Error> {
1139         let pass = CString::new(pass)?;
1140         self.setopt_str(curl_sys::CURLOPT_PASSWORD, &pass)
1141     }
1142 
1143     /// Set HTTP server authentication methods to try
1144     ///
1145     /// If more than one method is set, libcurl will first query the site to see
1146     /// which authentication methods it supports and then pick the best one you
1147     /// allow it to use. For some methods, this will induce an extra network
1148     /// round-trip. Set the actual name and password with the `password` and
1149     /// `username` methods.
1150     ///
1151     /// For authentication with a proxy, see `proxy_auth`.
1152     ///
1153     /// By default this value is basic and corresponds to `CURLOPT_HTTPAUTH`.
http_auth(&mut self, auth: &Auth) -> Result<(), Error>1154     pub fn http_auth(&mut self, auth: &Auth) -> Result<(), Error> {
1155         self.setopt_long(curl_sys::CURLOPT_HTTPAUTH, auth.bits)
1156     }
1157 
1158     /// Configures the proxy username to pass as authentication for this
1159     /// connection.
1160     ///
1161     /// By default this value is not set and corresponds to
1162     /// `CURLOPT_PROXYUSERNAME`.
proxy_username(&mut self, user: &str) -> Result<(), Error>1163     pub fn proxy_username(&mut self, user: &str) -> Result<(), Error> {
1164         let user = CString::new(user)?;
1165         self.setopt_str(curl_sys::CURLOPT_PROXYUSERNAME, &user)
1166     }
1167 
1168     /// Configures the proxy password to pass as authentication for this
1169     /// connection.
1170     ///
1171     /// By default this value is not set and corresponds to
1172     /// `CURLOPT_PROXYPASSWORD`.
proxy_password(&mut self, pass: &str) -> Result<(), Error>1173     pub fn proxy_password(&mut self, pass: &str) -> Result<(), Error> {
1174         let pass = CString::new(pass)?;
1175         self.setopt_str(curl_sys::CURLOPT_PROXYPASSWORD, &pass)
1176     }
1177 
1178     /// Set HTTP proxy authentication methods to try
1179     ///
1180     /// If more than one method is set, libcurl will first query the site to see
1181     /// which authentication methods it supports and then pick the best one you
1182     /// allow it to use. For some methods, this will induce an extra network
1183     /// round-trip. Set the actual name and password with the `proxy_password`
1184     /// and `proxy_username` methods.
1185     ///
1186     /// By default this value is basic and corresponds to `CURLOPT_PROXYAUTH`.
proxy_auth(&mut self, auth: &Auth) -> Result<(), Error>1187     pub fn proxy_auth(&mut self, auth: &Auth) -> Result<(), Error> {
1188         self.setopt_long(curl_sys::CURLOPT_PROXYAUTH, auth.bits)
1189     }
1190 
1191     /// Enable .netrc parsing
1192     ///
1193     /// By default the .netrc file is ignored and corresponds to `CURL_NETRC_IGNORED`.
netrc(&mut self, netrc: NetRc) -> Result<(), Error>1194     pub fn netrc(&mut self, netrc: NetRc) -> Result<(), Error> {
1195         self.setopt_long(curl_sys::CURLOPT_NETRC, netrc as c_long)
1196     }
1197 
1198     // =========================================================================
1199     // HTTP Options
1200 
1201     /// Indicates whether the referer header is automatically updated
1202     ///
1203     /// By default this option is `false` and corresponds to
1204     /// `CURLOPT_AUTOREFERER`.
autoreferer(&mut self, enable: bool) -> Result<(), Error>1205     pub fn autoreferer(&mut self, enable: bool) -> Result<(), Error> {
1206         self.setopt_long(curl_sys::CURLOPT_AUTOREFERER, enable as c_long)
1207     }
1208 
1209     /// Enables automatic decompression of HTTP downloads.
1210     ///
1211     /// Sets the contents of the Accept-Encoding header sent in an HTTP request.
1212     /// This enables decoding of a response with Content-Encoding.
1213     ///
1214     /// Currently supported encoding are `identity`, `zlib`, and `gzip`. A
1215     /// zero-length string passed in will send all accepted encodings.
1216     ///
1217     /// By default this option is not set and corresponds to
1218     /// `CURLOPT_ACCEPT_ENCODING`.
accept_encoding(&mut self, encoding: &str) -> Result<(), Error>1219     pub fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error> {
1220         let encoding = CString::new(encoding)?;
1221         self.setopt_str(curl_sys::CURLOPT_ACCEPT_ENCODING, &encoding)
1222     }
1223 
1224     /// Request the HTTP Transfer Encoding.
1225     ///
1226     /// By default this option is `false` and corresponds to
1227     /// `CURLOPT_TRANSFER_ENCODING`.
transfer_encoding(&mut self, enable: bool) -> Result<(), Error>1228     pub fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error> {
1229         self.setopt_long(curl_sys::CURLOPT_TRANSFER_ENCODING, enable as c_long)
1230     }
1231 
1232     /// Follow HTTP 3xx redirects.
1233     ///
1234     /// Indicates whether any `Location` headers in the response should get
1235     /// followed.
1236     ///
1237     /// By default this option is `false` and corresponds to
1238     /// `CURLOPT_FOLLOWLOCATION`.
follow_location(&mut self, enable: bool) -> Result<(), Error>1239     pub fn follow_location(&mut self, enable: bool) -> Result<(), Error> {
1240         self.setopt_long(curl_sys::CURLOPT_FOLLOWLOCATION, enable as c_long)
1241     }
1242 
1243     /// Send credentials to hosts other than the first as well.
1244     ///
1245     /// Sends username/password credentials even when the host changes as part
1246     /// of a redirect.
1247     ///
1248     /// By default this option is `false` and corresponds to
1249     /// `CURLOPT_UNRESTRICTED_AUTH`.
unrestricted_auth(&mut self, enable: bool) -> Result<(), Error>1250     pub fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error> {
1251         self.setopt_long(curl_sys::CURLOPT_UNRESTRICTED_AUTH, enable as c_long)
1252     }
1253 
1254     /// Set the maximum number of redirects allowed.
1255     ///
1256     /// A value of 0 will refuse any redirect.
1257     ///
1258     /// By default this option is `-1` (unlimited) and corresponds to
1259     /// `CURLOPT_MAXREDIRS`.
max_redirections(&mut self, max: u32) -> Result<(), Error>1260     pub fn max_redirections(&mut self, max: u32) -> Result<(), Error> {
1261         self.setopt_long(curl_sys::CURLOPT_MAXREDIRS, max as c_long)
1262     }
1263 
1264     // TODO: post_redirections
1265 
1266     /// Make an HTTP PUT request.
1267     ///
1268     /// By default this option is `false` and corresponds to `CURLOPT_PUT`.
put(&mut self, enable: bool) -> Result<(), Error>1269     pub fn put(&mut self, enable: bool) -> Result<(), Error> {
1270         self.setopt_long(curl_sys::CURLOPT_PUT, enable as c_long)
1271     }
1272 
1273     /// Make an HTTP POST request.
1274     ///
1275     /// This will also make the library use the
1276     /// `Content-Type: application/x-www-form-urlencoded` header.
1277     ///
1278     /// POST data can be specified through `post_fields` or by specifying a read
1279     /// function.
1280     ///
1281     /// By default this option is `false` and corresponds to `CURLOPT_POST`.
post(&mut self, enable: bool) -> Result<(), Error>1282     pub fn post(&mut self, enable: bool) -> Result<(), Error> {
1283         self.setopt_long(curl_sys::CURLOPT_POST, enable as c_long)
1284     }
1285 
1286     /// Configures the data that will be uploaded as part of a POST.
1287     ///
1288     /// Note that the data is copied into this handle and if that's not desired
1289     /// then the read callbacks can be used instead.
1290     ///
1291     /// By default this option is not set and corresponds to
1292     /// `CURLOPT_COPYPOSTFIELDS`.
post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error>1293     pub fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error> {
1294         // Set the length before the pointer so libcurl knows how much to read
1295         self.post_field_size(data.len() as u64)?;
1296         self.setopt_ptr(curl_sys::CURLOPT_COPYPOSTFIELDS, data.as_ptr() as *const _)
1297     }
1298 
1299     /// Configures the size of data that's going to be uploaded as part of a
1300     /// POST operation.
1301     ///
1302     /// This is called automatically as part of `post_fields` and should only
1303     /// be called if data is being provided in a read callback (and even then
1304     /// it's optional).
1305     ///
1306     /// By default this option is not set and corresponds to
1307     /// `CURLOPT_POSTFIELDSIZE_LARGE`.
post_field_size(&mut self, size: u64) -> Result<(), Error>1308     pub fn post_field_size(&mut self, size: u64) -> Result<(), Error> {
1309         // Clear anything previous to ensure we don't read past a buffer
1310         self.setopt_ptr(curl_sys::CURLOPT_POSTFIELDS, 0 as *const _)?;
1311         self.setopt_off_t(
1312             curl_sys::CURLOPT_POSTFIELDSIZE_LARGE,
1313             size as curl_sys::curl_off_t,
1314         )
1315     }
1316 
1317     /// Tells libcurl you want a multipart/formdata HTTP POST to be made and you
1318     /// instruct what data to pass on to the server in the `form` argument.
1319     ///
1320     /// By default this option is set to null and corresponds to
1321     /// `CURLOPT_HTTPPOST`.
httppost(&mut self, form: Form) -> Result<(), Error>1322     pub fn httppost(&mut self, form: Form) -> Result<(), Error> {
1323         self.setopt_ptr(curl_sys::CURLOPT_HTTPPOST, form::raw(&form) as *const _)?;
1324         self.inner.form = Some(form);
1325         Ok(())
1326     }
1327 
1328     /// Sets the HTTP referer header
1329     ///
1330     /// By default this option is not set and corresponds to `CURLOPT_REFERER`.
referer(&mut self, referer: &str) -> Result<(), Error>1331     pub fn referer(&mut self, referer: &str) -> Result<(), Error> {
1332         let referer = CString::new(referer)?;
1333         self.setopt_str(curl_sys::CURLOPT_REFERER, &referer)
1334     }
1335 
1336     /// Sets the HTTP user-agent header
1337     ///
1338     /// By default this option is not set and corresponds to
1339     /// `CURLOPT_USERAGENT`.
useragent(&mut self, useragent: &str) -> Result<(), Error>1340     pub fn useragent(&mut self, useragent: &str) -> Result<(), Error> {
1341         let useragent = CString::new(useragent)?;
1342         self.setopt_str(curl_sys::CURLOPT_USERAGENT, &useragent)
1343     }
1344 
1345     /// Add some headers to this HTTP request.
1346     ///
1347     /// If you add a header that is otherwise used internally, the value here
1348     /// takes precedence. If a header is added with no content (like `Accept:`)
1349     /// the internally the header will get disabled. To add a header with no
1350     /// content, use the form `MyHeader;` (not the trailing semicolon).
1351     ///
1352     /// Headers must not be CRLF terminated. Many replaced headers have common
1353     /// shortcuts which should be prefered.
1354     ///
1355     /// By default this option is not set and corresponds to
1356     /// `CURLOPT_HTTPHEADER`
1357     ///
1358     /// # Examples
1359     ///
1360     /// ```
1361     /// use curl::easy::{Easy, List};
1362     ///
1363     /// let mut list = List::new();
1364     /// list.append("Foo: bar").unwrap();
1365     /// list.append("Bar: baz").unwrap();
1366     ///
1367     /// let mut handle = Easy::new();
1368     /// handle.url("https://www.rust-lang.org/").unwrap();
1369     /// handle.http_headers(list).unwrap();
1370     /// handle.perform().unwrap();
1371     /// ```
http_headers(&mut self, list: List) -> Result<(), Error>1372     pub fn http_headers(&mut self, list: List) -> Result<(), Error> {
1373         let ptr = list::raw(&list);
1374         self.inner.header_list = Some(list);
1375         self.setopt_ptr(curl_sys::CURLOPT_HTTPHEADER, ptr as *const _)
1376     }
1377 
1378     // /// Add some headers to send to the HTTP proxy.
1379     // ///
1380     // /// This function is essentially the same as `http_headers`.
1381     // ///
1382     // /// By default this option is not set and corresponds to
1383     // /// `CURLOPT_PROXYHEADER`
1384     // pub fn proxy_headers(&mut self, list: &'a List) -> Result<(), Error> {
1385     //     self.setopt_ptr(curl_sys::CURLOPT_PROXYHEADER, list.raw as *const _)
1386     // }
1387 
1388     /// Set the contents of the HTTP Cookie header.
1389     ///
1390     /// Pass a string of the form `name=contents` for one cookie value or
1391     /// `name1=val1; name2=val2` for multiple values.
1392     ///
1393     /// Using this option multiple times will only make the latest string
1394     /// override the previous ones. This option will not enable the cookie
1395     /// engine, use `cookie_file` or `cookie_jar` to do that.
1396     ///
1397     /// By default this option is not set and corresponds to `CURLOPT_COOKIE`.
cookie(&mut self, cookie: &str) -> Result<(), Error>1398     pub fn cookie(&mut self, cookie: &str) -> Result<(), Error> {
1399         let cookie = CString::new(cookie)?;
1400         self.setopt_str(curl_sys::CURLOPT_COOKIE, &cookie)
1401     }
1402 
1403     /// Set the file name to read cookies from.
1404     ///
1405     /// The cookie data can be in either the old Netscape / Mozilla cookie data
1406     /// format or just regular HTTP headers (Set-Cookie style) dumped to a file.
1407     ///
1408     /// This also enables the cookie engine, making libcurl parse and send
1409     /// cookies on subsequent requests with this handle.
1410     ///
1411     /// Given an empty or non-existing file or by passing the empty string ("")
1412     /// to this option, you can enable the cookie engine without reading any
1413     /// initial cookies.
1414     ///
1415     /// If you use this option multiple times, you just add more files to read.
1416     /// Subsequent files will add more cookies.
1417     ///
1418     /// By default this option is not set and corresponds to
1419     /// `CURLOPT_COOKIEFILE`.
cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>1420     pub fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> {
1421         self.setopt_path(curl_sys::CURLOPT_COOKIEFILE, file.as_ref())
1422     }
1423 
1424     /// Set the file name to store cookies to.
1425     ///
1426     /// This will make libcurl write all internally known cookies to the file
1427     /// when this handle is dropped. If no cookies are known, no file will be
1428     /// created. Specify "-" as filename to instead have the cookies written to
1429     /// stdout. Using this option also enables cookies for this session, so if
1430     /// you for example follow a location it will make matching cookies get sent
1431     /// accordingly.
1432     ///
1433     /// Note that libcurl doesn't read any cookies from the cookie jar. If you
1434     /// want to read cookies from a file, use `cookie_file`.
1435     ///
1436     /// By default this option is not set and corresponds to
1437     /// `CURLOPT_COOKIEJAR`.
cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>1438     pub fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> {
1439         self.setopt_path(curl_sys::CURLOPT_COOKIEJAR, file.as_ref())
1440     }
1441 
1442     /// Start a new cookie session
1443     ///
1444     /// Marks this as a new cookie "session". It will force libcurl to ignore
1445     /// all cookies it is about to load that are "session cookies" from the
1446     /// previous session. By default, libcurl always stores and loads all
1447     /// cookies, independent if they are session cookies or not. Session cookies
1448     /// are cookies without expiry date and they are meant to be alive and
1449     /// existing for this "session" only.
1450     ///
1451     /// By default this option is `false` and corresponds to
1452     /// `CURLOPT_COOKIESESSION`.
cookie_session(&mut self, session: bool) -> Result<(), Error>1453     pub fn cookie_session(&mut self, session: bool) -> Result<(), Error> {
1454         self.setopt_long(curl_sys::CURLOPT_COOKIESESSION, session as c_long)
1455     }
1456 
1457     /// Add to or manipulate cookies held in memory.
1458     ///
1459     /// Such a cookie can be either a single line in Netscape / Mozilla format
1460     /// or just regular HTTP-style header (Set-Cookie: ...) format. This will
1461     /// also enable the cookie engine. This adds that single cookie to the
1462     /// internal cookie store.
1463     ///
1464     /// Exercise caution if you are using this option and multiple transfers may
1465     /// occur. If you use the Set-Cookie format and don't specify a domain then
1466     /// the cookie is sent for any domain (even after redirects are followed)
1467     /// and cannot be modified by a server-set cookie. If a server sets a cookie
1468     /// of the same name (or maybe you've imported one) then both will be sent
1469     /// on a future transfer to that server, likely not what you intended.
1470     /// address these issues set a domain in Set-Cookie or use the Netscape
1471     /// format.
1472     ///
1473     /// Additionally, there are commands available that perform actions if you
1474     /// pass in these exact strings:
1475     ///
1476     /// * "ALL" - erases all cookies held in memory
1477     /// * "SESS" - erases all session cookies held in memory
1478     /// * "FLUSH" - write all known cookies to the specified cookie jar
1479     /// * "RELOAD" - reread all cookies from the cookie file
1480     ///
1481     /// By default this options corresponds to `CURLOPT_COOKIELIST`
cookie_list(&mut self, cookie: &str) -> Result<(), Error>1482     pub fn cookie_list(&mut self, cookie: &str) -> Result<(), Error> {
1483         let cookie = CString::new(cookie)?;
1484         self.setopt_str(curl_sys::CURLOPT_COOKIELIST, &cookie)
1485     }
1486 
1487     /// Ask for a HTTP GET request.
1488     ///
1489     /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`.
get(&mut self, enable: bool) -> Result<(), Error>1490     pub fn get(&mut self, enable: bool) -> Result<(), Error> {
1491         self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long)
1492     }
1493 
1494     // /// Ask for a HTTP GET request.
1495     // ///
1496     // /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`.
1497     // pub fn http_version(&mut self, vers: &str) -> Result<(), Error> {
1498     //     self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long)
1499     // }
1500 
1501     /// Ignore the content-length header.
1502     ///
1503     /// By default this option is `false` and corresponds to
1504     /// `CURLOPT_IGNORE_CONTENT_LENGTH`.
ignore_content_length(&mut self, ignore: bool) -> Result<(), Error>1505     pub fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error> {
1506         self.setopt_long(curl_sys::CURLOPT_IGNORE_CONTENT_LENGTH, ignore as c_long)
1507     }
1508 
1509     /// Enable or disable HTTP content decoding.
1510     ///
1511     /// By default this option is `true` and corresponds to
1512     /// `CURLOPT_HTTP_CONTENT_DECODING`.
http_content_decoding(&mut self, enable: bool) -> Result<(), Error>1513     pub fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error> {
1514         self.setopt_long(curl_sys::CURLOPT_HTTP_CONTENT_DECODING, enable as c_long)
1515     }
1516 
1517     /// Enable or disable HTTP transfer decoding.
1518     ///
1519     /// By default this option is `true` and corresponds to
1520     /// `CURLOPT_HTTP_TRANSFER_DECODING`.
http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error>1521     pub fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error> {
1522         self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, enable as c_long)
1523     }
1524 
1525     // /// Timeout for the Expect: 100-continue response
1526     // ///
1527     // /// By default this option is 1s and corresponds to
1528     // /// `CURLOPT_EXPECT_100_TIMEOUT_MS`.
1529     // pub fn expect_100_timeout(&mut self, enable: bool) -> Result<(), Error> {
1530     //     self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING,
1531     //                      enable as c_long)
1532     // }
1533 
1534     // /// Wait for pipelining/multiplexing.
1535     // ///
1536     // /// Tells libcurl to prefer to wait for a connection to confirm or deny that
1537     // /// it can do pipelining or multiplexing before continuing.
1538     // ///
1539     // /// When about to perform a new transfer that allows pipelining or
1540     // /// multiplexing, libcurl will check for existing connections to re-use and
1541     // /// pipeline on. If no such connection exists it will immediately continue
1542     // /// and create a fresh new connection to use.
1543     // ///
1544     // /// By setting this option to `true` - having `pipeline` enabled for the
1545     // /// multi handle this transfer is associated with - libcurl will instead
1546     // /// wait for the connection to reveal if it is possible to
1547     // /// pipeline/multiplex on before it continues. This enables libcurl to much
1548     // /// better keep the number of connections to a minimum when using pipelining
1549     // /// or multiplexing protocols.
1550     // ///
1551     // /// The effect thus becomes that with this option set, libcurl prefers to
1552     // /// wait and re-use an existing connection for pipelining rather than the
1553     // /// opposite: prefer to open a new connection rather than waiting.
1554     // ///
1555     // /// The waiting time is as long as it takes for the connection to get up and
1556     // /// for libcurl to get the necessary response back that informs it about its
1557     // /// protocol and support level.
1558     // pub fn http_pipewait(&mut self, enable: bool) -> Result<(), Error> {
1559     // }
1560 
1561     // =========================================================================
1562     // Protocol Options
1563 
1564     /// Indicates the range that this request should retrieve.
1565     ///
1566     /// The string provided should be of the form `N-M` where either `N` or `M`
1567     /// can be left out. For HTTP transfers multiple ranges separated by commas
1568     /// are also accepted.
1569     ///
1570     /// By default this option is not set and corresponds to `CURLOPT_RANGE`.
range(&mut self, range: &str) -> Result<(), Error>1571     pub fn range(&mut self, range: &str) -> Result<(), Error> {
1572         let range = CString::new(range)?;
1573         self.setopt_str(curl_sys::CURLOPT_RANGE, &range)
1574     }
1575 
1576     /// Set a point to resume transfer from
1577     ///
1578     /// Specify the offset in bytes you want the transfer to start from.
1579     ///
1580     /// By default this option is 0 and corresponds to
1581     /// `CURLOPT_RESUME_FROM_LARGE`.
resume_from(&mut self, from: u64) -> Result<(), Error>1582     pub fn resume_from(&mut self, from: u64) -> Result<(), Error> {
1583         self.setopt_off_t(
1584             curl_sys::CURLOPT_RESUME_FROM_LARGE,
1585             from as curl_sys::curl_off_t,
1586         )
1587     }
1588 
1589     /// Set a custom request string
1590     ///
1591     /// Specifies that a custom request will be made (e.g. a custom HTTP
1592     /// method). This does not change how libcurl performs internally, just
1593     /// changes the string sent to the server.
1594     ///
1595     /// By default this option is not set and corresponds to
1596     /// `CURLOPT_CUSTOMREQUEST`.
custom_request(&mut self, request: &str) -> Result<(), Error>1597     pub fn custom_request(&mut self, request: &str) -> Result<(), Error> {
1598         let request = CString::new(request)?;
1599         self.setopt_str(curl_sys::CURLOPT_CUSTOMREQUEST, &request)
1600     }
1601 
1602     /// Get the modification time of the remote resource
1603     ///
1604     /// If true, libcurl will attempt to get the modification time of the
1605     /// remote document in this operation. This requires that the remote server
1606     /// sends the time or replies to a time querying command. The `filetime`
1607     /// function can be used after a transfer to extract the received time (if
1608     /// any).
1609     ///
1610     /// By default this option is `false` and corresponds to `CURLOPT_FILETIME`
fetch_filetime(&mut self, fetch: bool) -> Result<(), Error>1611     pub fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error> {
1612         self.setopt_long(curl_sys::CURLOPT_FILETIME, fetch as c_long)
1613     }
1614 
1615     /// Indicate whether to download the request without getting the body
1616     ///
1617     /// This is useful, for example, for doing a HEAD request.
1618     ///
1619     /// By default this option is `false` and corresponds to `CURLOPT_NOBODY`.
nobody(&mut self, enable: bool) -> Result<(), Error>1620     pub fn nobody(&mut self, enable: bool) -> Result<(), Error> {
1621         self.setopt_long(curl_sys::CURLOPT_NOBODY, enable as c_long)
1622     }
1623 
1624     /// Set the size of the input file to send off.
1625     ///
1626     /// By default this option is not set and corresponds to
1627     /// `CURLOPT_INFILESIZE_LARGE`.
in_filesize(&mut self, size: u64) -> Result<(), Error>1628     pub fn in_filesize(&mut self, size: u64) -> Result<(), Error> {
1629         self.setopt_off_t(
1630             curl_sys::CURLOPT_INFILESIZE_LARGE,
1631             size as curl_sys::curl_off_t,
1632         )
1633     }
1634 
1635     /// Enable or disable data upload.
1636     ///
1637     /// This means that a PUT request will be made for HTTP and probably wants
1638     /// to be combined with the read callback as well as the `in_filesize`
1639     /// method.
1640     ///
1641     /// By default this option is `false` and corresponds to `CURLOPT_UPLOAD`.
upload(&mut self, enable: bool) -> Result<(), Error>1642     pub fn upload(&mut self, enable: bool) -> Result<(), Error> {
1643         self.setopt_long(curl_sys::CURLOPT_UPLOAD, enable as c_long)
1644     }
1645 
1646     /// Configure the maximum file size to download.
1647     ///
1648     /// By default this option is not set and corresponds to
1649     /// `CURLOPT_MAXFILESIZE_LARGE`.
max_filesize(&mut self, size: u64) -> Result<(), Error>1650     pub fn max_filesize(&mut self, size: u64) -> Result<(), Error> {
1651         self.setopt_off_t(
1652             curl_sys::CURLOPT_MAXFILESIZE_LARGE,
1653             size as curl_sys::curl_off_t,
1654         )
1655     }
1656 
1657     /// Selects a condition for a time request.
1658     ///
1659     /// This value indicates how the `time_value` option is interpreted.
1660     ///
1661     /// By default this option is not set and corresponds to
1662     /// `CURLOPT_TIMECONDITION`.
time_condition(&mut self, cond: TimeCondition) -> Result<(), Error>1663     pub fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error> {
1664         self.setopt_long(curl_sys::CURLOPT_TIMECONDITION, cond as c_long)
1665     }
1666 
1667     /// Sets the time value for a conditional request.
1668     ///
1669     /// The value here should be the number of seconds elapsed since January 1,
1670     /// 1970. To pass how to interpret this value, use `time_condition`.
1671     ///
1672     /// By default this option is not set and corresponds to
1673     /// `CURLOPT_TIMEVALUE`.
time_value(&mut self, val: i64) -> Result<(), Error>1674     pub fn time_value(&mut self, val: i64) -> Result<(), Error> {
1675         self.setopt_long(curl_sys::CURLOPT_TIMEVALUE, val as c_long)
1676     }
1677 
1678     // =========================================================================
1679     // Connection Options
1680 
1681     /// Set maximum time the request is allowed to take.
1682     ///
1683     /// Normally, name lookups can take a considerable time and limiting
1684     /// operations to less than a few minutes risk aborting perfectly normal
1685     /// operations.
1686     ///
1687     /// If libcurl is built to use the standard system name resolver, that
1688     /// portion of the transfer will still use full-second resolution for
1689     /// timeouts with a minimum timeout allowed of one second.
1690     ///
1691     /// In unix-like systems, this might cause signals to be used unless
1692     /// `nosignal` is set.
1693     ///
1694     /// Since this puts a hard limit for how long a request is allowed to
1695     /// take, it has limited use in dynamic use cases with varying transfer
1696     /// times. You are then advised to explore `low_speed_limit`,
1697     /// `low_speed_time` or using `progress_function` to implement your own
1698     /// timeout logic.
1699     ///
1700     /// By default this option is not set and corresponds to
1701     /// `CURLOPT_TIMEOUT_MS`.
timeout(&mut self, timeout: Duration) -> Result<(), Error>1702     pub fn timeout(&mut self, timeout: Duration) -> Result<(), Error> {
1703         // TODO: checked arithmetic and casts
1704         // TODO: use CURLOPT_TIMEOUT if the timeout is too great
1705         let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64;
1706         self.setopt_long(curl_sys::CURLOPT_TIMEOUT_MS, ms as c_long)
1707     }
1708 
1709     /// Set the low speed limit in bytes per second.
1710     ///
1711     /// This specifies the average transfer speed in bytes per second that the
1712     /// transfer should be below during `low_speed_time` for libcurl to consider
1713     /// it to be too slow and abort.
1714     ///
1715     /// By default this option is not set and corresponds to
1716     /// `CURLOPT_LOW_SPEED_LIMIT`.
low_speed_limit(&mut self, limit: u32) -> Result<(), Error>1717     pub fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error> {
1718         self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_LIMIT, limit as c_long)
1719     }
1720 
1721     /// Set the low speed time period.
1722     ///
1723     /// Specifies the window of time for which if the transfer rate is below
1724     /// `low_speed_limit` the request will be aborted.
1725     ///
1726     /// By default this option is not set and corresponds to
1727     /// `CURLOPT_LOW_SPEED_TIME`.
low_speed_time(&mut self, dur: Duration) -> Result<(), Error>1728     pub fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error> {
1729         self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_TIME, dur.as_secs() as c_long)
1730     }
1731 
1732     /// Rate limit data upload speed
1733     ///
1734     /// If an upload exceeds this speed (counted in bytes per second) on
1735     /// cumulative average during the transfer, the transfer will pause to keep
1736     /// the average rate less than or equal to the parameter value.
1737     ///
1738     /// By default this option is not set (unlimited speed) and corresponds to
1739     /// `CURLOPT_MAX_SEND_SPEED_LARGE`.
max_send_speed(&mut self, speed: u64) -> Result<(), Error>1740     pub fn max_send_speed(&mut self, speed: u64) -> Result<(), Error> {
1741         self.setopt_off_t(
1742             curl_sys::CURLOPT_MAX_SEND_SPEED_LARGE,
1743             speed as curl_sys::curl_off_t,
1744         )
1745     }
1746 
1747     /// Rate limit data download speed
1748     ///
1749     /// If a download exceeds this speed (counted in bytes per second) on
1750     /// cumulative average during the transfer, the transfer will pause to keep
1751     /// the average rate less than or equal to the parameter value.
1752     ///
1753     /// By default this option is not set (unlimited speed) and corresponds to
1754     /// `CURLOPT_MAX_RECV_SPEED_LARGE`.
max_recv_speed(&mut self, speed: u64) -> Result<(), Error>1755     pub fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error> {
1756         self.setopt_off_t(
1757             curl_sys::CURLOPT_MAX_RECV_SPEED_LARGE,
1758             speed as curl_sys::curl_off_t,
1759         )
1760     }
1761 
1762     /// Set the maximum connection cache size.
1763     ///
1764     /// The set amount will be the maximum number of simultaneously open
1765     /// persistent connections that libcurl may cache in the pool associated
1766     /// with this handle. The default is 5, and there isn't much point in
1767     /// changing this value unless you are perfectly aware of how this works and
1768     /// changes libcurl's behaviour. This concerns connections using any of the
1769     /// protocols that support persistent connections.
1770     ///
1771     /// When reaching the maximum limit, curl closes the oldest one in the cache
1772     /// to prevent increasing the number of open connections.
1773     ///
1774     /// By default this option is set to 5 and corresponds to
1775     /// `CURLOPT_MAXCONNECTS`
max_connects(&mut self, max: u32) -> Result<(), Error>1776     pub fn max_connects(&mut self, max: u32) -> Result<(), Error> {
1777         self.setopt_long(curl_sys::CURLOPT_MAXCONNECTS, max as c_long)
1778     }
1779 
1780     /// Force a new connection to be used.
1781     ///
1782     /// Makes the next transfer use a new (fresh) connection by force instead of
1783     /// trying to re-use an existing one. This option should be used with
1784     /// caution and only if you understand what it does as it may seriously
1785     /// impact performance.
1786     ///
1787     /// By default this option is `false` and corresponds to
1788     /// `CURLOPT_FRESH_CONNECT`.
fresh_connect(&mut self, enable: bool) -> Result<(), Error>1789     pub fn fresh_connect(&mut self, enable: bool) -> Result<(), Error> {
1790         self.setopt_long(curl_sys::CURLOPT_FRESH_CONNECT, enable as c_long)
1791     }
1792 
1793     /// Make connection get closed at once after use.
1794     ///
1795     /// Makes libcurl explicitly close the connection when done with the
1796     /// transfer. Normally, libcurl keeps all connections alive when done with
1797     /// one transfer in case a succeeding one follows that can re-use them.
1798     /// This option should be used with caution and only if you understand what
1799     /// it does as it can seriously impact performance.
1800     ///
1801     /// By default this option is `false` and corresponds to
1802     /// `CURLOPT_FORBID_REUSE`.
forbid_reuse(&mut self, enable: bool) -> Result<(), Error>1803     pub fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error> {
1804         self.setopt_long(curl_sys::CURLOPT_FORBID_REUSE, enable as c_long)
1805     }
1806 
1807     /// Timeout for the connect phase
1808     ///
1809     /// This is the maximum time that you allow the connection phase to the
1810     /// server to take. This only limits the connection phase, it has no impact
1811     /// once it has connected.
1812     ///
1813     /// By default this value is 300 seconds and corresponds to
1814     /// `CURLOPT_CONNECTTIMEOUT_MS`.
connect_timeout(&mut self, timeout: Duration) -> Result<(), Error>1815     pub fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error> {
1816         let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64;
1817         self.setopt_long(curl_sys::CURLOPT_CONNECTTIMEOUT_MS, ms as c_long)
1818     }
1819 
1820     /// Specify which IP protocol version to use
1821     ///
1822     /// Allows an application to select what kind of IP addresses to use when
1823     /// resolving host names. This is only interesting when using host names
1824     /// that resolve addresses using more than one version of IP.
1825     ///
1826     /// By default this value is "any" and corresponds to `CURLOPT_IPRESOLVE`.
ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error>1827     pub fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error> {
1828         self.setopt_long(curl_sys::CURLOPT_IPRESOLVE, resolve as c_long)
1829     }
1830 
1831     /// Specify custom host name to IP address resolves.
1832     ///
1833     /// Allows specifying hostname to IP mappins to use before trying the
1834     /// system resolver.
1835     ///
1836     /// # Examples
1837     ///
1838     /// ```no_run
1839     /// use curl::easy::{Easy, List};
1840     ///
1841     /// let mut list = List::new();
1842     /// list.append("www.rust-lang.org:443:185.199.108.153").unwrap();
1843     ///
1844     /// let mut handle = Easy::new();
1845     /// handle.url("https://www.rust-lang.org/").unwrap();
1846     /// handle.resolve(list).unwrap();
1847     /// handle.perform().unwrap();
1848     /// ```
resolve(&mut self, list: List) -> Result<(), Error>1849     pub fn resolve(&mut self, list: List) -> Result<(), Error> {
1850         let ptr = list::raw(&list);
1851         self.inner.resolve_list = Some(list);
1852         self.setopt_ptr(curl_sys::CURLOPT_RESOLVE, ptr as *const _)
1853     }
1854 
1855     /// Configure whether to stop when connected to target server
1856     ///
1857     /// When enabled it tells the library to perform all the required proxy
1858     /// authentication and connection setup, but no data transfer, and then
1859     /// return.
1860     ///
1861     /// The option can be used to simply test a connection to a server.
1862     ///
1863     /// By default this value is `false` and corresponds to
1864     /// `CURLOPT_CONNECT_ONLY`.
connect_only(&mut self, enable: bool) -> Result<(), Error>1865     pub fn connect_only(&mut self, enable: bool) -> Result<(), Error> {
1866         self.setopt_long(curl_sys::CURLOPT_CONNECT_ONLY, enable as c_long)
1867     }
1868 
1869     // /// Set interface to speak DNS over.
1870     // ///
1871     // /// Set the name of the network interface that the DNS resolver should bind
1872     // /// to. This must be an interface name (not an address).
1873     // ///
1874     // /// By default this option is not set and corresponds to
1875     // /// `CURLOPT_DNS_INTERFACE`.
1876     // pub fn dns_interface(&mut self, interface: &str) -> Result<(), Error> {
1877     //     let interface = CString::new(interface)?;
1878     //     self.setopt_str(curl_sys::CURLOPT_DNS_INTERFACE, &interface)
1879     // }
1880     //
1881     // /// IPv4 address to bind DNS resolves to
1882     // ///
1883     // /// Set the local IPv4 address that the resolver should bind to. The
1884     // /// argument should be of type char * and contain a single numerical IPv4
1885     // /// address as a string.
1886     // ///
1887     // /// By default this option is not set and corresponds to
1888     // /// `CURLOPT_DNS_LOCAL_IP4`.
1889     // pub fn dns_local_ip4(&mut self, ip: &str) -> Result<(), Error> {
1890     //     let ip = CString::new(ip)?;
1891     //     self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP4, &ip)
1892     // }
1893     //
1894     // /// IPv6 address to bind DNS resolves to
1895     // ///
1896     // /// Set the local IPv6 address that the resolver should bind to. The
1897     // /// argument should be of type char * and contain a single numerical IPv6
1898     // /// address as a string.
1899     // ///
1900     // /// By default this option is not set and corresponds to
1901     // /// `CURLOPT_DNS_LOCAL_IP6`.
1902     // pub fn dns_local_ip6(&mut self, ip: &str) -> Result<(), Error> {
1903     //     let ip = CString::new(ip)?;
1904     //     self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP6, &ip)
1905     // }
1906     //
1907     // /// Set preferred DNS servers.
1908     // ///
1909     // /// Provides a list of DNS servers to be used instead of the system default.
1910     // /// The format of the dns servers option is:
1911     // ///
1912     // /// ```text
1913     // /// host[:port],[host[:port]]...
1914     // /// ```
1915     // ///
1916     // /// By default this option is not set and corresponds to
1917     // /// `CURLOPT_DNS_SERVERS`.
1918     // pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> {
1919     //     let servers = CString::new(servers)?;
1920     //     self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &servers)
1921     // }
1922 
1923     // =========================================================================
1924     // SSL/Security Options
1925 
1926     /// Sets the SSL client certificate.
1927     ///
1928     /// The string should be the file name of your client certificate. The
1929     /// default format is "P12" on Secure Transport and "PEM" on other engines,
1930     /// and can be changed with `ssl_cert_type`.
1931     ///
1932     /// With NSS or Secure Transport, this can also be the nickname of the
1933     /// certificate you wish to authenticate with as it is named in the security
1934     /// database. If you want to use a file from the current directory, please
1935     /// precede it with "./" prefix, in order to avoid confusion with a
1936     /// nickname.
1937     ///
1938     /// When using a client certificate, you most likely also need to provide a
1939     /// private key with `ssl_key`.
1940     ///
1941     /// By default this option is not set and corresponds to `CURLOPT_SSLCERT`.
ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error>1942     pub fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error> {
1943         self.setopt_path(curl_sys::CURLOPT_SSLCERT, cert.as_ref())
1944     }
1945 
1946     /// Specify type of the client SSL certificate.
1947     ///
1948     /// The string should be the format of your certificate. Supported formats
1949     /// are "PEM" and "DER", except with Secure Transport. OpenSSL (versions
1950     /// 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7
1951     /// or later) also support "P12" for PKCS#12-encoded files.
1952     ///
1953     /// By default this option is "PEM" and corresponds to
1954     /// `CURLOPT_SSLCERTTYPE`.
ssl_cert_type(&mut self, kind: &str) -> Result<(), Error>1955     pub fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error> {
1956         let kind = CString::new(kind)?;
1957         self.setopt_str(curl_sys::CURLOPT_SSLCERTTYPE, &kind)
1958     }
1959 
1960     /// Specify private keyfile for TLS and SSL client cert.
1961     ///
1962     /// The string should be the file name of your private key. The default
1963     /// format is "PEM" and can be changed with `ssl_key_type`.
1964     ///
1965     /// (iOS and Mac OS X only) This option is ignored if curl was built against
1966     /// Secure Transport. Secure Transport expects the private key to be already
1967     /// present in the keychain or PKCS#12 file containing the certificate.
1968     ///
1969     /// By default this option is not set and corresponds to `CURLOPT_SSLKEY`.
ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error>1970     pub fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error> {
1971         self.setopt_path(curl_sys::CURLOPT_SSLKEY, key.as_ref())
1972     }
1973 
1974     /// Set type of the private key file.
1975     ///
1976     /// The string should be the format of your private key. Supported formats
1977     /// are "PEM", "DER" and "ENG".
1978     ///
1979     /// The format "ENG" enables you to load the private key from a crypto
1980     /// engine. In this case `ssl_key` is used as an identifier passed to
1981     /// the engine. You have to set the crypto engine with `ssl_engine`.
1982     /// "DER" format key file currently does not work because of a bug in
1983     /// OpenSSL.
1984     ///
1985     /// By default this option is "PEM" and corresponds to
1986     /// `CURLOPT_SSLKEYTYPE`.
ssl_key_type(&mut self, kind: &str) -> Result<(), Error>1987     pub fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error> {
1988         let kind = CString::new(kind)?;
1989         self.setopt_str(curl_sys::CURLOPT_SSLKEYTYPE, &kind)
1990     }
1991 
1992     /// Set passphrase to private key.
1993     ///
1994     /// This will be used as the password required to use the `ssl_key`.
1995     /// You never needed a pass phrase to load a certificate but you need one to
1996     /// load your private key.
1997     ///
1998     /// By default this option is not set and corresponds to
1999     /// `CURLOPT_KEYPASSWD`.
key_password(&mut self, password: &str) -> Result<(), Error>2000     pub fn key_password(&mut self, password: &str) -> Result<(), Error> {
2001         let password = CString::new(password)?;
2002         self.setopt_str(curl_sys::CURLOPT_KEYPASSWD, &password)
2003     }
2004 
2005     /// Set the SSL engine identifier.
2006     ///
2007     /// This will be used as the identifier for the crypto engine you want to
2008     /// use for your private key.
2009     ///
2010     /// By default this option is not set and corresponds to
2011     /// `CURLOPT_SSLENGINE`.
ssl_engine(&mut self, engine: &str) -> Result<(), Error>2012     pub fn ssl_engine(&mut self, engine: &str) -> Result<(), Error> {
2013         let engine = CString::new(engine)?;
2014         self.setopt_str(curl_sys::CURLOPT_SSLENGINE, &engine)
2015     }
2016 
2017     /// Make this handle's SSL engine the default.
2018     ///
2019     /// By default this option is not set and corresponds to
2020     /// `CURLOPT_SSLENGINE_DEFAULT`.
ssl_engine_default(&mut self, enable: bool) -> Result<(), Error>2021     pub fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error> {
2022         self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long)
2023     }
2024 
2025     // /// Enable TLS false start.
2026     // ///
2027     // /// This option determines whether libcurl should use false start during the
2028     // /// TLS handshake. False start is a mode where a TLS client will start
2029     // /// sending application data before verifying the server's Finished message,
2030     // /// thus saving a round trip when performing a full handshake.
2031     // ///
2032     // /// By default this option is not set and corresponds to
2033     // /// `CURLOPT_SSL_FALSESTARTE`.
2034     // pub fn ssl_false_start(&mut self, enable: bool) -> Result<(), Error> {
2035     //     self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long)
2036     // }
2037 
2038     /// Set preferred HTTP version.
2039     ///
2040     /// By default this option is not set and corresponds to
2041     /// `CURLOPT_HTTP_VERSION`.
http_version(&mut self, version: HttpVersion) -> Result<(), Error>2042     pub fn http_version(&mut self, version: HttpVersion) -> Result<(), Error> {
2043         self.setopt_long(curl_sys::CURLOPT_HTTP_VERSION, version as c_long)
2044     }
2045 
2046     /// Set preferred TLS/SSL version.
2047     ///
2048     /// By default this option is not set and corresponds to
2049     /// `CURLOPT_SSLVERSION`.
ssl_version(&mut self, version: SslVersion) -> Result<(), Error>2050     pub fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error> {
2051         self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version as c_long)
2052     }
2053 
2054     /// Set preferred TLS/SSL version with minimum version and maximum version.
2055     ///
2056     /// By default this option is not set and corresponds to
2057     /// `CURLOPT_SSLVERSION`.
ssl_min_max_version( &mut self, min_version: SslVersion, max_version: SslVersion, ) -> Result<(), Error>2058     pub fn ssl_min_max_version(
2059         &mut self,
2060         min_version: SslVersion,
2061         max_version: SslVersion,
2062     ) -> Result<(), Error> {
2063         let version = (min_version as c_long) | ((max_version as c_long) << 16);
2064         self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version)
2065     }
2066 
2067     /// Verify the certificate's name against host.
2068     ///
2069     /// This should be disabled with great caution! It basically disables the
2070     /// security features of SSL if it is disabled.
2071     ///
2072     /// By default this option is set to `true` and corresponds to
2073     /// `CURLOPT_SSL_VERIFYHOST`.
ssl_verify_host(&mut self, verify: bool) -> Result<(), Error>2074     pub fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> {
2075         let val = if verify { 2 } else { 0 };
2076         self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYHOST, val)
2077     }
2078 
2079     /// Verify the peer's SSL certificate.
2080     ///
2081     /// This should be disabled with great caution! It basically disables the
2082     /// security features of SSL if it is disabled.
2083     ///
2084     /// By default this option is set to `true` and corresponds to
2085     /// `CURLOPT_SSL_VERIFYPEER`.
ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error>2086     pub fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> {
2087         self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYPEER, verify as c_long)
2088     }
2089 
2090     // /// Verify the certificate's status.
2091     // ///
2092     // /// This option determines whether libcurl verifies the status of the server
2093     // /// cert using the "Certificate Status Request" TLS extension (aka. OCSP
2094     // /// stapling).
2095     // ///
2096     // /// By default this option is set to `false` and corresponds to
2097     // /// `CURLOPT_SSL_VERIFYSTATUS`.
2098     // pub fn ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> {
2099     //     self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYSTATUS, verify as c_long)
2100     // }
2101 
2102     /// Specify the path to Certificate Authority (CA) bundle
2103     ///
2104     /// The file referenced should hold one or more certificates to verify the
2105     /// peer with.
2106     ///
2107     /// This option is by default set to the system path where libcurl's cacert
2108     /// bundle is assumed to be stored, as established at build time.
2109     ///
2110     /// If curl is built against the NSS SSL library, the NSS PEM PKCS#11 module
2111     /// (libnsspem.so) needs to be available for this option to work properly.
2112     ///
2113     /// By default this option is the system defaults, and corresponds to
2114     /// `CURLOPT_CAINFO`.
cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2115     pub fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2116         self.setopt_path(curl_sys::CURLOPT_CAINFO, path.as_ref())
2117     }
2118 
2119     /// Set the issuer SSL certificate filename
2120     ///
2121     /// Specifies a file holding a CA certificate in PEM format. If the option
2122     /// is set, an additional check against the peer certificate is performed to
2123     /// verify the issuer is indeed the one associated with the certificate
2124     /// provided by the option. This additional check is useful in multi-level
2125     /// PKI where one needs to enforce that the peer certificate is from a
2126     /// specific branch of the tree.
2127     ///
2128     /// This option makes sense only when used in combination with the
2129     /// `ssl_verify_peer` option. Otherwise, the result of the check is not
2130     /// considered as failure.
2131     ///
2132     /// By default this option is not set and corresponds to
2133     /// `CURLOPT_ISSUERCERT`.
issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2134     pub fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2135         self.setopt_path(curl_sys::CURLOPT_ISSUERCERT, path.as_ref())
2136     }
2137 
2138     /// Specify directory holding CA certificates
2139     ///
2140     /// Names a directory holding multiple CA certificates to verify the peer
2141     /// with. If libcurl is built against OpenSSL, the certificate directory
2142     /// must be prepared using the openssl c_rehash utility. This makes sense
2143     /// only when used in combination with the `ssl_verify_peer` option.
2144     ///
2145     /// By default this option is not set and corresponds to `CURLOPT_CAPATH`.
capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2146     pub fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2147         self.setopt_path(curl_sys::CURLOPT_CAPATH, path.as_ref())
2148     }
2149 
2150     /// Specify a Certificate Revocation List file
2151     ///
2152     /// Names a file with the concatenation of CRL (in PEM format) to use in the
2153     /// certificate validation that occurs during the SSL exchange.
2154     ///
2155     /// When curl is built to use NSS or GnuTLS, there is no way to influence
2156     /// the use of CRL passed to help in the verification process. When libcurl
2157     /// is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and
2158     /// X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all
2159     /// the elements of the certificate chain if a CRL file is passed.
2160     ///
2161     /// This option makes sense only when used in combination with the
2162     /// `ssl_verify_peer` option.
2163     ///
2164     /// A specific error code (`is_ssl_crl_badfile`) is defined with the
2165     /// option. It is returned when the SSL exchange fails because the CRL file
2166     /// cannot be loaded. A failure in certificate verification due to a
2167     /// revocation information found in the CRL does not trigger this specific
2168     /// error.
2169     ///
2170     /// By default this option is not set and corresponds to `CURLOPT_CRLFILE`.
crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2171     pub fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2172         self.setopt_path(curl_sys::CURLOPT_CRLFILE, path.as_ref())
2173     }
2174 
2175     /// Request SSL certificate information
2176     ///
2177     /// Enable libcurl's certificate chain info gatherer. With this enabled,
2178     /// libcurl will extract lots of information and data about the certificates
2179     /// in the certificate chain used in the SSL connection.
2180     ///
2181     /// By default this option is `false` and corresponds to
2182     /// `CURLOPT_CERTINFO`.
certinfo(&mut self, enable: bool) -> Result<(), Error>2183     pub fn certinfo(&mut self, enable: bool) -> Result<(), Error> {
2184         self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long)
2185     }
2186 
2187     // /// Set pinned public key.
2188     // ///
2189     // /// Pass a pointer to a zero terminated string as parameter. The string can
2190     // /// be the file name of your pinned public key. The file format expected is
2191     // /// "PEM" or "DER". The string can also be any number of base64 encoded
2192     // /// sha256 hashes preceded by "sha256//" and separated by ";"
2193     // ///
2194     // /// When negotiating a TLS or SSL connection, the server sends a certificate
2195     // /// indicating its identity. A public key is extracted from this certificate
2196     // /// and if it does not exactly match the public key provided to this option,
2197     // /// curl will abort the connection before sending or receiving any data.
2198     // ///
2199     // /// By default this option is not set and corresponds to
2200     // /// `CURLOPT_PINNEDPUBLICKEY`.
2201     // pub fn pinned_public_key(&mut self, enable: bool) -> Result<(), Error> {
2202     //     self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long)
2203     // }
2204 
2205     /// Specify a source for random data
2206     ///
2207     /// The file will be used to read from to seed the random engine for SSL and
2208     /// more.
2209     ///
2210     /// By default this option is not set and corresponds to
2211     /// `CURLOPT_RANDOM_FILE`.
random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>2212     pub fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> {
2213         self.setopt_path(curl_sys::CURLOPT_RANDOM_FILE, p.as_ref())
2214     }
2215 
2216     /// Specify EGD socket path.
2217     ///
2218     /// Indicates the path name to the Entropy Gathering Daemon socket. It will
2219     /// be used to seed the random engine for SSL.
2220     ///
2221     /// By default this option is not set and corresponds to
2222     /// `CURLOPT_EGDSOCKET`.
egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>2223     pub fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> {
2224         self.setopt_path(curl_sys::CURLOPT_EGDSOCKET, p.as_ref())
2225     }
2226 
2227     /// Specify ciphers to use for TLS.
2228     ///
2229     /// Holds the list of ciphers to use for the SSL connection. The list must
2230     /// be syntactically correct, it consists of one or more cipher strings
2231     /// separated by colons. Commas or spaces are also acceptable separators
2232     /// but colons are normally used, !, - and + can be used as operators.
2233     ///
2234     /// For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA',
2235     /// ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when
2236     /// you compile OpenSSL.
2237     ///
2238     /// You'll find more details about cipher lists on this URL:
2239     ///
2240     /// https://www.openssl.org/docs/apps/ciphers.html
2241     ///
2242     /// For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5',
2243     /// ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one
2244     /// uses this option then all known ciphers are disabled and only those
2245     /// passed in are enabled.
2246     ///
2247     /// You'll find more details about the NSS cipher lists on this URL:
2248     ///
2249     /// http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives
2250     ///
2251     /// By default this option is not set and corresponds to
2252     /// `CURLOPT_SSL_CIPHER_LIST`.
ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error>2253     pub fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> {
2254         let ciphers = CString::new(ciphers)?;
2255         self.setopt_str(curl_sys::CURLOPT_SSL_CIPHER_LIST, &ciphers)
2256     }
2257 
2258     /// Enable or disable use of the SSL session-ID cache
2259     ///
2260     /// By default all transfers are done using the cache enabled. While nothing
2261     /// ever should get hurt by attempting to reuse SSL session-IDs, there seem
2262     /// to be or have been broken SSL implementations in the wild that may
2263     /// require you to disable this in order for you to succeed.
2264     ///
2265     /// This corresponds to the `CURLOPT_SSL_SESSIONID_CACHE` option.
ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error>2266     pub fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error> {
2267         self.setopt_long(curl_sys::CURLOPT_SSL_SESSIONID_CACHE, enable as c_long)
2268     }
2269 
2270     /// Set SSL behavior options
2271     ///
2272     /// Inform libcurl about SSL specific behaviors.
2273     ///
2274     /// This corresponds to the `CURLOPT_SSL_OPTIONS` option.
ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error>2275     pub fn ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> {
2276         self.setopt_long(curl_sys::CURLOPT_SSL_OPTIONS, bits.bits)
2277     }
2278 
2279     // /// Set SSL behavior options for proxies
2280     // ///
2281     // /// Inform libcurl about SSL specific behaviors.
2282     // ///
2283     // /// This corresponds to the `CURLOPT_PROXY_SSL_OPTIONS` option.
2284     // pub fn proxy_ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> {
2285     //     self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_OPTIONS, bits.bits)
2286     // }
2287 
2288     // /// Stores a private pointer-sized piece of data.
2289     // ///
2290     // /// This can be retrieved through the `private` function and otherwise
2291     // /// libcurl does not tamper with this value. This corresponds to
2292     // /// `CURLOPT_PRIVATE` and defaults to 0.
2293     // pub fn set_private(&mut self, private: usize) -> Result<(), Error> {
2294     //     self.setopt_ptr(curl_sys::CURLOPT_PRIVATE, private as *const _)
2295     // }
2296     //
2297     // /// Fetches this handle's private pointer-sized piece of data.
2298     // ///
2299     // /// This corresponds to `CURLINFO_PRIVATE` and defaults to 0.
2300     // pub fn private(&mut self) -> Result<usize, Error> {
2301     //     self.getopt_ptr(curl_sys::CURLINFO_PRIVATE).map(|p| p as usize)
2302     // }
2303 
2304     // =========================================================================
2305     // getters
2306 
2307     /// Get info on unmet time conditional
2308     ///
2309     /// Returns if the condition provided in the previous request didn't match
2310     ///
2311     //// This corresponds to `CURLINFO_CONDITION_UNMET` and may return an error if the
2312     /// option is not supported
time_condition_unmet(&mut self) -> Result<bool, Error>2313     pub fn time_condition_unmet(&mut self) -> Result<bool, Error> {
2314         self.getopt_long(curl_sys::CURLINFO_CONDITION_UNMET).map(
2315             |r| {
2316                 if r == 0 {
2317                     false
2318                 } else {
2319                     true
2320                 }
2321             },
2322         )
2323     }
2324 
2325     /// Get the last used URL
2326     ///
2327     /// In cases when you've asked libcurl to follow redirects, it may
2328     /// not be the same value you set with `url`.
2329     ///
2330     /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option.
2331     ///
2332     /// Returns `Ok(None)` if no effective url is listed or `Err` if an error
2333     /// happens or the underlying bytes aren't valid utf-8.
effective_url(&mut self) -> Result<Option<&str>, Error>2334     pub fn effective_url(&mut self) -> Result<Option<&str>, Error> {
2335         self.getopt_str(curl_sys::CURLINFO_EFFECTIVE_URL)
2336     }
2337 
2338     /// Get the last used URL, in bytes
2339     ///
2340     /// In cases when you've asked libcurl to follow redirects, it may
2341     /// not be the same value you set with `url`.
2342     ///
2343     /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option.
2344     ///
2345     /// Returns `Ok(None)` if no effective url is listed or `Err` if an error
2346     /// happens or the underlying bytes aren't valid utf-8.
effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>2347     pub fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2348         self.getopt_bytes(curl_sys::CURLINFO_EFFECTIVE_URL)
2349     }
2350 
2351     /// Get the last response code
2352     ///
2353     /// The stored value will be zero if no server response code has been
2354     /// received. Note that a proxy's CONNECT response should be read with
2355     /// `http_connectcode` and not this.
2356     ///
2357     /// Corresponds to `CURLINFO_RESPONSE_CODE` and returns an error if this
2358     /// option is not supported.
response_code(&mut self) -> Result<u32, Error>2359     pub fn response_code(&mut self) -> Result<u32, Error> {
2360         self.getopt_long(curl_sys::CURLINFO_RESPONSE_CODE)
2361             .map(|c| c as u32)
2362     }
2363 
2364     /// Get the CONNECT response code
2365     ///
2366     /// Returns the last received HTTP proxy response code to a CONNECT request.
2367     /// The returned value will be zero if no such response code was available.
2368     ///
2369     /// Corresponds to `CURLINFO_HTTP_CONNECTCODE` and returns an error if this
2370     /// option is not supported.
http_connectcode(&mut self) -> Result<u32, Error>2371     pub fn http_connectcode(&mut self) -> Result<u32, Error> {
2372         self.getopt_long(curl_sys::CURLINFO_HTTP_CONNECTCODE)
2373             .map(|c| c as u32)
2374     }
2375 
2376     /// Get the remote time of the retrieved document
2377     ///
2378     /// Returns the remote time of the retrieved document (in number of seconds
2379     /// since 1 Jan 1970 in the GMT/UTC time zone). If you get `None`, it can be
2380     /// because of many reasons (it might be unknown, the server might hide it
2381     /// or the server doesn't support the command that tells document time etc)
2382     /// and the time of the document is unknown.
2383     ///
2384     /// Note that you must tell the server to collect this information before
2385     /// the transfer is made, by using the `filetime` method to
2386     /// or you will unconditionally get a `None` back.
2387     ///
2388     /// This corresponds to `CURLINFO_FILETIME` and may return an error if the
2389     /// option is not supported
filetime(&mut self) -> Result<Option<i64>, Error>2390     pub fn filetime(&mut self) -> Result<Option<i64>, Error> {
2391         self.getopt_long(curl_sys::CURLINFO_FILETIME).map(|r| {
2392             if r == -1 {
2393                 None
2394             } else {
2395                 Some(r as i64)
2396             }
2397         })
2398     }
2399 
2400     /// Get the number of downloaded bytes
2401     ///
2402     /// Returns the total amount of bytes that were downloaded.
2403     /// The amount is only for the latest transfer and will be reset again for each new transfer.
2404     /// This counts actual payload data, what's also commonly called body.
2405     /// All meta and header data are excluded and will not be counted in this number.
2406     ///
2407     /// This corresponds to `CURLINFO_SIZE_DOWNLOAD` and may return an error if the
2408     /// option is not supported
download_size(&mut self) -> Result<f64, Error>2409     pub fn download_size(&mut self) -> Result<f64, Error> {
2410         self.getopt_double(curl_sys::CURLINFO_SIZE_DOWNLOAD)
2411             .map(|r| r as f64)
2412     }
2413 
2414     /// Get the content-length of the download
2415     ///
2416     /// Returns the content-length of the download.
2417     /// This is the value read from the Content-Length: field
2418     ///
2419     /// This corresponds to `CURLINFO_CONTENT_LENGTH_DOWNLOAD` and may return an error if the
2420     /// option is not supported
content_length_download(&mut self) -> Result<f64, Error>2421     pub fn content_length_download(&mut self) -> Result<f64, Error> {
2422         self.getopt_double(curl_sys::CURLINFO_CONTENT_LENGTH_DOWNLOAD)
2423             .map(|r| r as f64)
2424     }
2425 
2426     /// Get total time of previous transfer
2427     ///
2428     /// Returns the total time for the previous transfer,
2429     /// including name resolving, TCP connect etc.
2430     ///
2431     /// Corresponds to `CURLINFO_TOTAL_TIME` and may return an error if the
2432     /// option isn't supported.
total_time(&mut self) -> Result<Duration, Error>2433     pub fn total_time(&mut self) -> Result<Duration, Error> {
2434         self.getopt_double(curl_sys::CURLINFO_TOTAL_TIME)
2435             .map(double_seconds_to_duration)
2436     }
2437 
2438     /// Get the name lookup time
2439     ///
2440     /// Returns the total time from the start
2441     /// until the name resolving was completed.
2442     ///
2443     /// Corresponds to `CURLINFO_NAMELOOKUP_TIME` and may return an error if the
2444     /// option isn't supported.
namelookup_time(&mut self) -> Result<Duration, Error>2445     pub fn namelookup_time(&mut self) -> Result<Duration, Error> {
2446         self.getopt_double(curl_sys::CURLINFO_NAMELOOKUP_TIME)
2447             .map(double_seconds_to_duration)
2448     }
2449 
2450     /// Get the time until connect
2451     ///
2452     /// Returns the total time from the start
2453     /// until the connection to the remote host (or proxy) was completed.
2454     ///
2455     /// Corresponds to `CURLINFO_CONNECT_TIME` and may return an error if the
2456     /// option isn't supported.
connect_time(&mut self) -> Result<Duration, Error>2457     pub fn connect_time(&mut self) -> Result<Duration, Error> {
2458         self.getopt_double(curl_sys::CURLINFO_CONNECT_TIME)
2459             .map(double_seconds_to_duration)
2460     }
2461 
2462     /// Get the time until the SSL/SSH handshake is completed
2463     ///
2464     /// Returns the total time it took from the start until the SSL/SSH
2465     /// connect/handshake to the remote host was completed. This time is most often
2466     /// very near to the `pretransfer_time` time, except for cases such as
2467     /// HTTP pipelining where the pretransfer time can be delayed due to waits in
2468     /// line for the pipeline and more.
2469     ///
2470     /// Corresponds to `CURLINFO_APPCONNECT_TIME` and may return an error if the
2471     /// option isn't supported.
appconnect_time(&mut self) -> Result<Duration, Error>2472     pub fn appconnect_time(&mut self) -> Result<Duration, Error> {
2473         self.getopt_double(curl_sys::CURLINFO_APPCONNECT_TIME)
2474             .map(double_seconds_to_duration)
2475     }
2476 
2477     /// Get the time until the file transfer start
2478     ///
2479     /// Returns the total time it took from the start until the file
2480     /// transfer is just about to begin. This includes all pre-transfer commands
2481     /// and negotiations that are specific to the particular protocol(s) involved.
2482     /// It does not involve the sending of the protocol- specific request that
2483     /// triggers a transfer.
2484     ///
2485     /// Corresponds to `CURLINFO_PRETRANSFER_TIME` and may return an error if the
2486     /// option isn't supported.
pretransfer_time(&mut self) -> Result<Duration, Error>2487     pub fn pretransfer_time(&mut self) -> Result<Duration, Error> {
2488         self.getopt_double(curl_sys::CURLINFO_PRETRANSFER_TIME)
2489             .map(double_seconds_to_duration)
2490     }
2491 
2492     /// Get the time until the first byte is received
2493     ///
2494     /// Returns the total time it took from the start until the first
2495     /// byte is received by libcurl. This includes `pretransfer_time` and
2496     /// also the time the server needs to calculate the result.
2497     ///
2498     /// Corresponds to `CURLINFO_STARTTRANSFER_TIME` and may return an error if the
2499     /// option isn't supported.
starttransfer_time(&mut self) -> Result<Duration, Error>2500     pub fn starttransfer_time(&mut self) -> Result<Duration, Error> {
2501         self.getopt_double(curl_sys::CURLINFO_STARTTRANSFER_TIME)
2502             .map(double_seconds_to_duration)
2503     }
2504 
2505     /// Get the time for all redirection steps
2506     ///
2507     /// Returns the total time it took for all redirection steps
2508     /// include name lookup, connect, pretransfer and transfer before final
2509     /// transaction was started. `redirect_time` contains the complete
2510     /// execution time for multiple redirections.
2511     ///
2512     /// Corresponds to `CURLINFO_REDIRECT_TIME` and may return an error if the
2513     /// option isn't supported.
redirect_time(&mut self) -> Result<Duration, Error>2514     pub fn redirect_time(&mut self) -> Result<Duration, Error> {
2515         self.getopt_double(curl_sys::CURLINFO_REDIRECT_TIME)
2516             .map(double_seconds_to_duration)
2517     }
2518 
2519     /// Get the number of redirects
2520     ///
2521     /// Corresponds to `CURLINFO_REDIRECT_COUNT` and may return an error if the
2522     /// option isn't supported.
redirect_count(&mut self) -> Result<u32, Error>2523     pub fn redirect_count(&mut self) -> Result<u32, Error> {
2524         self.getopt_long(curl_sys::CURLINFO_REDIRECT_COUNT)
2525             .map(|c| c as u32)
2526     }
2527 
2528     /// Get the URL a redirect would go to
2529     ///
2530     /// Returns the URL a redirect would take you to if you would enable
2531     /// `follow_location`. This can come very handy if you think using the
2532     /// built-in libcurl redirect logic isn't good enough for you but you would
2533     /// still prefer to avoid implementing all the magic of figuring out the new
2534     /// URL.
2535     ///
2536     /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error if the
2537     /// url isn't valid utf-8 or an error happens.
redirect_url(&mut self) -> Result<Option<&str>, Error>2538     pub fn redirect_url(&mut self) -> Result<Option<&str>, Error> {
2539         self.getopt_str(curl_sys::CURLINFO_REDIRECT_URL)
2540     }
2541 
2542     /// Get the URL a redirect would go to, in bytes
2543     ///
2544     /// Returns the URL a redirect would take you to if you would enable
2545     /// `follow_location`. This can come very handy if you think using the
2546     /// built-in libcurl redirect logic isn't good enough for you but you would
2547     /// still prefer to avoid implementing all the magic of figuring out the new
2548     /// URL.
2549     ///
2550     /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error.
redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>2551     pub fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2552         self.getopt_bytes(curl_sys::CURLINFO_REDIRECT_URL)
2553     }
2554 
2555     /// Get size of retrieved headers
2556     ///
2557     /// Corresponds to `CURLINFO_HEADER_SIZE` and may return an error if the
2558     /// option isn't supported.
header_size(&mut self) -> Result<u64, Error>2559     pub fn header_size(&mut self) -> Result<u64, Error> {
2560         self.getopt_long(curl_sys::CURLINFO_HEADER_SIZE)
2561             .map(|c| c as u64)
2562     }
2563 
2564     /// Get size of sent request.
2565     ///
2566     /// Corresponds to `CURLINFO_REQUEST_SIZE` and may return an error if the
2567     /// option isn't supported.
request_size(&mut self) -> Result<u64, Error>2568     pub fn request_size(&mut self) -> Result<u64, Error> {
2569         self.getopt_long(curl_sys::CURLINFO_REQUEST_SIZE)
2570             .map(|c| c as u64)
2571     }
2572 
2573     /// Get Content-Type
2574     ///
2575     /// Returns the content-type of the downloaded object. This is the value
2576     /// read from the Content-Type: field.  If you get `None`, it means that the
2577     /// server didn't send a valid Content-Type header or that the protocol
2578     /// used doesn't support this.
2579     ///
2580     /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the
2581     /// option isn't supported.
content_type(&mut self) -> Result<Option<&str>, Error>2582     pub fn content_type(&mut self) -> Result<Option<&str>, Error> {
2583         self.getopt_str(curl_sys::CURLINFO_CONTENT_TYPE)
2584     }
2585 
2586     /// Get Content-Type, in bytes
2587     ///
2588     /// Returns the content-type of the downloaded object. This is the value
2589     /// read from the Content-Type: field.  If you get `None`, it means that the
2590     /// server didn't send a valid Content-Type header or that the protocol
2591     /// used doesn't support this.
2592     ///
2593     /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the
2594     /// option isn't supported.
content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error>2595     pub fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2596         self.getopt_bytes(curl_sys::CURLINFO_CONTENT_TYPE)
2597     }
2598 
2599     /// Get errno number from last connect failure.
2600     ///
2601     /// Note that the value is only set on failure, it is not reset upon a
2602     /// successful operation. The number is OS and system specific.
2603     ///
2604     /// Corresponds to `CURLINFO_OS_ERRNO` and may return an error if the
2605     /// option isn't supported.
os_errno(&mut self) -> Result<i32, Error>2606     pub fn os_errno(&mut self) -> Result<i32, Error> {
2607         self.getopt_long(curl_sys::CURLINFO_OS_ERRNO)
2608             .map(|c| c as i32)
2609     }
2610 
2611     /// Get IP address of last connection.
2612     ///
2613     /// Returns a string holding the IP address of the most recent connection
2614     /// done with this curl handle. This string may be IPv6 when that is
2615     /// enabled.
2616     ///
2617     /// Corresponds to `CURLINFO_PRIMARY_IP` and may return an error if the
2618     /// option isn't supported.
primary_ip(&mut self) -> Result<Option<&str>, Error>2619     pub fn primary_ip(&mut self) -> Result<Option<&str>, Error> {
2620         self.getopt_str(curl_sys::CURLINFO_PRIMARY_IP)
2621     }
2622 
2623     /// Get the latest destination port number
2624     ///
2625     /// Corresponds to `CURLINFO_PRIMARY_PORT` and may return an error if the
2626     /// option isn't supported.
primary_port(&mut self) -> Result<u16, Error>2627     pub fn primary_port(&mut self) -> Result<u16, Error> {
2628         self.getopt_long(curl_sys::CURLINFO_PRIMARY_PORT)
2629             .map(|c| c as u16)
2630     }
2631 
2632     /// Get local IP address of last connection
2633     ///
2634     /// Returns a string holding the IP address of the local end of most recent
2635     /// connection done with this curl handle. This string may be IPv6 when that
2636     /// is enabled.
2637     ///
2638     /// Corresponds to `CURLINFO_LOCAL_IP` and may return an error if the
2639     /// option isn't supported.
local_ip(&mut self) -> Result<Option<&str>, Error>2640     pub fn local_ip(&mut self) -> Result<Option<&str>, Error> {
2641         self.getopt_str(curl_sys::CURLINFO_LOCAL_IP)
2642     }
2643 
2644     /// Get the latest local port number
2645     ///
2646     /// Corresponds to `CURLINFO_LOCAL_PORT` and may return an error if the
2647     /// option isn't supported.
local_port(&mut self) -> Result<u16, Error>2648     pub fn local_port(&mut self) -> Result<u16, Error> {
2649         self.getopt_long(curl_sys::CURLINFO_LOCAL_PORT)
2650             .map(|c| c as u16)
2651     }
2652 
2653     /// Get all known cookies
2654     ///
2655     /// Returns a linked-list of all cookies cURL knows (expired ones, too).
2656     ///
2657     /// Corresponds to the `CURLINFO_COOKIELIST` option and may return an error
2658     /// if the option isn't supported.
cookies(&mut self) -> Result<List, Error>2659     pub fn cookies(&mut self) -> Result<List, Error> {
2660         unsafe {
2661             let mut list = 0 as *mut _;
2662             let rc = curl_sys::curl_easy_getinfo(
2663                 self.inner.handle,
2664                 curl_sys::CURLINFO_COOKIELIST,
2665                 &mut list,
2666             );
2667             self.cvt(rc)?;
2668             Ok(list::from_raw(list))
2669         }
2670     }
2671 
2672     /// Wait for pipelining/multiplexing
2673     ///
2674     /// Set wait to `true` to tell libcurl to prefer to wait for a connection to
2675     /// confirm or deny that it can do pipelining or multiplexing before
2676     /// continuing.
2677     ///
2678     /// When about to perform a new transfer that allows pipelining or
2679     /// multiplexing, libcurl will check for existing connections to re-use and
2680     /// pipeline on. If no such connection exists it will immediately continue
2681     /// and create a fresh new connection to use.
2682     ///
2683     /// By setting this option to `true` - and having `pipelining(true, true)`
2684     /// enabled for the multi handle this transfer is associated with - libcurl
2685     /// will instead wait for the connection to reveal if it is possible to
2686     /// pipeline/multiplex on before it continues. This enables libcurl to much
2687     /// better keep the number of connections to a minimum when using pipelining
2688     /// or multiplexing protocols.
2689     ///
2690     /// The effect thus becomes that with this option set, libcurl prefers to
2691     /// wait and re-use an existing connection for pipelining rather than the
2692     /// opposite: prefer to open a new connection rather than waiting.
2693     ///
2694     /// The waiting time is as long as it takes for the connection to get up and
2695     /// for libcurl to get the necessary response back that informs it about its
2696     /// protocol and support level.
2697     ///
2698     /// This corresponds to the `CURLOPT_PIPEWAIT` option.
pipewait(&mut self, wait: bool) -> Result<(), Error>2699     pub fn pipewait(&mut self, wait: bool) -> Result<(), Error> {
2700         self.setopt_long(curl_sys::CURLOPT_PIPEWAIT, wait as c_long)
2701     }
2702 
2703     // =========================================================================
2704     // Other methods
2705 
2706     /// After options have been set, this will perform the transfer described by
2707     /// the options.
2708     ///
2709     /// This performs the request in a synchronous fashion. This can be used
2710     /// multiple times for one easy handle and libcurl will attempt to re-use
2711     /// the same connection for all transfers.
2712     ///
2713     /// This method will preserve all options configured in this handle for the
2714     /// next request, and if that is not desired then the options can be
2715     /// manually reset or the `reset` method can be called.
2716     ///
2717     /// Note that this method takes `&self`, which is quite important! This
2718     /// allows applications to close over the handle in various callbacks to
2719     /// call methods like `unpause_write` and `unpause_read` while a transfer is
2720     /// in progress.
perform(&self) -> Result<(), Error>2721     pub fn perform(&self) -> Result<(), Error> {
2722         let ret = unsafe { self.cvt(curl_sys::curl_easy_perform(self.inner.handle)) };
2723         panic::propagate();
2724         return ret;
2725     }
2726 
2727     /// Unpause reading on a connection.
2728     ///
2729     /// Using this function, you can explicitly unpause a connection that was
2730     /// previously paused.
2731     ///
2732     /// A connection can be paused by letting the read or the write callbacks
2733     /// return `ReadError::Pause` or `WriteError::Pause`.
2734     ///
2735     /// To unpause, you may for example call this from the progress callback
2736     /// which gets called at least once per second, even if the connection is
2737     /// paused.
2738     ///
2739     /// The chance is high that you will get your write callback called before
2740     /// this function returns.
unpause_read(&self) -> Result<(), Error>2741     pub fn unpause_read(&self) -> Result<(), Error> {
2742         unsafe {
2743             let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_RECV_CONT);
2744             self.cvt(rc)
2745         }
2746     }
2747 
2748     /// Unpause writing on a connection.
2749     ///
2750     /// Using this function, you can explicitly unpause a connection that was
2751     /// previously paused.
2752     ///
2753     /// A connection can be paused by letting the read or the write callbacks
2754     /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that
2755     /// returns pause signals to the library that it couldn't take care of any
2756     /// data at all, and that data will then be delivered again to the callback
2757     /// when the writing is later unpaused.
2758     ///
2759     /// To unpause, you may for example call this from the progress callback
2760     /// which gets called at least once per second, even if the connection is
2761     /// paused.
unpause_write(&self) -> Result<(), Error>2762     pub fn unpause_write(&self) -> Result<(), Error> {
2763         unsafe {
2764             let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_SEND_CONT);
2765             self.cvt(rc)
2766         }
2767     }
2768 
2769     /// URL encodes a string `s`
url_encode(&mut self, s: &[u8]) -> String2770     pub fn url_encode(&mut self, s: &[u8]) -> String {
2771         if s.len() == 0 {
2772             return String::new();
2773         }
2774         unsafe {
2775             let p = curl_sys::curl_easy_escape(
2776                 self.inner.handle,
2777                 s.as_ptr() as *const _,
2778                 s.len() as c_int,
2779             );
2780             assert!(!p.is_null());
2781             let ret = str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap();
2782             let ret = String::from(ret);
2783             curl_sys::curl_free(p as *mut _);
2784             return ret;
2785         }
2786     }
2787 
2788     /// URL decodes a string `s`, returning `None` if it fails
url_decode(&mut self, s: &str) -> Vec<u8>2789     pub fn url_decode(&mut self, s: &str) -> Vec<u8> {
2790         if s.len() == 0 {
2791             return Vec::new();
2792         }
2793 
2794         // Work around https://curl.haxx.se/docs/adv_20130622.html, a bug where
2795         // if the last few characters are a bad escape then curl will have a
2796         // buffer overrun.
2797         let mut iter = s.chars().rev();
2798         let orig_len = s.len();
2799         let mut data;
2800         let mut s = s;
2801         if iter.next() == Some('%') || iter.next() == Some('%') || iter.next() == Some('%') {
2802             data = s.to_string();
2803             data.push(0u8 as char);
2804             s = &data[..];
2805         }
2806         unsafe {
2807             let mut len = 0;
2808             let p = curl_sys::curl_easy_unescape(
2809                 self.inner.handle,
2810                 s.as_ptr() as *const _,
2811                 orig_len as c_int,
2812                 &mut len,
2813             );
2814             assert!(!p.is_null());
2815             let slice = slice::from_raw_parts(p as *const u8, len as usize);
2816             let ret = slice.to_vec();
2817             curl_sys::curl_free(p as *mut _);
2818             return ret;
2819         }
2820     }
2821 
2822     // TODO: I don't think this is safe, you can drop this which has all the
2823     //       callback data and then the next is use-after-free
2824     //
2825     // /// Attempts to clone this handle, returning a new session handle with the
2826     // /// same options set for this handle.
2827     // ///
2828     // /// Internal state info and things like persistent connections ccannot be
2829     // /// transferred.
2830     // ///
2831     // /// # Errors
2832     // ///
2833     // /// If a new handle could not be allocated or another error happens, `None`
2834     // /// is returned.
2835     // pub fn try_clone<'b>(&mut self) -> Option<Easy<'b>> {
2836     //     unsafe {
2837     //         let handle = curl_sys::curl_easy_duphandle(self.handle);
2838     //         if handle.is_null() {
2839     //             None
2840     //         } else {
2841     //             Some(Easy {
2842     //                 handle: handle,
2843     //                 data: blank_data(),
2844     //                 _marker: marker::PhantomData,
2845     //             })
2846     //         }
2847     //     }
2848     // }
2849 
2850     /// Receives data from a connected socket.
2851     ///
2852     /// Only useful after a successful `perform` with the `connect_only` option
2853     /// set as well.
recv(&mut self, data: &mut [u8]) -> Result<usize, Error>2854     pub fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error> {
2855         unsafe {
2856             let mut n = 0;
2857             let r = curl_sys::curl_easy_recv(
2858                 self.inner.handle,
2859                 data.as_mut_ptr() as *mut _,
2860                 data.len(),
2861                 &mut n,
2862             );
2863             if r == curl_sys::CURLE_OK {
2864                 Ok(n)
2865             } else {
2866                 Err(Error::new(r))
2867             }
2868         }
2869     }
2870 
2871     /// Sends data over the connected socket.
2872     ///
2873     /// Only useful after a successful `perform` with the `connect_only` option
2874     /// set as well.
send(&mut self, data: &[u8]) -> Result<usize, Error>2875     pub fn send(&mut self, data: &[u8]) -> Result<usize, Error> {
2876         unsafe {
2877             let mut n = 0;
2878             let rc = curl_sys::curl_easy_send(
2879                 self.inner.handle,
2880                 data.as_ptr() as *const _,
2881                 data.len(),
2882                 &mut n,
2883             );
2884             self.cvt(rc)?;
2885             Ok(n)
2886         }
2887     }
2888 
2889     /// Get a pointer to the raw underlying CURL handle.
raw(&self) -> *mut curl_sys::CURL2890     pub fn raw(&self) -> *mut curl_sys::CURL {
2891         self.inner.handle
2892     }
2893 
2894     #[cfg(unix)]
setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error>2895     fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> {
2896         use std::os::unix::prelude::*;
2897         let s = CString::new(val.as_os_str().as_bytes())?;
2898         self.setopt_str(opt, &s)
2899     }
2900 
2901     #[cfg(windows)]
setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error>2902     fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> {
2903         match val.to_str() {
2904             Some(s) => self.setopt_str(opt, &CString::new(s)?),
2905             None => Err(Error::new(curl_sys::CURLE_CONV_FAILED)),
2906         }
2907     }
2908 
setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error>2909     fn setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error> {
2910         unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) }
2911     }
2912 
setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error>2913     fn setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error> {
2914         self.setopt_ptr(opt, val.as_ptr())
2915     }
2916 
setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error>2917     fn setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error> {
2918         unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) }
2919     }
2920 
setopt_off_t( &mut self, opt: curl_sys::CURLoption, val: curl_sys::curl_off_t, ) -> Result<(), Error>2921     fn setopt_off_t(
2922         &mut self,
2923         opt: curl_sys::CURLoption,
2924         val: curl_sys::curl_off_t,
2925     ) -> Result<(), Error> {
2926         unsafe {
2927             let rc = curl_sys::curl_easy_setopt(self.inner.handle, opt, val);
2928             self.cvt(rc)
2929         }
2930     }
2931 
getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error>2932     fn getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error> {
2933         unsafe {
2934             let p = self.getopt_ptr(opt)?;
2935             if p.is_null() {
2936                 Ok(None)
2937             } else {
2938                 Ok(Some(CStr::from_ptr(p).to_bytes()))
2939             }
2940         }
2941     }
2942 
getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error>2943     fn getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error> {
2944         unsafe {
2945             let mut p = 0 as *const c_char;
2946             let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
2947             self.cvt(rc)?;
2948             Ok(p)
2949         }
2950     }
2951 
getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error>2952     fn getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error> {
2953         match self.getopt_bytes(opt) {
2954             Ok(None) => Ok(None),
2955             Err(e) => Err(e),
2956             Ok(Some(bytes)) => match str::from_utf8(bytes) {
2957                 Ok(s) => Ok(Some(s)),
2958                 Err(_) => Err(Error::new(curl_sys::CURLE_CONV_FAILED)),
2959             },
2960         }
2961     }
2962 
getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error>2963     fn getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error> {
2964         unsafe {
2965             let mut p = 0;
2966             let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
2967             self.cvt(rc)?;
2968             Ok(p)
2969         }
2970     }
2971 
getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error>2972     fn getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error> {
2973         unsafe {
2974             let mut p = 0 as c_double;
2975             let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
2976             self.cvt(rc)?;
2977             Ok(p)
2978         }
2979     }
2980 
2981     /// Returns the contents of the internal error buffer, if available.
2982     ///
2983     /// When an easy handle is created it configured the `CURLOPT_ERRORBUFFER`
2984     /// parameter and instructs libcurl to store more error information into a
2985     /// buffer for better error messages and better debugging. The contents of
2986     /// that buffer are automatically coupled with all errors for methods on
2987     /// this type, but if manually invoking APIs the contents will need to be
2988     /// extracted with this method.
2989     ///
2990     /// Put another way, you probably don't need this, you're probably already
2991     /// getting nice error messages!
2992     ///
2993     /// This function will clear the internal buffer, so this is an operation
2994     /// that mutates the handle internally.
take_error_buf(&self) -> Option<String>2995     pub fn take_error_buf(&self) -> Option<String> {
2996         let mut buf = self.inner.error_buf.borrow_mut();
2997         if buf[0] == 0 {
2998             return None;
2999         }
3000         let pos = buf.iter().position(|i| *i == 0).unwrap_or(buf.len());
3001         let msg = String::from_utf8_lossy(&buf[..pos]).into_owned();
3002         buf[0] = 0;
3003         Some(msg)
3004     }
3005 
cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error>3006     fn cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error> {
3007         if rc == curl_sys::CURLE_OK {
3008             return Ok(());
3009         }
3010         let mut err = Error::new(rc);
3011         if let Some(msg) = self.take_error_buf() {
3012             err.set_extra(msg);
3013         }
3014         Err(Error::new(rc))
3015     }
3016 }
3017 
3018 impl<H: fmt::Debug> fmt::Debug for Easy2<H> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3019     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3020         f.debug_struct("Easy")
3021             .field("handle", &self.inner.handle)
3022             .field("handler", &self.inner.handle)
3023             .finish()
3024     }
3025 }
3026 
3027 impl<H> Drop for Easy2<H> {
drop(&mut self)3028     fn drop(&mut self) {
3029         unsafe {
3030             curl_sys::curl_easy_cleanup(self.inner.handle);
3031         }
3032     }
3033 }
3034 
header_cb<H: Handler>( buffer: *mut c_char, size: size_t, nitems: size_t, userptr: *mut c_void, ) -> size_t3035 extern "C" fn header_cb<H: Handler>(
3036     buffer: *mut c_char,
3037     size: size_t,
3038     nitems: size_t,
3039     userptr: *mut c_void,
3040 ) -> size_t {
3041     let keep_going = panic::catch(|| unsafe {
3042         let data = slice::from_raw_parts(buffer as *const u8, size * nitems);
3043         (*(userptr as *mut Inner<H>)).handler.header(data)
3044     })
3045     .unwrap_or(false);
3046     if keep_going {
3047         size * nitems
3048     } else {
3049         !0
3050     }
3051 }
3052 
write_cb<H: Handler>( ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void, ) -> size_t3053 extern "C" fn write_cb<H: Handler>(
3054     ptr: *mut c_char,
3055     size: size_t,
3056     nmemb: size_t,
3057     data: *mut c_void,
3058 ) -> size_t {
3059     panic::catch(|| unsafe {
3060         let input = slice::from_raw_parts(ptr as *const u8, size * nmemb);
3061         match (*(data as *mut Inner<H>)).handler.write(input) {
3062             Ok(s) => s,
3063             Err(WriteError::Pause) | Err(WriteError::__Nonexhaustive) => {
3064                 curl_sys::CURL_WRITEFUNC_PAUSE
3065             }
3066         }
3067     })
3068     .unwrap_or(!0)
3069 }
3070 
read_cb<H: Handler>( ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void, ) -> size_t3071 extern "C" fn read_cb<H: Handler>(
3072     ptr: *mut c_char,
3073     size: size_t,
3074     nmemb: size_t,
3075     data: *mut c_void,
3076 ) -> size_t {
3077     panic::catch(|| unsafe {
3078         let input = slice::from_raw_parts_mut(ptr as *mut u8, size * nmemb);
3079         match (*(data as *mut Inner<H>)).handler.read(input) {
3080             Ok(s) => s,
3081             Err(ReadError::Pause) => curl_sys::CURL_READFUNC_PAUSE,
3082             Err(ReadError::__Nonexhaustive) | Err(ReadError::Abort) => {
3083                 curl_sys::CURL_READFUNC_ABORT
3084             }
3085         }
3086     })
3087     .unwrap_or(!0)
3088 }
3089 
seek_cb<H: Handler>( data: *mut c_void, offset: curl_sys::curl_off_t, origin: c_int, ) -> c_int3090 extern "C" fn seek_cb<H: Handler>(
3091     data: *mut c_void,
3092     offset: curl_sys::curl_off_t,
3093     origin: c_int,
3094 ) -> c_int {
3095     panic::catch(|| unsafe {
3096         let from = if origin == libc::SEEK_SET {
3097             SeekFrom::Start(offset as u64)
3098         } else {
3099             panic!("unknown origin from libcurl: {}", origin);
3100         };
3101         (*(data as *mut Inner<H>)).handler.seek(from) as c_int
3102     })
3103     .unwrap_or(!0)
3104 }
3105 
progress_cb<H: Handler>( data: *mut c_void, dltotal: c_double, dlnow: c_double, ultotal: c_double, ulnow: c_double, ) -> c_int3106 extern "C" fn progress_cb<H: Handler>(
3107     data: *mut c_void,
3108     dltotal: c_double,
3109     dlnow: c_double,
3110     ultotal: c_double,
3111     ulnow: c_double,
3112 ) -> c_int {
3113     let keep_going = panic::catch(|| unsafe {
3114         (*(data as *mut Inner<H>))
3115             .handler
3116             .progress(dltotal, dlnow, ultotal, ulnow)
3117     })
3118     .unwrap_or(false);
3119     if keep_going {
3120         0
3121     } else {
3122         1
3123     }
3124 }
3125 
3126 // TODO: expose `handle`? is that safe?
debug_cb<H: Handler>( _handle: *mut curl_sys::CURL, kind: curl_sys::curl_infotype, data: *mut c_char, size: size_t, userptr: *mut c_void, ) -> c_int3127 extern "C" fn debug_cb<H: Handler>(
3128     _handle: *mut curl_sys::CURL,
3129     kind: curl_sys::curl_infotype,
3130     data: *mut c_char,
3131     size: size_t,
3132     userptr: *mut c_void,
3133 ) -> c_int {
3134     panic::catch(|| unsafe {
3135         let data = slice::from_raw_parts(data as *const u8, size);
3136         let kind = match kind {
3137             curl_sys::CURLINFO_TEXT => InfoType::Text,
3138             curl_sys::CURLINFO_HEADER_IN => InfoType::HeaderIn,
3139             curl_sys::CURLINFO_HEADER_OUT => InfoType::HeaderOut,
3140             curl_sys::CURLINFO_DATA_IN => InfoType::DataIn,
3141             curl_sys::CURLINFO_DATA_OUT => InfoType::DataOut,
3142             curl_sys::CURLINFO_SSL_DATA_IN => InfoType::SslDataIn,
3143             curl_sys::CURLINFO_SSL_DATA_OUT => InfoType::SslDataOut,
3144             _ => return,
3145         };
3146         (*(userptr as *mut Inner<H>)).handler.debug(kind, data)
3147     });
3148     return 0;
3149 }
3150 
ssl_ctx_cb<H: Handler>( _handle: *mut curl_sys::CURL, ssl_ctx: *mut c_void, data: *mut c_void, ) -> curl_sys::CURLcode3151 extern "C" fn ssl_ctx_cb<H: Handler>(
3152     _handle: *mut curl_sys::CURL,
3153     ssl_ctx: *mut c_void,
3154     data: *mut c_void,
3155 ) -> curl_sys::CURLcode {
3156     let res = panic::catch(|| unsafe {
3157         match (*(data as *mut Inner<H>)).handler.ssl_ctx(ssl_ctx) {
3158             Ok(()) => curl_sys::CURLE_OK,
3159             Err(e) => e.code(),
3160         }
3161     });
3162     // Default to a generic SSL error in case of panic. This
3163     // shouldn't really matter since the error should be
3164     // propagated later on but better safe than sorry...
3165     res.unwrap_or(curl_sys::CURLE_SSL_CONNECT_ERROR)
3166 }
3167 
3168 // TODO: expose `purpose` and `sockaddr` inside of `address`
opensocket_cb<H: Handler>( data: *mut c_void, _purpose: curl_sys::curlsocktype, address: *mut curl_sys::curl_sockaddr, ) -> curl_sys::curl_socket_t3169 extern "C" fn opensocket_cb<H: Handler>(
3170     data: *mut c_void,
3171     _purpose: curl_sys::curlsocktype,
3172     address: *mut curl_sys::curl_sockaddr,
3173 ) -> curl_sys::curl_socket_t {
3174     let res = panic::catch(|| unsafe {
3175         (*(data as *mut Inner<H>))
3176             .handler
3177             .open_socket((*address).family, (*address).socktype, (*address).protocol)
3178             .unwrap_or(curl_sys::CURL_SOCKET_BAD)
3179     });
3180     res.unwrap_or(curl_sys::CURL_SOCKET_BAD)
3181 }
3182 
double_seconds_to_duration(seconds: f64) -> Duration3183 fn double_seconds_to_duration(seconds: f64) -> Duration {
3184     let whole_seconds = seconds.trunc() as u64;
3185     let nanos = seconds.fract() * 1_000_000_000f64;
3186     Duration::new(whole_seconds, nanos as u32)
3187 }
3188 
3189 #[test]
double_seconds_to_duration_whole_second()3190 fn double_seconds_to_duration_whole_second() {
3191     let dur = double_seconds_to_duration(1.0);
3192     assert_eq!(dur.as_secs(), 1);
3193     assert_eq!(dur.subsec_nanos(), 0);
3194 }
3195 
3196 #[test]
double_seconds_to_duration_sub_second1()3197 fn double_seconds_to_duration_sub_second1() {
3198     let dur = double_seconds_to_duration(0.0);
3199     assert_eq!(dur.as_secs(), 0);
3200     assert_eq!(dur.subsec_nanos(), 0);
3201 }
3202 
3203 #[test]
double_seconds_to_duration_sub_second2()3204 fn double_seconds_to_duration_sub_second2() {
3205     let dur = double_seconds_to_duration(0.5);
3206     assert_eq!(dur.as_secs(), 0);
3207     assert_eq!(dur.subsec_nanos(), 500_000_000);
3208 }
3209 
3210 impl Auth {
3211     /// Creates a new set of authentications with no members.
3212     ///
3213     /// An `Auth` structure is used to configure which forms of authentication
3214     /// are attempted when negotiating connections with servers.
new() -> Auth3215     pub fn new() -> Auth {
3216         Auth { bits: 0 }
3217     }
3218 
3219     /// HTTP Basic authentication.
3220     ///
3221     /// This is the default choice, and the only method that is in wide-spread
3222     /// use and supported virtually everywhere.  This sends the user name and
3223     /// password over the network in plain text, easily captured by others.
basic(&mut self, on: bool) -> &mut Auth3224     pub fn basic(&mut self, on: bool) -> &mut Auth {
3225         self.flag(curl_sys::CURLAUTH_BASIC, on)
3226     }
3227 
3228     /// HTTP Digest authentication.
3229     ///
3230     /// Digest authentication is defined in RFC 2617 and is a more secure way to
3231     /// do authentication over public networks than the regular old-fashioned
3232     /// Basic method.
digest(&mut self, on: bool) -> &mut Auth3233     pub fn digest(&mut self, on: bool) -> &mut Auth {
3234         self.flag(curl_sys::CURLAUTH_DIGEST, on)
3235     }
3236 
3237     /// HTTP Digest authentication with an IE flavor.
3238     ///
3239     /// Digest authentication is defined in RFC 2617 and is a more secure way to
3240     /// do authentication over public networks than the regular old-fashioned
3241     /// Basic method. The IE flavor is simply that libcurl will use a special
3242     /// "quirk" that IE is known to have used before version 7 and that some
3243     /// servers require the client to use.
digest_ie(&mut self, on: bool) -> &mut Auth3244     pub fn digest_ie(&mut self, on: bool) -> &mut Auth {
3245         self.flag(curl_sys::CURLAUTH_DIGEST_IE, on)
3246     }
3247 
3248     /// HTTP Negotiate (SPNEGO) authentication.
3249     ///
3250     /// Negotiate authentication is defined in RFC 4559 and is the most secure
3251     /// way to perform authentication over HTTP.
3252     ///
3253     /// You need to build libcurl with a suitable GSS-API library or SSPI on
3254     /// Windows for this to work.
gssnegotiate(&mut self, on: bool) -> &mut Auth3255     pub fn gssnegotiate(&mut self, on: bool) -> &mut Auth {
3256         self.flag(curl_sys::CURLAUTH_GSSNEGOTIATE, on)
3257     }
3258 
3259     /// HTTP NTLM authentication.
3260     ///
3261     /// A proprietary protocol invented and used by Microsoft. It uses a
3262     /// challenge-response and hash concept similar to Digest, to prevent the
3263     /// password from being eavesdropped.
3264     ///
3265     /// You need to build libcurl with either OpenSSL, GnuTLS or NSS support for
3266     /// this option to work, or build libcurl on Windows with SSPI support.
ntlm(&mut self, on: bool) -> &mut Auth3267     pub fn ntlm(&mut self, on: bool) -> &mut Auth {
3268         self.flag(curl_sys::CURLAUTH_NTLM, on)
3269     }
3270 
3271     /// NTLM delegating to winbind helper.
3272     ///
3273     /// Authentication is performed by a separate binary application that is
3274     /// executed when needed. The name of the application is specified at
3275     /// compile time but is typically /usr/bin/ntlm_auth
3276     ///
3277     /// Note that libcurl will fork when necessary to run the winbind
3278     /// application and kill it when complete, calling waitpid() to await its
3279     /// exit when done. On POSIX operating systems, killing the process will
3280     /// cause a SIGCHLD signal to be raised (regardless of whether
3281     /// CURLOPT_NOSIGNAL is set), which must be handled intelligently by the
3282     /// application. In particular, the application must not unconditionally
3283     /// call wait() in its SIGCHLD signal handler to avoid being subject to a
3284     /// race condition. This behavior is subject to change in future versions of
3285     /// libcurl.
3286     ///
3287     /// A proprietary protocol invented and used by Microsoft. It uses a
3288     /// challenge-response and hash concept similar to Digest, to prevent the
3289     /// password from being eavesdropped.
ntlm_wb(&mut self, on: bool) -> &mut Auth3290     pub fn ntlm_wb(&mut self, on: bool) -> &mut Auth {
3291         self.flag(curl_sys::CURLAUTH_NTLM_WB, on)
3292     }
3293 
flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth3294     fn flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth {
3295         if on {
3296             self.bits |= bit as c_long;
3297         } else {
3298             self.bits &= !bit as c_long;
3299         }
3300         self
3301     }
3302 }
3303 
3304 impl fmt::Debug for Auth {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3305     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3306         let bits = self.bits as c_ulong;
3307         f.debug_struct("Auth")
3308             .field("basic", &(bits & curl_sys::CURLAUTH_BASIC != 0))
3309             .field("digest", &(bits & curl_sys::CURLAUTH_DIGEST != 0))
3310             .field("digest_ie", &(bits & curl_sys::CURLAUTH_DIGEST_IE != 0))
3311             .field(
3312                 "gssnegotiate",
3313                 &(bits & curl_sys::CURLAUTH_GSSNEGOTIATE != 0),
3314             )
3315             .field("ntlm", &(bits & curl_sys::CURLAUTH_NTLM != 0))
3316             .field("ntlm_wb", &(bits & curl_sys::CURLAUTH_NTLM_WB != 0))
3317             .finish()
3318     }
3319 }
3320 
3321 impl SslOpt {
3322     /// Creates a new set of SSL options.
new() -> SslOpt3323     pub fn new() -> SslOpt {
3324         SslOpt { bits: 0 }
3325     }
3326 
3327     /// Tells libcurl to disable certificate revocation checks for those SSL
3328     /// backends where such behavior is present.
3329     ///
3330     /// Currently this option is only supported for WinSSL (the native Windows
3331     /// SSL library), with an exception in the case of Windows' Untrusted
3332     /// Publishers blacklist which it seems can't be bypassed. This option may
3333     /// have broader support to accommodate other SSL backends in the future.
3334     /// https://curl.haxx.se/docs/ssl-compared.html
no_revoke(&mut self, on: bool) -> &mut SslOpt3335     pub fn no_revoke(&mut self, on: bool) -> &mut SslOpt {
3336         self.flag(curl_sys::CURLSSLOPT_NO_REVOKE, on)
3337     }
3338 
3339     /// Tells libcurl to not attempt to use any workarounds for a security flaw
3340     /// in the SSL3 and TLS1.0 protocols.
3341     ///
3342     /// If this option isn't used or this bit is set to 0, the SSL layer libcurl
3343     /// uses may use a work-around for this flaw although it might cause
3344     /// interoperability problems with some (older) SSL implementations.
3345     ///
3346     /// > WARNING: avoiding this work-around lessens the security, and by
3347     /// > setting this option to 1 you ask for exactly that. This option is only
3348     /// > supported for DarwinSSL, NSS and OpenSSL.
allow_beast(&mut self, on: bool) -> &mut SslOpt3349     pub fn allow_beast(&mut self, on: bool) -> &mut SslOpt {
3350         self.flag(curl_sys::CURLSSLOPT_ALLOW_BEAST, on)
3351     }
3352 
flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt3353     fn flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt {
3354         if on {
3355             self.bits |= bit as c_long;
3356         } else {
3357             self.bits &= !bit as c_long;
3358         }
3359         self
3360     }
3361 }
3362 
3363 impl fmt::Debug for SslOpt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3364     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3365         f.debug_struct("SslOpt")
3366             .field(
3367                 "no_revoke",
3368                 &(self.bits & curl_sys::CURLSSLOPT_NO_REVOKE != 0),
3369             )
3370             .field(
3371                 "allow_beast",
3372                 &(self.bits & curl_sys::CURLSSLOPT_ALLOW_BEAST != 0),
3373             )
3374             .finish()
3375     }
3376 }
3377