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