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