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