Skip to main content

curl/easy/
handler.rs

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