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 // /// Enable or disable TCP Fast Open
1065 // ///
1066 // /// By default this options defaults to `false` and corresponds to
1067 // /// `CURLOPT_TCP_FASTOPEN`
1068 // pub fn fast_open(&mut self, enable: bool) -> Result<(), Error> {
1069 // }
1070
1071 /// Configures whether the TCP_NODELAY option is set, or Nagle's algorithm
1072 /// is disabled.
1073 ///
1074 /// The purpose of Nagle's algorithm is to minimize the number of small
1075 /// packet's on the network, and disabling this may be less efficient in
1076 /// some situations.
1077 ///
1078 /// By default this option is `false` and corresponds to
1079 /// `CURLOPT_TCP_NODELAY`.
tcp_nodelay(&mut self, enable: bool) -> Result<(), Error>1080 pub fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error> {
1081 self.setopt_long(curl_sys::CURLOPT_TCP_NODELAY, enable as c_long)
1082 }
1083
1084 /// Configures whether TCP keepalive probes will be sent.
1085 ///
1086 /// The delay and frequency of these probes is controlled by `tcp_keepidle`
1087 /// and `tcp_keepintvl`.
1088 ///
1089 /// By default this option is `false` and corresponds to
1090 /// `CURLOPT_TCP_KEEPALIVE`.
tcp_keepalive(&mut self, enable: bool) -> Result<(), Error>1091 pub fn tcp_keepalive(&mut self, enable: bool) -> Result<(), Error> {
1092 self.setopt_long(curl_sys::CURLOPT_TCP_KEEPALIVE, enable as c_long)
1093 }
1094
1095 /// Configures the TCP keepalive idle time wait.
1096 ///
1097 /// This is the delay, after which the connection is idle, keepalive probes
1098 /// will be sent. Not all operating systems support this.
1099 ///
1100 /// By default this corresponds to `CURLOPT_TCP_KEEPIDLE`.
tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error>1101 pub fn tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error> {
1102 self.setopt_long(curl_sys::CURLOPT_TCP_KEEPIDLE, amt.as_secs() as c_long)
1103 }
1104
1105 /// Configures the delay between keepalive probes.
1106 ///
1107 /// By default this corresponds to `CURLOPT_TCP_KEEPINTVL`.
tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error>1108 pub fn tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error> {
1109 self.setopt_long(curl_sys::CURLOPT_TCP_KEEPINTVL, amt.as_secs() as c_long)
1110 }
1111
1112 /// Configures the scope for local IPv6 addresses.
1113 ///
1114 /// Sets the scope_id value to use when connecting to IPv6 or link-local
1115 /// addresses.
1116 ///
1117 /// By default this value is 0 and corresponds to `CURLOPT_ADDRESS_SCOPE`
address_scope(&mut self, scope: u32) -> Result<(), Error>1118 pub fn address_scope(&mut self, scope: u32) -> Result<(), Error> {
1119 self.setopt_long(curl_sys::CURLOPT_ADDRESS_SCOPE, scope as c_long)
1120 }
1121
1122 // =========================================================================
1123 // Names and passwords
1124
1125 /// Configures the username to pass as authentication for this connection.
1126 ///
1127 /// By default this value is not set and corresponds to `CURLOPT_USERNAME`.
username(&mut self, user: &str) -> Result<(), Error>1128 pub fn username(&mut self, user: &str) -> Result<(), Error> {
1129 let user = CString::new(user)?;
1130 self.setopt_str(curl_sys::CURLOPT_USERNAME, &user)
1131 }
1132
1133 /// Configures the password to pass as authentication for this connection.
1134 ///
1135 /// By default this value is not set and corresponds to `CURLOPT_PASSWORD`.
password(&mut self, pass: &str) -> Result<(), Error>1136 pub fn password(&mut self, pass: &str) -> Result<(), Error> {
1137 let pass = CString::new(pass)?;
1138 self.setopt_str(curl_sys::CURLOPT_PASSWORD, &pass)
1139 }
1140
1141 /// Set HTTP server authentication methods to try
1142 ///
1143 /// If more than one method is set, libcurl will first query the site to see
1144 /// which authentication methods it supports and then pick the best one you
1145 /// allow it to use. For some methods, this will induce an extra network
1146 /// round-trip. Set the actual name and password with the `password` and
1147 /// `username` methods.
1148 ///
1149 /// For authentication with a proxy, see `proxy_auth`.
1150 ///
1151 /// By default this value is basic and corresponds to `CURLOPT_HTTPAUTH`.
http_auth(&mut self, auth: &Auth) -> Result<(), Error>1152 pub fn http_auth(&mut self, auth: &Auth) -> Result<(), Error> {
1153 self.setopt_long(curl_sys::CURLOPT_HTTPAUTH, auth.bits)
1154 }
1155
1156 /// Configures the proxy username to pass as authentication for this
1157 /// connection.
1158 ///
1159 /// By default this value is not set and corresponds to
1160 /// `CURLOPT_PROXYUSERNAME`.
proxy_username(&mut self, user: &str) -> Result<(), Error>1161 pub fn proxy_username(&mut self, user: &str) -> Result<(), Error> {
1162 let user = CString::new(user)?;
1163 self.setopt_str(curl_sys::CURLOPT_PROXYUSERNAME, &user)
1164 }
1165
1166 /// Configures the proxy password to pass as authentication for this
1167 /// connection.
1168 ///
1169 /// By default this value is not set and corresponds to
1170 /// `CURLOPT_PROXYPASSWORD`.
proxy_password(&mut self, pass: &str) -> Result<(), Error>1171 pub fn proxy_password(&mut self, pass: &str) -> Result<(), Error> {
1172 let pass = CString::new(pass)?;
1173 self.setopt_str(curl_sys::CURLOPT_PROXYPASSWORD, &pass)
1174 }
1175
1176 /// Set HTTP proxy authentication methods to try
1177 ///
1178 /// If more than one method is set, libcurl will first query the site to see
1179 /// which authentication methods it supports and then pick the best one you
1180 /// allow it to use. For some methods, this will induce an extra network
1181 /// round-trip. Set the actual name and password with the `proxy_password`
1182 /// and `proxy_username` methods.
1183 ///
1184 /// By default this value is basic and corresponds to `CURLOPT_PROXYAUTH`.
proxy_auth(&mut self, auth: &Auth) -> Result<(), Error>1185 pub fn proxy_auth(&mut self, auth: &Auth) -> Result<(), Error> {
1186 self.setopt_long(curl_sys::CURLOPT_PROXYAUTH, auth.bits)
1187 }
1188
1189 /// Enable .netrc parsing
1190 ///
1191 /// By default the .netrc file is ignored and corresponds to `CURL_NETRC_IGNORED`.
netrc(&mut self, netrc: NetRc) -> Result<(), Error>1192 pub fn netrc(&mut self, netrc: NetRc) -> Result<(), Error> {
1193 self.setopt_long(curl_sys::CURLOPT_NETRC, netrc as c_long)
1194 }
1195
1196 // =========================================================================
1197 // HTTP Options
1198
1199 /// Indicates whether the referer header is automatically updated
1200 ///
1201 /// By default this option is `false` and corresponds to
1202 /// `CURLOPT_AUTOREFERER`.
autoreferer(&mut self, enable: bool) -> Result<(), Error>1203 pub fn autoreferer(&mut self, enable: bool) -> Result<(), Error> {
1204 self.setopt_long(curl_sys::CURLOPT_AUTOREFERER, enable as c_long)
1205 }
1206
1207 /// Enables automatic decompression of HTTP downloads.
1208 ///
1209 /// Sets the contents of the Accept-Encoding header sent in an HTTP request.
1210 /// This enables decoding of a response with Content-Encoding.
1211 ///
1212 /// Currently supported encoding are `identity`, `zlib`, and `gzip`. A
1213 /// zero-length string passed in will send all accepted encodings.
1214 ///
1215 /// By default this option is not set and corresponds to
1216 /// `CURLOPT_ACCEPT_ENCODING`.
accept_encoding(&mut self, encoding: &str) -> Result<(), Error>1217 pub fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error> {
1218 let encoding = CString::new(encoding)?;
1219 self.setopt_str(curl_sys::CURLOPT_ACCEPT_ENCODING, &encoding)
1220 }
1221
1222 /// Request the HTTP Transfer Encoding.
1223 ///
1224 /// By default this option is `false` and corresponds to
1225 /// `CURLOPT_TRANSFER_ENCODING`.
transfer_encoding(&mut self, enable: bool) -> Result<(), Error>1226 pub fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error> {
1227 self.setopt_long(curl_sys::CURLOPT_TRANSFER_ENCODING, enable as c_long)
1228 }
1229
1230 /// Follow HTTP 3xx redirects.
1231 ///
1232 /// Indicates whether any `Location` headers in the response should get
1233 /// followed.
1234 ///
1235 /// By default this option is `false` and corresponds to
1236 /// `CURLOPT_FOLLOWLOCATION`.
follow_location(&mut self, enable: bool) -> Result<(), Error>1237 pub fn follow_location(&mut self, enable: bool) -> Result<(), Error> {
1238 self.setopt_long(curl_sys::CURLOPT_FOLLOWLOCATION, enable as c_long)
1239 }
1240
1241 /// Send credentials to hosts other than the first as well.
1242 ///
1243 /// Sends username/password credentials even when the host changes as part
1244 /// of a redirect.
1245 ///
1246 /// By default this option is `false` and corresponds to
1247 /// `CURLOPT_UNRESTRICTED_AUTH`.
unrestricted_auth(&mut self, enable: bool) -> Result<(), Error>1248 pub fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error> {
1249 self.setopt_long(curl_sys::CURLOPT_UNRESTRICTED_AUTH, enable as c_long)
1250 }
1251
1252 /// Set the maximum number of redirects allowed.
1253 ///
1254 /// A value of 0 will refuse any redirect.
1255 ///
1256 /// By default this option is `-1` (unlimited) and corresponds to
1257 /// `CURLOPT_MAXREDIRS`.
max_redirections(&mut self, max: u32) -> Result<(), Error>1258 pub fn max_redirections(&mut self, max: u32) -> Result<(), Error> {
1259 self.setopt_long(curl_sys::CURLOPT_MAXREDIRS, max as c_long)
1260 }
1261
1262 // TODO: post_redirections
1263
1264 /// Make an HTTP PUT request.
1265 ///
1266 /// By default this option is `false` and corresponds to `CURLOPT_PUT`.
put(&mut self, enable: bool) -> Result<(), Error>1267 pub fn put(&mut self, enable: bool) -> Result<(), Error> {
1268 self.setopt_long(curl_sys::CURLOPT_PUT, enable as c_long)
1269 }
1270
1271 /// Make an HTTP POST request.
1272 ///
1273 /// This will also make the library use the
1274 /// `Content-Type: application/x-www-form-urlencoded` header.
1275 ///
1276 /// POST data can be specified through `post_fields` or by specifying a read
1277 /// function.
1278 ///
1279 /// By default this option is `false` and corresponds to `CURLOPT_POST`.
post(&mut self, enable: bool) -> Result<(), Error>1280 pub fn post(&mut self, enable: bool) -> Result<(), Error> {
1281 self.setopt_long(curl_sys::CURLOPT_POST, enable as c_long)
1282 }
1283
1284 /// Configures the data that will be uploaded as part of a POST.
1285 ///
1286 /// Note that the data is copied into this handle and if that's not desired
1287 /// then the read callbacks can be used instead.
1288 ///
1289 /// By default this option is not set and corresponds to
1290 /// `CURLOPT_COPYPOSTFIELDS`.
post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error>1291 pub fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error> {
1292 // Set the length before the pointer so libcurl knows how much to read
1293 self.post_field_size(data.len() as u64)?;
1294 self.setopt_ptr(curl_sys::CURLOPT_COPYPOSTFIELDS, data.as_ptr() as *const _)
1295 }
1296
1297 /// Configures the size of data that's going to be uploaded as part of a
1298 /// POST operation.
1299 ///
1300 /// This is called automatically as part of `post_fields` and should only
1301 /// be called if data is being provided in a read callback (and even then
1302 /// it's optional).
1303 ///
1304 /// By default this option is not set and corresponds to
1305 /// `CURLOPT_POSTFIELDSIZE_LARGE`.
post_field_size(&mut self, size: u64) -> Result<(), Error>1306 pub fn post_field_size(&mut self, size: u64) -> Result<(), Error> {
1307 // Clear anything previous to ensure we don't read past a buffer
1308 self.setopt_ptr(curl_sys::CURLOPT_POSTFIELDS, 0 as *const _)?;
1309 self.setopt_off_t(
1310 curl_sys::CURLOPT_POSTFIELDSIZE_LARGE,
1311 size as curl_sys::curl_off_t,
1312 )
1313 }
1314
1315 /// Tells libcurl you want a multipart/formdata HTTP POST to be made and you
1316 /// instruct what data to pass on to the server in the `form` argument.
1317 ///
1318 /// By default this option is set to null and corresponds to
1319 /// `CURLOPT_HTTPPOST`.
httppost(&mut self, form: Form) -> Result<(), Error>1320 pub fn httppost(&mut self, form: Form) -> Result<(), Error> {
1321 self.setopt_ptr(curl_sys::CURLOPT_HTTPPOST, form::raw(&form) as *const _)?;
1322 self.inner.form = Some(form);
1323 Ok(())
1324 }
1325
1326 /// Sets the HTTP referer header
1327 ///
1328 /// By default this option is not set and corresponds to `CURLOPT_REFERER`.
referer(&mut self, referer: &str) -> Result<(), Error>1329 pub fn referer(&mut self, referer: &str) -> Result<(), Error> {
1330 let referer = CString::new(referer)?;
1331 self.setopt_str(curl_sys::CURLOPT_REFERER, &referer)
1332 }
1333
1334 /// Sets the HTTP user-agent header
1335 ///
1336 /// By default this option is not set and corresponds to
1337 /// `CURLOPT_USERAGENT`.
useragent(&mut self, useragent: &str) -> Result<(), Error>1338 pub fn useragent(&mut self, useragent: &str) -> Result<(), Error> {
1339 let useragent = CString::new(useragent)?;
1340 self.setopt_str(curl_sys::CURLOPT_USERAGENT, &useragent)
1341 }
1342
1343 /// Add some headers to this HTTP request.
1344 ///
1345 /// If you add a header that is otherwise used internally, the value here
1346 /// takes precedence. If a header is added with no content (like `Accept:`)
1347 /// the internally the header will get disabled. To add a header with no
1348 /// content, use the form `MyHeader;` (not the trailing semicolon).
1349 ///
1350 /// Headers must not be CRLF terminated. Many replaced headers have common
1351 /// shortcuts which should be prefered.
1352 ///
1353 /// By default this option is not set and corresponds to
1354 /// `CURLOPT_HTTPHEADER`
1355 ///
1356 /// # Examples
1357 ///
1358 /// ```
1359 /// use curl::easy::{Easy, List};
1360 ///
1361 /// let mut list = List::new();
1362 /// list.append("Foo: bar").unwrap();
1363 /// list.append("Bar: baz").unwrap();
1364 ///
1365 /// let mut handle = Easy::new();
1366 /// handle.url("https://www.rust-lang.org/").unwrap();
1367 /// handle.http_headers(list).unwrap();
1368 /// handle.perform().unwrap();
1369 /// ```
http_headers(&mut self, list: List) -> Result<(), Error>1370 pub fn http_headers(&mut self, list: List) -> Result<(), Error> {
1371 let ptr = list::raw(&list);
1372 self.inner.header_list = Some(list);
1373 self.setopt_ptr(curl_sys::CURLOPT_HTTPHEADER, ptr as *const _)
1374 }
1375
1376 // /// Add some headers to send to the HTTP proxy.
1377 // ///
1378 // /// This function is essentially the same as `http_headers`.
1379 // ///
1380 // /// By default this option is not set and corresponds to
1381 // /// `CURLOPT_PROXYHEADER`
1382 // pub fn proxy_headers(&mut self, list: &'a List) -> Result<(), Error> {
1383 // self.setopt_ptr(curl_sys::CURLOPT_PROXYHEADER, list.raw as *const _)
1384 // }
1385
1386 /// Set the contents of the HTTP Cookie header.
1387 ///
1388 /// Pass a string of the form `name=contents` for one cookie value or
1389 /// `name1=val1; name2=val2` for multiple values.
1390 ///
1391 /// Using this option multiple times will only make the latest string
1392 /// override the previous ones. This option will not enable the cookie
1393 /// engine, use `cookie_file` or `cookie_jar` to do that.
1394 ///
1395 /// By default this option is not set and corresponds to `CURLOPT_COOKIE`.
cookie(&mut self, cookie: &str) -> Result<(), Error>1396 pub fn cookie(&mut self, cookie: &str) -> Result<(), Error> {
1397 let cookie = CString::new(cookie)?;
1398 self.setopt_str(curl_sys::CURLOPT_COOKIE, &cookie)
1399 }
1400
1401 /// Set the file name to read cookies from.
1402 ///
1403 /// The cookie data can be in either the old Netscape / Mozilla cookie data
1404 /// format or just regular HTTP headers (Set-Cookie style) dumped to a file.
1405 ///
1406 /// This also enables the cookie engine, making libcurl parse and send
1407 /// cookies on subsequent requests with this handle.
1408 ///
1409 /// Given an empty or non-existing file or by passing the empty string ("")
1410 /// to this option, you can enable the cookie engine without reading any
1411 /// initial cookies.
1412 ///
1413 /// If you use this option multiple times, you just add more files to read.
1414 /// Subsequent files will add more cookies.
1415 ///
1416 /// By default this option is not set and corresponds to
1417 /// `CURLOPT_COOKIEFILE`.
cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>1418 pub fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> {
1419 self.setopt_path(curl_sys::CURLOPT_COOKIEFILE, file.as_ref())
1420 }
1421
1422 /// Set the file name to store cookies to.
1423 ///
1424 /// This will make libcurl write all internally known cookies to the file
1425 /// when this handle is dropped. If no cookies are known, no file will be
1426 /// created. Specify "-" as filename to instead have the cookies written to
1427 /// stdout. Using this option also enables cookies for this session, so if
1428 /// you for example follow a location it will make matching cookies get sent
1429 /// accordingly.
1430 ///
1431 /// Note that libcurl doesn't read any cookies from the cookie jar. If you
1432 /// want to read cookies from a file, use `cookie_file`.
1433 ///
1434 /// By default this option is not set and corresponds to
1435 /// `CURLOPT_COOKIEJAR`.
cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>1436 pub fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> {
1437 self.setopt_path(curl_sys::CURLOPT_COOKIEJAR, file.as_ref())
1438 }
1439
1440 /// Start a new cookie session
1441 ///
1442 /// Marks this as a new cookie "session". It will force libcurl to ignore
1443 /// all cookies it is about to load that are "session cookies" from the
1444 /// previous session. By default, libcurl always stores and loads all
1445 /// cookies, independent if they are session cookies or not. Session cookies
1446 /// are cookies without expiry date and they are meant to be alive and
1447 /// existing for this "session" only.
1448 ///
1449 /// By default this option is `false` and corresponds to
1450 /// `CURLOPT_COOKIESESSION`.
cookie_session(&mut self, session: bool) -> Result<(), Error>1451 pub fn cookie_session(&mut self, session: bool) -> Result<(), Error> {
1452 self.setopt_long(curl_sys::CURLOPT_COOKIESESSION, session as c_long)
1453 }
1454
1455 /// Add to or manipulate cookies held in memory.
1456 ///
1457 /// Such a cookie can be either a single line in Netscape / Mozilla format
1458 /// or just regular HTTP-style header (Set-Cookie: ...) format. This will
1459 /// also enable the cookie engine. This adds that single cookie to the
1460 /// internal cookie store.
1461 ///
1462 /// Exercise caution if you are using this option and multiple transfers may
1463 /// occur. If you use the Set-Cookie format and don't specify a domain then
1464 /// the cookie is sent for any domain (even after redirects are followed)
1465 /// and cannot be modified by a server-set cookie. If a server sets a cookie
1466 /// of the same name (or maybe you've imported one) then both will be sent
1467 /// on a future transfer to that server, likely not what you intended.
1468 /// address these issues set a domain in Set-Cookie or use the Netscape
1469 /// format.
1470 ///
1471 /// Additionally, there are commands available that perform actions if you
1472 /// pass in these exact strings:
1473 ///
1474 /// * "ALL" - erases all cookies held in memory
1475 /// * "SESS" - erases all session cookies held in memory
1476 /// * "FLUSH" - write all known cookies to the specified cookie jar
1477 /// * "RELOAD" - reread all cookies from the cookie file
1478 ///
1479 /// By default this options corresponds to `CURLOPT_COOKIELIST`
cookie_list(&mut self, cookie: &str) -> Result<(), Error>1480 pub fn cookie_list(&mut self, cookie: &str) -> Result<(), Error> {
1481 let cookie = CString::new(cookie)?;
1482 self.setopt_str(curl_sys::CURLOPT_COOKIELIST, &cookie)
1483 }
1484
1485 /// Ask for a HTTP GET request.
1486 ///
1487 /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`.
get(&mut self, enable: bool) -> Result<(), Error>1488 pub fn get(&mut self, enable: bool) -> Result<(), Error> {
1489 self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long)
1490 }
1491
1492 // /// Ask for a HTTP GET request.
1493 // ///
1494 // /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`.
1495 // pub fn http_version(&mut self, vers: &str) -> Result<(), Error> {
1496 // self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long)
1497 // }
1498
1499 /// Ignore the content-length header.
1500 ///
1501 /// By default this option is `false` and corresponds to
1502 /// `CURLOPT_IGNORE_CONTENT_LENGTH`.
ignore_content_length(&mut self, ignore: bool) -> Result<(), Error>1503 pub fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error> {
1504 self.setopt_long(curl_sys::CURLOPT_IGNORE_CONTENT_LENGTH, ignore as c_long)
1505 }
1506
1507 /// Enable or disable HTTP content decoding.
1508 ///
1509 /// By default this option is `true` and corresponds to
1510 /// `CURLOPT_HTTP_CONTENT_DECODING`.
http_content_decoding(&mut self, enable: bool) -> Result<(), Error>1511 pub fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error> {
1512 self.setopt_long(curl_sys::CURLOPT_HTTP_CONTENT_DECODING, enable as c_long)
1513 }
1514
1515 /// Enable or disable HTTP transfer decoding.
1516 ///
1517 /// By default this option is `true` and corresponds to
1518 /// `CURLOPT_HTTP_TRANSFER_DECODING`.
http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error>1519 pub fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error> {
1520 self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, enable as c_long)
1521 }
1522
1523 // /// Timeout for the Expect: 100-continue response
1524 // ///
1525 // /// By default this option is 1s and corresponds to
1526 // /// `CURLOPT_EXPECT_100_TIMEOUT_MS`.
1527 // pub fn expect_100_timeout(&mut self, enable: bool) -> Result<(), Error> {
1528 // self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING,
1529 // enable as c_long)
1530 // }
1531
1532 // /// Wait for pipelining/multiplexing.
1533 // ///
1534 // /// Tells libcurl to prefer to wait for a connection to confirm or deny that
1535 // /// it can do pipelining or multiplexing before continuing.
1536 // ///
1537 // /// When about to perform a new transfer that allows pipelining or
1538 // /// multiplexing, libcurl will check for existing connections to re-use and
1539 // /// pipeline on. If no such connection exists it will immediately continue
1540 // /// and create a fresh new connection to use.
1541 // ///
1542 // /// By setting this option to `true` - having `pipeline` enabled for the
1543 // /// multi handle this transfer is associated with - libcurl will instead
1544 // /// wait for the connection to reveal if it is possible to
1545 // /// pipeline/multiplex on before it continues. This enables libcurl to much
1546 // /// better keep the number of connections to a minimum when using pipelining
1547 // /// or multiplexing protocols.
1548 // ///
1549 // /// The effect thus becomes that with this option set, libcurl prefers to
1550 // /// wait and re-use an existing connection for pipelining rather than the
1551 // /// opposite: prefer to open a new connection rather than waiting.
1552 // ///
1553 // /// The waiting time is as long as it takes for the connection to get up and
1554 // /// for libcurl to get the necessary response back that informs it about its
1555 // /// protocol and support level.
1556 // pub fn http_pipewait(&mut self, enable: bool) -> Result<(), Error> {
1557 // }
1558
1559 // =========================================================================
1560 // Protocol Options
1561
1562 /// Indicates the range that this request should retrieve.
1563 ///
1564 /// The string provided should be of the form `N-M` where either `N` or `M`
1565 /// can be left out. For HTTP transfers multiple ranges separated by commas
1566 /// are also accepted.
1567 ///
1568 /// By default this option is not set and corresponds to `CURLOPT_RANGE`.
range(&mut self, range: &str) -> Result<(), Error>1569 pub fn range(&mut self, range: &str) -> Result<(), Error> {
1570 let range = CString::new(range)?;
1571 self.setopt_str(curl_sys::CURLOPT_RANGE, &range)
1572 }
1573
1574 /// Set a point to resume transfer from
1575 ///
1576 /// Specify the offset in bytes you want the transfer to start from.
1577 ///
1578 /// By default this option is 0 and corresponds to
1579 /// `CURLOPT_RESUME_FROM_LARGE`.
resume_from(&mut self, from: u64) -> Result<(), Error>1580 pub fn resume_from(&mut self, from: u64) -> Result<(), Error> {
1581 self.setopt_off_t(
1582 curl_sys::CURLOPT_RESUME_FROM_LARGE,
1583 from as curl_sys::curl_off_t,
1584 )
1585 }
1586
1587 /// Set a custom request string
1588 ///
1589 /// Specifies that a custom request will be made (e.g. a custom HTTP
1590 /// method). This does not change how libcurl performs internally, just
1591 /// changes the string sent to the server.
1592 ///
1593 /// By default this option is not set and corresponds to
1594 /// `CURLOPT_CUSTOMREQUEST`.
custom_request(&mut self, request: &str) -> Result<(), Error>1595 pub fn custom_request(&mut self, request: &str) -> Result<(), Error> {
1596 let request = CString::new(request)?;
1597 self.setopt_str(curl_sys::CURLOPT_CUSTOMREQUEST, &request)
1598 }
1599
1600 /// Get the modification time of the remote resource
1601 ///
1602 /// If true, libcurl will attempt to get the modification time of the
1603 /// remote document in this operation. This requires that the remote server
1604 /// sends the time or replies to a time querying command. The `filetime`
1605 /// function can be used after a transfer to extract the received time (if
1606 /// any).
1607 ///
1608 /// By default this option is `false` and corresponds to `CURLOPT_FILETIME`
fetch_filetime(&mut self, fetch: bool) -> Result<(), Error>1609 pub fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error> {
1610 self.setopt_long(curl_sys::CURLOPT_FILETIME, fetch as c_long)
1611 }
1612
1613 /// Indicate whether to download the request without getting the body
1614 ///
1615 /// This is useful, for example, for doing a HEAD request.
1616 ///
1617 /// By default this option is `false` and corresponds to `CURLOPT_NOBODY`.
nobody(&mut self, enable: bool) -> Result<(), Error>1618 pub fn nobody(&mut self, enable: bool) -> Result<(), Error> {
1619 self.setopt_long(curl_sys::CURLOPT_NOBODY, enable as c_long)
1620 }
1621
1622 /// Set the size of the input file to send off.
1623 ///
1624 /// By default this option is not set and corresponds to
1625 /// `CURLOPT_INFILESIZE_LARGE`.
in_filesize(&mut self, size: u64) -> Result<(), Error>1626 pub fn in_filesize(&mut self, size: u64) -> Result<(), Error> {
1627 self.setopt_off_t(
1628 curl_sys::CURLOPT_INFILESIZE_LARGE,
1629 size as curl_sys::curl_off_t,
1630 )
1631 }
1632
1633 /// Enable or disable data upload.
1634 ///
1635 /// This means that a PUT request will be made for HTTP and probably wants
1636 /// to be combined with the read callback as well as the `in_filesize`
1637 /// method.
1638 ///
1639 /// By default this option is `false` and corresponds to `CURLOPT_UPLOAD`.
upload(&mut self, enable: bool) -> Result<(), Error>1640 pub fn upload(&mut self, enable: bool) -> Result<(), Error> {
1641 self.setopt_long(curl_sys::CURLOPT_UPLOAD, enable as c_long)
1642 }
1643
1644 /// Configure the maximum file size to download.
1645 ///
1646 /// By default this option is not set and corresponds to
1647 /// `CURLOPT_MAXFILESIZE_LARGE`.
max_filesize(&mut self, size: u64) -> Result<(), Error>1648 pub fn max_filesize(&mut self, size: u64) -> Result<(), Error> {
1649 self.setopt_off_t(
1650 curl_sys::CURLOPT_MAXFILESIZE_LARGE,
1651 size as curl_sys::curl_off_t,
1652 )
1653 }
1654
1655 /// Selects a condition for a time request.
1656 ///
1657 /// This value indicates how the `time_value` option is interpreted.
1658 ///
1659 /// By default this option is not set and corresponds to
1660 /// `CURLOPT_TIMECONDITION`.
time_condition(&mut self, cond: TimeCondition) -> Result<(), Error>1661 pub fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error> {
1662 self.setopt_long(curl_sys::CURLOPT_TIMECONDITION, cond as c_long)
1663 }
1664
1665 /// Sets the time value for a conditional request.
1666 ///
1667 /// The value here should be the number of seconds elapsed since January 1,
1668 /// 1970. To pass how to interpret this value, use `time_condition`.
1669 ///
1670 /// By default this option is not set and corresponds to
1671 /// `CURLOPT_TIMEVALUE`.
time_value(&mut self, val: i64) -> Result<(), Error>1672 pub fn time_value(&mut self, val: i64) -> Result<(), Error> {
1673 self.setopt_long(curl_sys::CURLOPT_TIMEVALUE, val as c_long)
1674 }
1675
1676 // =========================================================================
1677 // Connection Options
1678
1679 /// Set maximum time the request is allowed to take.
1680 ///
1681 /// Normally, name lookups can take a considerable time and limiting
1682 /// operations to less than a few minutes risk aborting perfectly normal
1683 /// operations.
1684 ///
1685 /// If libcurl is built to use the standard system name resolver, that
1686 /// portion of the transfer will still use full-second resolution for
1687 /// timeouts with a minimum timeout allowed of one second.
1688 ///
1689 /// In unix-like systems, this might cause signals to be used unless
1690 /// `nosignal` is set.
1691 ///
1692 /// Since this puts a hard limit for how long a request is allowed to
1693 /// take, it has limited use in dynamic use cases with varying transfer
1694 /// times. You are then advised to explore `low_speed_limit`,
1695 /// `low_speed_time` or using `progress_function` to implement your own
1696 /// timeout logic.
1697 ///
1698 /// By default this option is not set and corresponds to
1699 /// `CURLOPT_TIMEOUT_MS`.
timeout(&mut self, timeout: Duration) -> Result<(), Error>1700 pub fn timeout(&mut self, timeout: Duration) -> Result<(), Error> {
1701 // TODO: checked arithmetic and casts
1702 // TODO: use CURLOPT_TIMEOUT if the timeout is too great
1703 let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64;
1704 self.setopt_long(curl_sys::CURLOPT_TIMEOUT_MS, ms as c_long)
1705 }
1706
1707 /// Set the low speed limit in bytes per second.
1708 ///
1709 /// This specifies the average transfer speed in bytes per second that the
1710 /// transfer should be below during `low_speed_time` for libcurl to consider
1711 /// it to be too slow and abort.
1712 ///
1713 /// By default this option is not set and corresponds to
1714 /// `CURLOPT_LOW_SPEED_LIMIT`.
low_speed_limit(&mut self, limit: u32) -> Result<(), Error>1715 pub fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error> {
1716 self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_LIMIT, limit as c_long)
1717 }
1718
1719 /// Set the low speed time period.
1720 ///
1721 /// Specifies the window of time for which if the transfer rate is below
1722 /// `low_speed_limit` the request will be aborted.
1723 ///
1724 /// By default this option is not set and corresponds to
1725 /// `CURLOPT_LOW_SPEED_TIME`.
low_speed_time(&mut self, dur: Duration) -> Result<(), Error>1726 pub fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error> {
1727 self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_TIME, dur.as_secs() as c_long)
1728 }
1729
1730 /// Rate limit data upload speed
1731 ///
1732 /// If an upload exceeds this speed (counted in bytes per second) on
1733 /// cumulative average during the transfer, the transfer will pause to keep
1734 /// the average rate less than or equal to the parameter value.
1735 ///
1736 /// By default this option is not set (unlimited speed) and corresponds to
1737 /// `CURLOPT_MAX_SEND_SPEED_LARGE`.
max_send_speed(&mut self, speed: u64) -> Result<(), Error>1738 pub fn max_send_speed(&mut self, speed: u64) -> Result<(), Error> {
1739 self.setopt_off_t(
1740 curl_sys::CURLOPT_MAX_SEND_SPEED_LARGE,
1741 speed as curl_sys::curl_off_t,
1742 )
1743 }
1744
1745 /// Rate limit data download speed
1746 ///
1747 /// If a download exceeds this speed (counted in bytes per second) on
1748 /// cumulative average during the transfer, the transfer will pause to keep
1749 /// the average rate less than or equal to the parameter value.
1750 ///
1751 /// By default this option is not set (unlimited speed) and corresponds to
1752 /// `CURLOPT_MAX_RECV_SPEED_LARGE`.
max_recv_speed(&mut self, speed: u64) -> Result<(), Error>1753 pub fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error> {
1754 self.setopt_off_t(
1755 curl_sys::CURLOPT_MAX_RECV_SPEED_LARGE,
1756 speed as curl_sys::curl_off_t,
1757 )
1758 }
1759
1760 /// Set the maximum connection cache size.
1761 ///
1762 /// The set amount will be the maximum number of simultaneously open
1763 /// persistent connections that libcurl may cache in the pool associated
1764 /// with this handle. The default is 5, and there isn't much point in
1765 /// changing this value unless you are perfectly aware of how this works and
1766 /// changes libcurl's behaviour. This concerns connections using any of the
1767 /// protocols that support persistent connections.
1768 ///
1769 /// When reaching the maximum limit, curl closes the oldest one in the cache
1770 /// to prevent increasing the number of open connections.
1771 ///
1772 /// By default this option is set to 5 and corresponds to
1773 /// `CURLOPT_MAXCONNECTS`
max_connects(&mut self, max: u32) -> Result<(), Error>1774 pub fn max_connects(&mut self, max: u32) -> Result<(), Error> {
1775 self.setopt_long(curl_sys::CURLOPT_MAXCONNECTS, max as c_long)
1776 }
1777
1778 /// Set the maximum idle time allowed for a connection.
1779 ///
1780 /// This configuration sets the maximum time that a connection inside of the connection cache
1781 /// can be reused. Any connection older than this value will be considered stale and will
1782 /// be closed.
1783 ///
1784 /// By default, a value of 118 seconds is used.
maxage_conn(&mut self, max_age: Duration) -> Result<(), Error>1785 pub fn maxage_conn(&mut self, max_age: Duration) -> Result<(), Error> {
1786 self.setopt_long(curl_sys::CURLOPT_MAXAGE_CONN, max_age.as_secs() as c_long)
1787 }
1788
1789 /// Force a new connection to be used.
1790 ///
1791 /// Makes the next transfer use a new (fresh) connection by force instead of
1792 /// trying to re-use an existing one. This option should be used with
1793 /// caution and only if you understand what it does as it may seriously
1794 /// impact performance.
1795 ///
1796 /// By default this option is `false` and corresponds to
1797 /// `CURLOPT_FRESH_CONNECT`.
fresh_connect(&mut self, enable: bool) -> Result<(), Error>1798 pub fn fresh_connect(&mut self, enable: bool) -> Result<(), Error> {
1799 self.setopt_long(curl_sys::CURLOPT_FRESH_CONNECT, enable as c_long)
1800 }
1801
1802 /// Make connection get closed at once after use.
1803 ///
1804 /// Makes libcurl explicitly close the connection when done with the
1805 /// transfer. Normally, libcurl keeps all connections alive when done with
1806 /// one transfer in case a succeeding one follows that can re-use them.
1807 /// This option should be used with caution and only if you understand what
1808 /// it does as it can seriously impact performance.
1809 ///
1810 /// By default this option is `false` and corresponds to
1811 /// `CURLOPT_FORBID_REUSE`.
forbid_reuse(&mut self, enable: bool) -> Result<(), Error>1812 pub fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error> {
1813 self.setopt_long(curl_sys::CURLOPT_FORBID_REUSE, enable as c_long)
1814 }
1815
1816 /// Timeout for the connect phase
1817 ///
1818 /// This is the maximum time that you allow the connection phase to the
1819 /// server to take. This only limits the connection phase, it has no impact
1820 /// once it has connected.
1821 ///
1822 /// By default this value is 300 seconds and corresponds to
1823 /// `CURLOPT_CONNECTTIMEOUT_MS`.
connect_timeout(&mut self, timeout: Duration) -> Result<(), Error>1824 pub fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error> {
1825 let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64;
1826 self.setopt_long(curl_sys::CURLOPT_CONNECTTIMEOUT_MS, ms as c_long)
1827 }
1828
1829 /// Specify which IP protocol version to use
1830 ///
1831 /// Allows an application to select what kind of IP addresses to use when
1832 /// resolving host names. This is only interesting when using host names
1833 /// that resolve addresses using more than one version of IP.
1834 ///
1835 /// By default this value is "any" and corresponds to `CURLOPT_IPRESOLVE`.
ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error>1836 pub fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error> {
1837 self.setopt_long(curl_sys::CURLOPT_IPRESOLVE, resolve as c_long)
1838 }
1839
1840 /// Specify custom host name to IP address resolves.
1841 ///
1842 /// Allows specifying hostname to IP mappins to use before trying the
1843 /// system resolver.
1844 ///
1845 /// # Examples
1846 ///
1847 /// ```no_run
1848 /// use curl::easy::{Easy, List};
1849 ///
1850 /// let mut list = List::new();
1851 /// list.append("www.rust-lang.org:443:185.199.108.153").unwrap();
1852 ///
1853 /// let mut handle = Easy::new();
1854 /// handle.url("https://www.rust-lang.org/").unwrap();
1855 /// handle.resolve(list).unwrap();
1856 /// handle.perform().unwrap();
1857 /// ```
resolve(&mut self, list: List) -> Result<(), Error>1858 pub fn resolve(&mut self, list: List) -> Result<(), Error> {
1859 let ptr = list::raw(&list);
1860 self.inner.resolve_list = Some(list);
1861 self.setopt_ptr(curl_sys::CURLOPT_RESOLVE, ptr as *const _)
1862 }
1863
1864 /// Configure whether to stop when connected to target server
1865 ///
1866 /// When enabled it tells the library to perform all the required proxy
1867 /// authentication and connection setup, but no data transfer, and then
1868 /// return.
1869 ///
1870 /// The option can be used to simply test a connection to a server.
1871 ///
1872 /// By default this value is `false` and corresponds to
1873 /// `CURLOPT_CONNECT_ONLY`.
connect_only(&mut self, enable: bool) -> Result<(), Error>1874 pub fn connect_only(&mut self, enable: bool) -> Result<(), Error> {
1875 self.setopt_long(curl_sys::CURLOPT_CONNECT_ONLY, enable as c_long)
1876 }
1877
1878 // /// Set interface to speak DNS over.
1879 // ///
1880 // /// Set the name of the network interface that the DNS resolver should bind
1881 // /// to. This must be an interface name (not an address).
1882 // ///
1883 // /// By default this option is not set and corresponds to
1884 // /// `CURLOPT_DNS_INTERFACE`.
1885 // pub fn dns_interface(&mut self, interface: &str) -> Result<(), Error> {
1886 // let interface = CString::new(interface)?;
1887 // self.setopt_str(curl_sys::CURLOPT_DNS_INTERFACE, &interface)
1888 // }
1889 //
1890 // /// IPv4 address to bind DNS resolves to
1891 // ///
1892 // /// Set the local IPv4 address that the resolver should bind to. The
1893 // /// argument should be of type char * and contain a single numerical IPv4
1894 // /// address as a string.
1895 // ///
1896 // /// By default this option is not set and corresponds to
1897 // /// `CURLOPT_DNS_LOCAL_IP4`.
1898 // pub fn dns_local_ip4(&mut self, ip: &str) -> Result<(), Error> {
1899 // let ip = CString::new(ip)?;
1900 // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP4, &ip)
1901 // }
1902 //
1903 // /// IPv6 address to bind DNS resolves to
1904 // ///
1905 // /// Set the local IPv6 address that the resolver should bind to. The
1906 // /// argument should be of type char * and contain a single numerical IPv6
1907 // /// address as a string.
1908 // ///
1909 // /// By default this option is not set and corresponds to
1910 // /// `CURLOPT_DNS_LOCAL_IP6`.
1911 // pub fn dns_local_ip6(&mut self, ip: &str) -> Result<(), Error> {
1912 // let ip = CString::new(ip)?;
1913 // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP6, &ip)
1914 // }
1915 //
1916 // /// Set preferred DNS servers.
1917 // ///
1918 // /// Provides a list of DNS servers to be used instead of the system default.
1919 // /// The format of the dns servers option is:
1920 // ///
1921 // /// ```text
1922 // /// host[:port],[host[:port]]...
1923 // /// ```
1924 // ///
1925 // /// By default this option is not set and corresponds to
1926 // /// `CURLOPT_DNS_SERVERS`.
1927 // pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> {
1928 // let servers = CString::new(servers)?;
1929 // self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &servers)
1930 // }
1931
1932 // =========================================================================
1933 // SSL/Security Options
1934
1935 /// Sets the SSL client certificate.
1936 ///
1937 /// The string should be the file name of your client certificate. The
1938 /// default format is "P12" on Secure Transport and "PEM" on other engines,
1939 /// and can be changed with `ssl_cert_type`.
1940 ///
1941 /// With NSS or Secure Transport, this can also be the nickname of the
1942 /// certificate you wish to authenticate with as it is named in the security
1943 /// database. If you want to use a file from the current directory, please
1944 /// precede it with "./" prefix, in order to avoid confusion with a
1945 /// nickname.
1946 ///
1947 /// When using a client certificate, you most likely also need to provide a
1948 /// private key with `ssl_key`.
1949 ///
1950 /// By default this option is not set and corresponds to `CURLOPT_SSLCERT`.
ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error>1951 pub fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error> {
1952 self.setopt_path(curl_sys::CURLOPT_SSLCERT, cert.as_ref())
1953 }
1954
1955 /// Set the SSL client certificate using an in-memory blob.
1956 ///
1957 /// The specified byte buffer should contain the binary content of your
1958 /// client certificate, which will be copied into the handle. The format of
1959 /// the certificate can be specified with `ssl_cert_type`.
1960 ///
1961 /// By default this option is not set and corresponds to
1962 /// `CURLOPT_SSLCERT_BLOB`.
ssl_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error>1963 pub fn ssl_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> {
1964 self.setopt_blob(curl_sys::CURLOPT_SSLCERT_BLOB, blob)
1965 }
1966
1967 /// Specify type of the client SSL certificate.
1968 ///
1969 /// The string should be the format of your certificate. Supported formats
1970 /// are "PEM" and "DER", except with Secure Transport. OpenSSL (versions
1971 /// 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7
1972 /// or later) also support "P12" for PKCS#12-encoded files.
1973 ///
1974 /// By default this option is "PEM" and corresponds to
1975 /// `CURLOPT_SSLCERTTYPE`.
ssl_cert_type(&mut self, kind: &str) -> Result<(), Error>1976 pub fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error> {
1977 let kind = CString::new(kind)?;
1978 self.setopt_str(curl_sys::CURLOPT_SSLCERTTYPE, &kind)
1979 }
1980
1981 /// Specify private keyfile for TLS and SSL client cert.
1982 ///
1983 /// The string should be the file name of your private key. The default
1984 /// format is "PEM" and can be changed with `ssl_key_type`.
1985 ///
1986 /// (iOS and Mac OS X only) This option is ignored if curl was built against
1987 /// Secure Transport. Secure Transport expects the private key to be already
1988 /// present in the keychain or PKCS#12 file containing the certificate.
1989 ///
1990 /// By default this option is not set and corresponds to `CURLOPT_SSLKEY`.
ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error>1991 pub fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error> {
1992 self.setopt_path(curl_sys::CURLOPT_SSLKEY, key.as_ref())
1993 }
1994
1995 /// Specify an SSL private key using an in-memory blob.
1996 ///
1997 /// The specified byte buffer should contain the binary content of your
1998 /// private key, which will be copied into the handle. The format of
1999 /// the private key can be specified with `ssl_key_type`.
2000 ///
2001 /// By default this option is not set and corresponds to
2002 /// `CURLOPT_SSLKEY_BLOB`.
ssl_key_blob(&mut self, blob: &[u8]) -> Result<(), Error>2003 pub fn ssl_key_blob(&mut self, blob: &[u8]) -> Result<(), Error> {
2004 self.setopt_blob(curl_sys::CURLOPT_SSLKEY_BLOB, blob)
2005 }
2006
2007 /// Set type of the private key file.
2008 ///
2009 /// The string should be the format of your private key. Supported formats
2010 /// are "PEM", "DER" and "ENG".
2011 ///
2012 /// The format "ENG" enables you to load the private key from a crypto
2013 /// engine. In this case `ssl_key` is used as an identifier passed to
2014 /// the engine. You have to set the crypto engine with `ssl_engine`.
2015 /// "DER" format key file currently does not work because of a bug in
2016 /// OpenSSL.
2017 ///
2018 /// By default this option is "PEM" and corresponds to
2019 /// `CURLOPT_SSLKEYTYPE`.
ssl_key_type(&mut self, kind: &str) -> Result<(), Error>2020 pub fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error> {
2021 let kind = CString::new(kind)?;
2022 self.setopt_str(curl_sys::CURLOPT_SSLKEYTYPE, &kind)
2023 }
2024
2025 /// Set passphrase to private key.
2026 ///
2027 /// This will be used as the password required to use the `ssl_key`.
2028 /// You never needed a pass phrase to load a certificate but you need one to
2029 /// load your private key.
2030 ///
2031 /// By default this option is not set and corresponds to
2032 /// `CURLOPT_KEYPASSWD`.
key_password(&mut self, password: &str) -> Result<(), Error>2033 pub fn key_password(&mut self, password: &str) -> Result<(), Error> {
2034 let password = CString::new(password)?;
2035 self.setopt_str(curl_sys::CURLOPT_KEYPASSWD, &password)
2036 }
2037
2038 /// Set the SSL engine identifier.
2039 ///
2040 /// This will be used as the identifier for the crypto engine you want to
2041 /// use for your private key.
2042 ///
2043 /// By default this option is not set and corresponds to
2044 /// `CURLOPT_SSLENGINE`.
ssl_engine(&mut self, engine: &str) -> Result<(), Error>2045 pub fn ssl_engine(&mut self, engine: &str) -> Result<(), Error> {
2046 let engine = CString::new(engine)?;
2047 self.setopt_str(curl_sys::CURLOPT_SSLENGINE, &engine)
2048 }
2049
2050 /// Make this handle's SSL engine the default.
2051 ///
2052 /// By default this option is not set and corresponds to
2053 /// `CURLOPT_SSLENGINE_DEFAULT`.
ssl_engine_default(&mut self, enable: bool) -> Result<(), Error>2054 pub fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error> {
2055 self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long)
2056 }
2057
2058 // /// Enable TLS false start.
2059 // ///
2060 // /// This option determines whether libcurl should use false start during the
2061 // /// TLS handshake. False start is a mode where a TLS client will start
2062 // /// sending application data before verifying the server's Finished message,
2063 // /// thus saving a round trip when performing a full handshake.
2064 // ///
2065 // /// By default this option is not set and corresponds to
2066 // /// `CURLOPT_SSL_FALSESTARTE`.
2067 // pub fn ssl_false_start(&mut self, enable: bool) -> Result<(), Error> {
2068 // self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long)
2069 // }
2070
2071 /// Set preferred HTTP version.
2072 ///
2073 /// By default this option is not set and corresponds to
2074 /// `CURLOPT_HTTP_VERSION`.
http_version(&mut self, version: HttpVersion) -> Result<(), Error>2075 pub fn http_version(&mut self, version: HttpVersion) -> Result<(), Error> {
2076 self.setopt_long(curl_sys::CURLOPT_HTTP_VERSION, version as c_long)
2077 }
2078
2079 /// Set preferred TLS/SSL version.
2080 ///
2081 /// By default this option is not set and corresponds to
2082 /// `CURLOPT_SSLVERSION`.
ssl_version(&mut self, version: SslVersion) -> Result<(), Error>2083 pub fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error> {
2084 self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version as c_long)
2085 }
2086
2087 /// Set preferred TLS/SSL version with minimum version and maximum version.
2088 ///
2089 /// By default this option is not set and corresponds to
2090 /// `CURLOPT_SSLVERSION`.
ssl_min_max_version( &mut self, min_version: SslVersion, max_version: SslVersion, ) -> Result<(), Error>2091 pub fn ssl_min_max_version(
2092 &mut self,
2093 min_version: SslVersion,
2094 max_version: SslVersion,
2095 ) -> Result<(), Error> {
2096 let version = (min_version as c_long) | ((max_version as c_long) << 16);
2097 self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version)
2098 }
2099
2100 /// Verify the certificate's name against host.
2101 ///
2102 /// This should be disabled with great caution! It basically disables the
2103 /// security features of SSL if it is disabled.
2104 ///
2105 /// By default this option is set to `true` and corresponds to
2106 /// `CURLOPT_SSL_VERIFYHOST`.
ssl_verify_host(&mut self, verify: bool) -> Result<(), Error>2107 pub fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> {
2108 let val = if verify { 2 } else { 0 };
2109 self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYHOST, val)
2110 }
2111
2112 /// Verify the peer's SSL certificate.
2113 ///
2114 /// This should be disabled with great caution! It basically disables the
2115 /// security features of SSL if it is disabled.
2116 ///
2117 /// By default this option is set to `true` and corresponds to
2118 /// `CURLOPT_SSL_VERIFYPEER`.
ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error>2119 pub fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> {
2120 self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYPEER, verify as c_long)
2121 }
2122
2123 // /// Verify the certificate's status.
2124 // ///
2125 // /// This option determines whether libcurl verifies the status of the server
2126 // /// cert using the "Certificate Status Request" TLS extension (aka. OCSP
2127 // /// stapling).
2128 // ///
2129 // /// By default this option is set to `false` and corresponds to
2130 // /// `CURLOPT_SSL_VERIFYSTATUS`.
2131 // pub fn ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> {
2132 // self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYSTATUS, verify as c_long)
2133 // }
2134
2135 /// Specify the path to Certificate Authority (CA) bundle
2136 ///
2137 /// The file referenced should hold one or more certificates to verify the
2138 /// peer with.
2139 ///
2140 /// This option is by default set to the system path where libcurl's cacert
2141 /// bundle is assumed to be stored, as established at build time.
2142 ///
2143 /// If curl is built against the NSS SSL library, the NSS PEM PKCS#11 module
2144 /// (libnsspem.so) needs to be available for this option to work properly.
2145 ///
2146 /// By default this option is the system defaults, and corresponds to
2147 /// `CURLOPT_CAINFO`.
cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2148 pub fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2149 self.setopt_path(curl_sys::CURLOPT_CAINFO, path.as_ref())
2150 }
2151
2152 /// Set the issuer SSL certificate filename
2153 ///
2154 /// Specifies a file holding a CA certificate in PEM format. If the option
2155 /// is set, an additional check against the peer certificate is performed to
2156 /// verify the issuer is indeed the one associated with the certificate
2157 /// provided by the option. This additional check is useful in multi-level
2158 /// PKI where one needs to enforce that the peer certificate is from a
2159 /// specific branch of the tree.
2160 ///
2161 /// This option makes sense only when used in combination with the
2162 /// `ssl_verify_peer` option. Otherwise, the result of the check is not
2163 /// considered as failure.
2164 ///
2165 /// By default this option is not set and corresponds to
2166 /// `CURLOPT_ISSUERCERT`.
issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2167 pub fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2168 self.setopt_path(curl_sys::CURLOPT_ISSUERCERT, path.as_ref())
2169 }
2170
2171 /// Set the issuer SSL certificate using an in-memory blob.
2172 ///
2173 /// The specified byte buffer should contain the binary content of a CA
2174 /// certificate in the PEM format. The certificate will be copied into the
2175 /// handle.
2176 ///
2177 /// By default this option is not set and corresponds to
2178 /// `CURLOPT_ISSUERCERT_BLOB`.
issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error>2179 pub fn issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> {
2180 self.setopt_blob(curl_sys::CURLOPT_ISSUERCERT_BLOB, blob)
2181 }
2182
2183 /// Specify directory holding CA certificates
2184 ///
2185 /// Names a directory holding multiple CA certificates to verify the peer
2186 /// with. If libcurl is built against OpenSSL, the certificate directory
2187 /// must be prepared using the openssl c_rehash utility. This makes sense
2188 /// only when used in combination with the `ssl_verify_peer` option.
2189 ///
2190 /// By default this option is not set and corresponds to `CURLOPT_CAPATH`.
capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2191 pub fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2192 self.setopt_path(curl_sys::CURLOPT_CAPATH, path.as_ref())
2193 }
2194
2195 /// Specify a Certificate Revocation List file
2196 ///
2197 /// Names a file with the concatenation of CRL (in PEM format) to use in the
2198 /// certificate validation that occurs during the SSL exchange.
2199 ///
2200 /// When curl is built to use NSS or GnuTLS, there is no way to influence
2201 /// the use of CRL passed to help in the verification process. When libcurl
2202 /// is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and
2203 /// X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all
2204 /// the elements of the certificate chain if a CRL file is passed.
2205 ///
2206 /// This option makes sense only when used in combination with the
2207 /// `ssl_verify_peer` option.
2208 ///
2209 /// A specific error code (`is_ssl_crl_badfile`) is defined with the
2210 /// option. It is returned when the SSL exchange fails because the CRL file
2211 /// cannot be loaded. A failure in certificate verification due to a
2212 /// revocation information found in the CRL does not trigger this specific
2213 /// error.
2214 ///
2215 /// By default this option is not set and corresponds to `CURLOPT_CRLFILE`.
crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>2216 pub fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
2217 self.setopt_path(curl_sys::CURLOPT_CRLFILE, path.as_ref())
2218 }
2219
2220 /// Request SSL certificate information
2221 ///
2222 /// Enable libcurl's certificate chain info gatherer. With this enabled,
2223 /// libcurl will extract lots of information and data about the certificates
2224 /// in the certificate chain used in the SSL connection.
2225 ///
2226 /// By default this option is `false` and corresponds to
2227 /// `CURLOPT_CERTINFO`.
certinfo(&mut self, enable: bool) -> Result<(), Error>2228 pub fn certinfo(&mut self, enable: bool) -> Result<(), Error> {
2229 self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long)
2230 }
2231
2232 /// Set pinned public key.
2233 ///
2234 /// Pass a pointer to a zero terminated string as parameter. The string can
2235 /// be the file name of your pinned public key. The file format expected is
2236 /// "PEM" or "DER". The string can also be any number of base64 encoded
2237 /// sha256 hashes preceded by "sha256//" and separated by ";"
2238 ///
2239 /// When negotiating a TLS or SSL connection, the server sends a certificate
2240 /// indicating its identity. A public key is extracted from this certificate
2241 /// and if it does not exactly match the public key provided to this option,
2242 /// curl will abort the connection before sending or receiving any data.
2243 ///
2244 /// By default this option is not set and corresponds to
2245 /// `CURLOPT_PINNEDPUBLICKEY`.
pinned_public_key(&mut self, pubkey: &str) -> Result<(), Error>2246 pub fn pinned_public_key(&mut self, pubkey: &str) -> Result<(), Error> {
2247 let key = CString::new(pubkey)?;
2248 self.setopt_str(curl_sys::CURLOPT_PINNEDPUBLICKEY, &key)
2249 }
2250
2251 /// Specify a source for random data
2252 ///
2253 /// The file will be used to read from to seed the random engine for SSL and
2254 /// more.
2255 ///
2256 /// By default this option is not set and corresponds to
2257 /// `CURLOPT_RANDOM_FILE`.
random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>2258 pub fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> {
2259 self.setopt_path(curl_sys::CURLOPT_RANDOM_FILE, p.as_ref())
2260 }
2261
2262 /// Specify EGD socket path.
2263 ///
2264 /// Indicates the path name to the Entropy Gathering Daemon socket. It will
2265 /// be used to seed the random engine for SSL.
2266 ///
2267 /// By default this option is not set and corresponds to
2268 /// `CURLOPT_EGDSOCKET`.
egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>2269 pub fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> {
2270 self.setopt_path(curl_sys::CURLOPT_EGDSOCKET, p.as_ref())
2271 }
2272
2273 /// Specify ciphers to use for TLS.
2274 ///
2275 /// Holds the list of ciphers to use for the SSL connection. The list must
2276 /// be syntactically correct, it consists of one or more cipher strings
2277 /// separated by colons. Commas or spaces are also acceptable separators
2278 /// but colons are normally used, !, - and + can be used as operators.
2279 ///
2280 /// For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA',
2281 /// ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when
2282 /// you compile OpenSSL.
2283 ///
2284 /// You'll find more details about cipher lists on this URL:
2285 ///
2286 /// https://www.openssl.org/docs/apps/ciphers.html
2287 ///
2288 /// For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5',
2289 /// ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one
2290 /// uses this option then all known ciphers are disabled and only those
2291 /// passed in are enabled.
2292 ///
2293 /// You'll find more details about the NSS cipher lists on this URL:
2294 ///
2295 /// http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives
2296 ///
2297 /// By default this option is not set and corresponds to
2298 /// `CURLOPT_SSL_CIPHER_LIST`.
ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error>2299 pub fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> {
2300 let ciphers = CString::new(ciphers)?;
2301 self.setopt_str(curl_sys::CURLOPT_SSL_CIPHER_LIST, &ciphers)
2302 }
2303
2304 /// Enable or disable use of the SSL session-ID cache
2305 ///
2306 /// By default all transfers are done using the cache enabled. While nothing
2307 /// ever should get hurt by attempting to reuse SSL session-IDs, there seem
2308 /// to be or have been broken SSL implementations in the wild that may
2309 /// require you to disable this in order for you to succeed.
2310 ///
2311 /// This corresponds to the `CURLOPT_SSL_SESSIONID_CACHE` option.
ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error>2312 pub fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error> {
2313 self.setopt_long(curl_sys::CURLOPT_SSL_SESSIONID_CACHE, enable as c_long)
2314 }
2315
2316 /// Set SSL behavior options
2317 ///
2318 /// Inform libcurl about SSL specific behaviors.
2319 ///
2320 /// This corresponds to the `CURLOPT_SSL_OPTIONS` option.
ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error>2321 pub fn ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> {
2322 self.setopt_long(curl_sys::CURLOPT_SSL_OPTIONS, bits.bits)
2323 }
2324
2325 // /// Set SSL behavior options for proxies
2326 // ///
2327 // /// Inform libcurl about SSL specific behaviors.
2328 // ///
2329 // /// This corresponds to the `CURLOPT_PROXY_SSL_OPTIONS` option.
2330 // pub fn proxy_ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> {
2331 // self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_OPTIONS, bits.bits)
2332 // }
2333
2334 // /// Stores a private pointer-sized piece of data.
2335 // ///
2336 // /// This can be retrieved through the `private` function and otherwise
2337 // /// libcurl does not tamper with this value. This corresponds to
2338 // /// `CURLOPT_PRIVATE` and defaults to 0.
2339 // pub fn set_private(&mut self, private: usize) -> Result<(), Error> {
2340 // self.setopt_ptr(curl_sys::CURLOPT_PRIVATE, private as *const _)
2341 // }
2342 //
2343 // /// Fetches this handle's private pointer-sized piece of data.
2344 // ///
2345 // /// This corresponds to `CURLINFO_PRIVATE` and defaults to 0.
2346 // pub fn private(&mut self) -> Result<usize, Error> {
2347 // self.getopt_ptr(curl_sys::CURLINFO_PRIVATE).map(|p| p as usize)
2348 // }
2349
2350 // =========================================================================
2351 // getters
2352
2353 /// Set maximum time to wait for Expect 100 request before sending body.
2354 ///
2355 /// `curl` has internal heuristics that trigger the use of a `Expect`
2356 /// header for large enough request bodies where the client first sends the
2357 /// request header along with an `Expect: 100-continue` header. The server
2358 /// is supposed to validate the headers and respond with a `100` response
2359 /// status code after which `curl` will send the actual request body.
2360 ///
2361 /// However, if the server does not respond to the initial request
2362 /// within `CURLOPT_EXPECT_100_TIMEOUT_MS` then `curl` will send the
2363 /// request body anyways.
2364 ///
2365 /// The best-case scenario is where the request is invalid and the server
2366 /// replies with a `417 Expectation Failed` without having to wait for or process
2367 /// the request body at all. However, this behaviour can also lead to higher
2368 /// total latency since in the best case, an additional server roundtrip is required
2369 /// and in the worst case, the request is delayed by `CURLOPT_EXPECT_100_TIMEOUT_MS`.
2370 ///
2371 /// More info: https://curl.se/libcurl/c/CURLOPT_EXPECT_100_TIMEOUT_MS.html
2372 ///
2373 /// By default this option is not set and corresponds to
2374 /// `CURLOPT_EXPECT_100_TIMEOUT_MS`.
expect_100_timeout(&mut self, timeout: Duration) -> Result<(), Error>2375 pub fn expect_100_timeout(&mut self, timeout: Duration) -> Result<(), Error> {
2376 let ms = timeout.as_secs() * 1000 + (timeout.subsec_nanos() / 1_000_000) as u64;
2377 self.setopt_long(curl_sys::CURLOPT_EXPECT_100_TIMEOUT_MS, ms as c_long)
2378 }
2379
2380 /// Get info on unmet time conditional
2381 ///
2382 /// Returns if the condition provided in the previous request didn't match
2383 ///
2384 //// This corresponds to `CURLINFO_CONDITION_UNMET` and may return an error if the
2385 /// option is not supported
time_condition_unmet(&mut self) -> Result<bool, Error>2386 pub fn time_condition_unmet(&mut self) -> Result<bool, Error> {
2387 self.getopt_long(curl_sys::CURLINFO_CONDITION_UNMET).map(
2388 |r| {
2389 if r == 0 {
2390 false
2391 } else {
2392 true
2393 }
2394 },
2395 )
2396 }
2397
2398 /// Get the last used URL
2399 ///
2400 /// In cases when you've asked libcurl to follow redirects, it may
2401 /// not be the same value you set with `url`.
2402 ///
2403 /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option.
2404 ///
2405 /// Returns `Ok(None)` if no effective url is listed or `Err` if an error
2406 /// happens or the underlying bytes aren't valid utf-8.
effective_url(&mut self) -> Result<Option<&str>, Error>2407 pub fn effective_url(&mut self) -> Result<Option<&str>, Error> {
2408 self.getopt_str(curl_sys::CURLINFO_EFFECTIVE_URL)
2409 }
2410
2411 /// Get the last used URL, in bytes
2412 ///
2413 /// In cases when you've asked libcurl to follow redirects, it may
2414 /// not be the same value you set with `url`.
2415 ///
2416 /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option.
2417 ///
2418 /// Returns `Ok(None)` if no effective url is listed or `Err` if an error
2419 /// happens or the underlying bytes aren't valid utf-8.
effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>2420 pub fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2421 self.getopt_bytes(curl_sys::CURLINFO_EFFECTIVE_URL)
2422 }
2423
2424 /// Get the last response code
2425 ///
2426 /// The stored value will be zero if no server response code has been
2427 /// received. Note that a proxy's CONNECT response should be read with
2428 /// `http_connectcode` and not this.
2429 ///
2430 /// Corresponds to `CURLINFO_RESPONSE_CODE` and returns an error if this
2431 /// option is not supported.
response_code(&mut self) -> Result<u32, Error>2432 pub fn response_code(&mut self) -> Result<u32, Error> {
2433 self.getopt_long(curl_sys::CURLINFO_RESPONSE_CODE)
2434 .map(|c| c as u32)
2435 }
2436
2437 /// Get the CONNECT response code
2438 ///
2439 /// Returns the last received HTTP proxy response code to a CONNECT request.
2440 /// The returned value will be zero if no such response code was available.
2441 ///
2442 /// Corresponds to `CURLINFO_HTTP_CONNECTCODE` and returns an error if this
2443 /// option is not supported.
http_connectcode(&mut self) -> Result<u32, Error>2444 pub fn http_connectcode(&mut self) -> Result<u32, Error> {
2445 self.getopt_long(curl_sys::CURLINFO_HTTP_CONNECTCODE)
2446 .map(|c| c as u32)
2447 }
2448
2449 /// Get the remote time of the retrieved document
2450 ///
2451 /// Returns the remote time of the retrieved document (in number of seconds
2452 /// since 1 Jan 1970 in the GMT/UTC time zone). If you get `None`, it can be
2453 /// because of many reasons (it might be unknown, the server might hide it
2454 /// or the server doesn't support the command that tells document time etc)
2455 /// and the time of the document is unknown.
2456 ///
2457 /// Note that you must tell the server to collect this information before
2458 /// the transfer is made, by using the `filetime` method to
2459 /// or you will unconditionally get a `None` back.
2460 ///
2461 /// This corresponds to `CURLINFO_FILETIME` and may return an error if the
2462 /// option is not supported
filetime(&mut self) -> Result<Option<i64>, Error>2463 pub fn filetime(&mut self) -> Result<Option<i64>, Error> {
2464 self.getopt_long(curl_sys::CURLINFO_FILETIME).map(|r| {
2465 if r == -1 {
2466 None
2467 } else {
2468 Some(r as i64)
2469 }
2470 })
2471 }
2472
2473 /// Get the number of downloaded bytes
2474 ///
2475 /// Returns the total amount of bytes that were downloaded.
2476 /// The amount is only for the latest transfer and will be reset again for each new transfer.
2477 /// This counts actual payload data, what's also commonly called body.
2478 /// All meta and header data are excluded and will not be counted in this number.
2479 ///
2480 /// This corresponds to `CURLINFO_SIZE_DOWNLOAD` and may return an error if the
2481 /// option is not supported
download_size(&mut self) -> Result<f64, Error>2482 pub fn download_size(&mut self) -> Result<f64, Error> {
2483 self.getopt_double(curl_sys::CURLINFO_SIZE_DOWNLOAD)
2484 .map(|r| r as f64)
2485 }
2486
2487 /// Get the content-length of the download
2488 ///
2489 /// Returns the content-length of the download.
2490 /// This is the value read from the Content-Length: field
2491 ///
2492 /// This corresponds to `CURLINFO_CONTENT_LENGTH_DOWNLOAD` and may return an error if the
2493 /// option is not supported
content_length_download(&mut self) -> Result<f64, Error>2494 pub fn content_length_download(&mut self) -> Result<f64, Error> {
2495 self.getopt_double(curl_sys::CURLINFO_CONTENT_LENGTH_DOWNLOAD)
2496 .map(|r| r as f64)
2497 }
2498
2499 /// Get total time of previous transfer
2500 ///
2501 /// Returns the total time for the previous transfer,
2502 /// including name resolving, TCP connect etc.
2503 ///
2504 /// Corresponds to `CURLINFO_TOTAL_TIME` and may return an error if the
2505 /// option isn't supported.
total_time(&mut self) -> Result<Duration, Error>2506 pub fn total_time(&mut self) -> Result<Duration, Error> {
2507 self.getopt_double(curl_sys::CURLINFO_TOTAL_TIME)
2508 .map(double_seconds_to_duration)
2509 }
2510
2511 /// Get the name lookup time
2512 ///
2513 /// Returns the total time from the start
2514 /// until the name resolving was completed.
2515 ///
2516 /// Corresponds to `CURLINFO_NAMELOOKUP_TIME` and may return an error if the
2517 /// option isn't supported.
namelookup_time(&mut self) -> Result<Duration, Error>2518 pub fn namelookup_time(&mut self) -> Result<Duration, Error> {
2519 self.getopt_double(curl_sys::CURLINFO_NAMELOOKUP_TIME)
2520 .map(double_seconds_to_duration)
2521 }
2522
2523 /// Get the time until connect
2524 ///
2525 /// Returns the total time from the start
2526 /// until the connection to the remote host (or proxy) was completed.
2527 ///
2528 /// Corresponds to `CURLINFO_CONNECT_TIME` and may return an error if the
2529 /// option isn't supported.
connect_time(&mut self) -> Result<Duration, Error>2530 pub fn connect_time(&mut self) -> Result<Duration, Error> {
2531 self.getopt_double(curl_sys::CURLINFO_CONNECT_TIME)
2532 .map(double_seconds_to_duration)
2533 }
2534
2535 /// Get the time until the SSL/SSH handshake is completed
2536 ///
2537 /// Returns the total time it took from the start until the SSL/SSH
2538 /// connect/handshake to the remote host was completed. This time is most often
2539 /// very near to the `pretransfer_time` time, except for cases such as
2540 /// HTTP pipelining where the pretransfer time can be delayed due to waits in
2541 /// line for the pipeline and more.
2542 ///
2543 /// Corresponds to `CURLINFO_APPCONNECT_TIME` and may return an error if the
2544 /// option isn't supported.
appconnect_time(&mut self) -> Result<Duration, Error>2545 pub fn appconnect_time(&mut self) -> Result<Duration, Error> {
2546 self.getopt_double(curl_sys::CURLINFO_APPCONNECT_TIME)
2547 .map(double_seconds_to_duration)
2548 }
2549
2550 /// Get the time until the file transfer start
2551 ///
2552 /// Returns the total time it took from the start until the file
2553 /// transfer is just about to begin. This includes all pre-transfer commands
2554 /// and negotiations that are specific to the particular protocol(s) involved.
2555 /// It does not involve the sending of the protocol- specific request that
2556 /// triggers a transfer.
2557 ///
2558 /// Corresponds to `CURLINFO_PRETRANSFER_TIME` and may return an error if the
2559 /// option isn't supported.
pretransfer_time(&mut self) -> Result<Duration, Error>2560 pub fn pretransfer_time(&mut self) -> Result<Duration, Error> {
2561 self.getopt_double(curl_sys::CURLINFO_PRETRANSFER_TIME)
2562 .map(double_seconds_to_duration)
2563 }
2564
2565 /// Get the time until the first byte is received
2566 ///
2567 /// Returns the total time it took from the start until the first
2568 /// byte is received by libcurl. This includes `pretransfer_time` and
2569 /// also the time the server needs to calculate the result.
2570 ///
2571 /// Corresponds to `CURLINFO_STARTTRANSFER_TIME` and may return an error if the
2572 /// option isn't supported.
starttransfer_time(&mut self) -> Result<Duration, Error>2573 pub fn starttransfer_time(&mut self) -> Result<Duration, Error> {
2574 self.getopt_double(curl_sys::CURLINFO_STARTTRANSFER_TIME)
2575 .map(double_seconds_to_duration)
2576 }
2577
2578 /// Get the time for all redirection steps
2579 ///
2580 /// Returns the total time it took for all redirection steps
2581 /// include name lookup, connect, pretransfer and transfer before final
2582 /// transaction was started. `redirect_time` contains the complete
2583 /// execution time for multiple redirections.
2584 ///
2585 /// Corresponds to `CURLINFO_REDIRECT_TIME` and may return an error if the
2586 /// option isn't supported.
redirect_time(&mut self) -> Result<Duration, Error>2587 pub fn redirect_time(&mut self) -> Result<Duration, Error> {
2588 self.getopt_double(curl_sys::CURLINFO_REDIRECT_TIME)
2589 .map(double_seconds_to_duration)
2590 }
2591
2592 /// Get the number of redirects
2593 ///
2594 /// Corresponds to `CURLINFO_REDIRECT_COUNT` and may return an error if the
2595 /// option isn't supported.
redirect_count(&mut self) -> Result<u32, Error>2596 pub fn redirect_count(&mut self) -> Result<u32, Error> {
2597 self.getopt_long(curl_sys::CURLINFO_REDIRECT_COUNT)
2598 .map(|c| c as u32)
2599 }
2600
2601 /// Get the URL a redirect would go to
2602 ///
2603 /// Returns the URL a redirect would take you to if you would enable
2604 /// `follow_location`. This can come very handy if you think using the
2605 /// built-in libcurl redirect logic isn't good enough for you but you would
2606 /// still prefer to avoid implementing all the magic of figuring out the new
2607 /// URL.
2608 ///
2609 /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error if the
2610 /// url isn't valid utf-8 or an error happens.
redirect_url(&mut self) -> Result<Option<&str>, Error>2611 pub fn redirect_url(&mut self) -> Result<Option<&str>, Error> {
2612 self.getopt_str(curl_sys::CURLINFO_REDIRECT_URL)
2613 }
2614
2615 /// Get the URL a redirect would go to, in bytes
2616 ///
2617 /// Returns the URL a redirect would take you to if you would enable
2618 /// `follow_location`. This can come very handy if you think using the
2619 /// built-in libcurl redirect logic isn't good enough for you but you would
2620 /// still prefer to avoid implementing all the magic of figuring out the new
2621 /// URL.
2622 ///
2623 /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error.
redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>2624 pub fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2625 self.getopt_bytes(curl_sys::CURLINFO_REDIRECT_URL)
2626 }
2627
2628 /// Get size of retrieved headers
2629 ///
2630 /// Corresponds to `CURLINFO_HEADER_SIZE` and may return an error if the
2631 /// option isn't supported.
header_size(&mut self) -> Result<u64, Error>2632 pub fn header_size(&mut self) -> Result<u64, Error> {
2633 self.getopt_long(curl_sys::CURLINFO_HEADER_SIZE)
2634 .map(|c| c as u64)
2635 }
2636
2637 /// Get size of sent request.
2638 ///
2639 /// Corresponds to `CURLINFO_REQUEST_SIZE` and may return an error if the
2640 /// option isn't supported.
request_size(&mut self) -> Result<u64, Error>2641 pub fn request_size(&mut self) -> Result<u64, Error> {
2642 self.getopt_long(curl_sys::CURLINFO_REQUEST_SIZE)
2643 .map(|c| c as u64)
2644 }
2645
2646 /// Get Content-Type
2647 ///
2648 /// Returns the content-type of the downloaded object. This is the value
2649 /// read from the Content-Type: field. If you get `None`, it means that the
2650 /// server didn't send a valid Content-Type header or that the protocol
2651 /// used doesn't support this.
2652 ///
2653 /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the
2654 /// option isn't supported.
content_type(&mut self) -> Result<Option<&str>, Error>2655 pub fn content_type(&mut self) -> Result<Option<&str>, Error> {
2656 self.getopt_str(curl_sys::CURLINFO_CONTENT_TYPE)
2657 }
2658
2659 /// Get Content-Type, in bytes
2660 ///
2661 /// Returns the content-type of the downloaded object. This is the value
2662 /// read from the Content-Type: field. If you get `None`, it means that the
2663 /// server didn't send a valid Content-Type header or that the protocol
2664 /// used doesn't support this.
2665 ///
2666 /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the
2667 /// option isn't supported.
content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error>2668 pub fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error> {
2669 self.getopt_bytes(curl_sys::CURLINFO_CONTENT_TYPE)
2670 }
2671
2672 /// Get errno number from last connect failure.
2673 ///
2674 /// Note that the value is only set on failure, it is not reset upon a
2675 /// successful operation. The number is OS and system specific.
2676 ///
2677 /// Corresponds to `CURLINFO_OS_ERRNO` and may return an error if the
2678 /// option isn't supported.
os_errno(&mut self) -> Result<i32, Error>2679 pub fn os_errno(&mut self) -> Result<i32, Error> {
2680 self.getopt_long(curl_sys::CURLINFO_OS_ERRNO)
2681 .map(|c| c as i32)
2682 }
2683
2684 /// Get IP address of last connection.
2685 ///
2686 /// Returns a string holding the IP address of the most recent connection
2687 /// done with this curl handle. This string may be IPv6 when that is
2688 /// enabled.
2689 ///
2690 /// Corresponds to `CURLINFO_PRIMARY_IP` and may return an error if the
2691 /// option isn't supported.
primary_ip(&mut self) -> Result<Option<&str>, Error>2692 pub fn primary_ip(&mut self) -> Result<Option<&str>, Error> {
2693 self.getopt_str(curl_sys::CURLINFO_PRIMARY_IP)
2694 }
2695
2696 /// Get the latest destination port number
2697 ///
2698 /// Corresponds to `CURLINFO_PRIMARY_PORT` and may return an error if the
2699 /// option isn't supported.
primary_port(&mut self) -> Result<u16, Error>2700 pub fn primary_port(&mut self) -> Result<u16, Error> {
2701 self.getopt_long(curl_sys::CURLINFO_PRIMARY_PORT)
2702 .map(|c| c as u16)
2703 }
2704
2705 /// Get local IP address of last connection
2706 ///
2707 /// Returns a string holding the IP address of the local end of most recent
2708 /// connection done with this curl handle. This string may be IPv6 when that
2709 /// is enabled.
2710 ///
2711 /// Corresponds to `CURLINFO_LOCAL_IP` and may return an error if the
2712 /// option isn't supported.
local_ip(&mut self) -> Result<Option<&str>, Error>2713 pub fn local_ip(&mut self) -> Result<Option<&str>, Error> {
2714 self.getopt_str(curl_sys::CURLINFO_LOCAL_IP)
2715 }
2716
2717 /// Get the latest local port number
2718 ///
2719 /// Corresponds to `CURLINFO_LOCAL_PORT` and may return an error if the
2720 /// option isn't supported.
local_port(&mut self) -> Result<u16, Error>2721 pub fn local_port(&mut self) -> Result<u16, Error> {
2722 self.getopt_long(curl_sys::CURLINFO_LOCAL_PORT)
2723 .map(|c| c as u16)
2724 }
2725
2726 /// Get all known cookies
2727 ///
2728 /// Returns a linked-list of all cookies cURL knows (expired ones, too).
2729 ///
2730 /// Corresponds to the `CURLINFO_COOKIELIST` option and may return an error
2731 /// if the option isn't supported.
cookies(&mut self) -> Result<List, Error>2732 pub fn cookies(&mut self) -> Result<List, Error> {
2733 unsafe {
2734 let mut list = ptr::null_mut();
2735 let rc = curl_sys::curl_easy_getinfo(
2736 self.inner.handle,
2737 curl_sys::CURLINFO_COOKIELIST,
2738 &mut list,
2739 );
2740 self.cvt(rc)?;
2741 Ok(list::from_raw(list))
2742 }
2743 }
2744
2745 /// Wait for pipelining/multiplexing
2746 ///
2747 /// Set wait to `true` to tell libcurl to prefer to wait for a connection to
2748 /// confirm or deny that it can do pipelining or multiplexing before
2749 /// continuing.
2750 ///
2751 /// When about to perform a new transfer that allows pipelining or
2752 /// multiplexing, libcurl will check for existing connections to re-use and
2753 /// pipeline on. If no such connection exists it will immediately continue
2754 /// and create a fresh new connection to use.
2755 ///
2756 /// By setting this option to `true` - and having `pipelining(true, true)`
2757 /// enabled for the multi handle this transfer is associated with - libcurl
2758 /// will instead wait for the connection to reveal if it is possible to
2759 /// pipeline/multiplex on before it continues. This enables libcurl to much
2760 /// better keep the number of connections to a minimum when using pipelining
2761 /// or multiplexing protocols.
2762 ///
2763 /// The effect thus becomes that with this option set, libcurl prefers to
2764 /// wait and re-use an existing connection for pipelining rather than the
2765 /// opposite: prefer to open a new connection rather than waiting.
2766 ///
2767 /// The waiting time is as long as it takes for the connection to get up and
2768 /// for libcurl to get the necessary response back that informs it about its
2769 /// protocol and support level.
2770 ///
2771 /// This corresponds to the `CURLOPT_PIPEWAIT` option.
pipewait(&mut self, wait: bool) -> Result<(), Error>2772 pub fn pipewait(&mut self, wait: bool) -> Result<(), Error> {
2773 self.setopt_long(curl_sys::CURLOPT_PIPEWAIT, wait as c_long)
2774 }
2775
2776 // =========================================================================
2777 // Other methods
2778
2779 /// After options have been set, this will perform the transfer described by
2780 /// the options.
2781 ///
2782 /// This performs the request in a synchronous fashion. This can be used
2783 /// multiple times for one easy handle and libcurl will attempt to re-use
2784 /// the same connection for all transfers.
2785 ///
2786 /// This method will preserve all options configured in this handle for the
2787 /// next request, and if that is not desired then the options can be
2788 /// manually reset or the `reset` method can be called.
2789 ///
2790 /// Note that this method takes `&self`, which is quite important! This
2791 /// allows applications to close over the handle in various callbacks to
2792 /// call methods like `unpause_write` and `unpause_read` while a transfer is
2793 /// in progress.
perform(&self) -> Result<(), Error>2794 pub fn perform(&self) -> Result<(), Error> {
2795 let ret = unsafe { self.cvt(curl_sys::curl_easy_perform(self.inner.handle)) };
2796 panic::propagate();
2797 ret
2798 }
2799
2800 /// Some protocols have "connection upkeep" mechanisms. These mechanisms
2801 /// usually send some traffic on existing connections in order to keep them
2802 /// alive; this can prevent connections from being closed due to overzealous
2803 /// firewalls, for example.
2804 ///
2805 /// Currently the only protocol with a connection upkeep mechanism is
2806 /// HTTP/2: when the connection upkeep interval is exceeded and upkeep() is
2807 /// called, an HTTP/2 PING frame is sent on the connection.
2808 #[cfg(feature = "upkeep_7_62_0")]
upkeep(&self) -> Result<(), Error>2809 pub fn upkeep(&self) -> Result<(), Error> {
2810 let ret = unsafe { self.cvt(curl_sys::curl_easy_upkeep(self.inner.handle)) };
2811 panic::propagate();
2812 return ret;
2813 }
2814
2815 /// Unpause reading on a connection.
2816 ///
2817 /// Using this function, you can explicitly unpause a connection that was
2818 /// previously paused.
2819 ///
2820 /// A connection can be paused by letting the read or the write callbacks
2821 /// return `ReadError::Pause` or `WriteError::Pause`.
2822 ///
2823 /// To unpause, you may for example call this from the progress callback
2824 /// which gets called at least once per second, even if the connection is
2825 /// paused.
2826 ///
2827 /// The chance is high that you will get your write callback called before
2828 /// this function returns.
unpause_read(&self) -> Result<(), Error>2829 pub fn unpause_read(&self) -> Result<(), Error> {
2830 unsafe {
2831 let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_RECV_CONT);
2832 self.cvt(rc)
2833 }
2834 }
2835
2836 /// Unpause writing on a connection.
2837 ///
2838 /// Using this function, you can explicitly unpause a connection that was
2839 /// previously paused.
2840 ///
2841 /// A connection can be paused by letting the read or the write callbacks
2842 /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that
2843 /// returns pause signals to the library that it couldn't take care of any
2844 /// data at all, and that data will then be delivered again to the callback
2845 /// when the writing is later unpaused.
2846 ///
2847 /// To unpause, you may for example call this from the progress callback
2848 /// which gets called at least once per second, even if the connection is
2849 /// paused.
unpause_write(&self) -> Result<(), Error>2850 pub fn unpause_write(&self) -> Result<(), Error> {
2851 unsafe {
2852 let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_SEND_CONT);
2853 self.cvt(rc)
2854 }
2855 }
2856
2857 /// URL encodes a string `s`
url_encode(&mut self, s: &[u8]) -> String2858 pub fn url_encode(&mut self, s: &[u8]) -> String {
2859 if s.len() == 0 {
2860 return String::new();
2861 }
2862 unsafe {
2863 let p = curl_sys::curl_easy_escape(
2864 self.inner.handle,
2865 s.as_ptr() as *const _,
2866 s.len() as c_int,
2867 );
2868 assert!(!p.is_null());
2869 let ret = str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap();
2870 let ret = String::from(ret);
2871 curl_sys::curl_free(p as *mut _);
2872 ret
2873 }
2874 }
2875
2876 /// URL decodes a string `s`, returning `None` if it fails
url_decode(&mut self, s: &str) -> Vec<u8>2877 pub fn url_decode(&mut self, s: &str) -> Vec<u8> {
2878 if s.len() == 0 {
2879 return Vec::new();
2880 }
2881
2882 // Work around https://curl.haxx.se/docs/adv_20130622.html, a bug where
2883 // if the last few characters are a bad escape then curl will have a
2884 // buffer overrun.
2885 let mut iter = s.chars().rev();
2886 let orig_len = s.len();
2887 let mut data;
2888 let mut s = s;
2889 if iter.next() == Some('%') || iter.next() == Some('%') || iter.next() == Some('%') {
2890 data = s.to_string();
2891 data.push(0u8 as char);
2892 s = &data[..];
2893 }
2894 unsafe {
2895 let mut len = 0;
2896 let p = curl_sys::curl_easy_unescape(
2897 self.inner.handle,
2898 s.as_ptr() as *const _,
2899 orig_len as c_int,
2900 &mut len,
2901 );
2902 assert!(!p.is_null());
2903 let slice = slice::from_raw_parts(p as *const u8, len as usize);
2904 let ret = slice.to_vec();
2905 curl_sys::curl_free(p as *mut _);
2906 ret
2907 }
2908 }
2909
2910 // TODO: I don't think this is safe, you can drop this which has all the
2911 // callback data and then the next is use-after-free
2912 //
2913 // /// Attempts to clone this handle, returning a new session handle with the
2914 // /// same options set for this handle.
2915 // ///
2916 // /// Internal state info and things like persistent connections ccannot be
2917 // /// transferred.
2918 // ///
2919 // /// # Errors
2920 // ///
2921 // /// If a new handle could not be allocated or another error happens, `None`
2922 // /// is returned.
2923 // pub fn try_clone<'b>(&mut self) -> Option<Easy<'b>> {
2924 // unsafe {
2925 // let handle = curl_sys::curl_easy_duphandle(self.handle);
2926 // if handle.is_null() {
2927 // None
2928 // } else {
2929 // Some(Easy {
2930 // handle: handle,
2931 // data: blank_data(),
2932 // _marker: marker::PhantomData,
2933 // })
2934 // }
2935 // }
2936 // }
2937
2938 /// Receives data from a connected socket.
2939 ///
2940 /// Only useful after a successful `perform` with the `connect_only` option
2941 /// set as well.
recv(&mut self, data: &mut [u8]) -> Result<usize, Error>2942 pub fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error> {
2943 unsafe {
2944 let mut n = 0;
2945 let r = curl_sys::curl_easy_recv(
2946 self.inner.handle,
2947 data.as_mut_ptr() as *mut _,
2948 data.len(),
2949 &mut n,
2950 );
2951 if r == curl_sys::CURLE_OK {
2952 Ok(n)
2953 } else {
2954 Err(Error::new(r))
2955 }
2956 }
2957 }
2958
2959 /// Sends data over the connected socket.
2960 ///
2961 /// Only useful after a successful `perform` with the `connect_only` option
2962 /// set as well.
send(&mut self, data: &[u8]) -> Result<usize, Error>2963 pub fn send(&mut self, data: &[u8]) -> Result<usize, Error> {
2964 unsafe {
2965 let mut n = 0;
2966 let rc = curl_sys::curl_easy_send(
2967 self.inner.handle,
2968 data.as_ptr() as *const _,
2969 data.len(),
2970 &mut n,
2971 );
2972 self.cvt(rc)?;
2973 Ok(n)
2974 }
2975 }
2976
2977 /// Get a pointer to the raw underlying CURL handle.
raw(&self) -> *mut curl_sys::CURL2978 pub fn raw(&self) -> *mut curl_sys::CURL {
2979 self.inner.handle
2980 }
2981
2982 #[cfg(unix)]
setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error>2983 fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> {
2984 use std::os::unix::prelude::*;
2985 let s = CString::new(val.as_os_str().as_bytes())?;
2986 self.setopt_str(opt, &s)
2987 }
2988
2989 #[cfg(windows)]
setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error>2990 fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> {
2991 match val.to_str() {
2992 Some(s) => self.setopt_str(opt, &CString::new(s)?),
2993 None => Err(Error::new(curl_sys::CURLE_CONV_FAILED)),
2994 }
2995 }
2996
setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error>2997 fn setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error> {
2998 unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) }
2999 }
3000
setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error>3001 fn setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error> {
3002 self.setopt_ptr(opt, val.as_ptr())
3003 }
3004
setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error>3005 fn setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error> {
3006 unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) }
3007 }
3008
setopt_off_t( &mut self, opt: curl_sys::CURLoption, val: curl_sys::curl_off_t, ) -> Result<(), Error>3009 fn setopt_off_t(
3010 &mut self,
3011 opt: curl_sys::CURLoption,
3012 val: curl_sys::curl_off_t,
3013 ) -> Result<(), Error> {
3014 unsafe {
3015 let rc = curl_sys::curl_easy_setopt(self.inner.handle, opt, val);
3016 self.cvt(rc)
3017 }
3018 }
3019
setopt_blob(&mut self, opt: curl_sys::CURLoption, val: &[u8]) -> Result<(), Error>3020 fn setopt_blob(&mut self, opt: curl_sys::CURLoption, val: &[u8]) -> Result<(), Error> {
3021 let blob = curl_sys::curl_blob {
3022 data: val.as_ptr() as *const c_void as *mut c_void,
3023 len: val.len(),
3024 flags: curl_sys::CURL_BLOB_COPY,
3025 };
3026 let blob_ptr = &blob as *const curl_sys::curl_blob;
3027 unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, blob_ptr)) }
3028 }
3029
getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error>3030 fn getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error> {
3031 unsafe {
3032 let p = self.getopt_ptr(opt)?;
3033 if p.is_null() {
3034 Ok(None)
3035 } else {
3036 Ok(Some(CStr::from_ptr(p).to_bytes()))
3037 }
3038 }
3039 }
3040
getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error>3041 fn getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error> {
3042 unsafe {
3043 let mut p = 0 as *const c_char;
3044 let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
3045 self.cvt(rc)?;
3046 Ok(p)
3047 }
3048 }
3049
getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error>3050 fn getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error> {
3051 match self.getopt_bytes(opt) {
3052 Ok(None) => Ok(None),
3053 Err(e) => Err(e),
3054 Ok(Some(bytes)) => match str::from_utf8(bytes) {
3055 Ok(s) => Ok(Some(s)),
3056 Err(_) => Err(Error::new(curl_sys::CURLE_CONV_FAILED)),
3057 },
3058 }
3059 }
3060
getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error>3061 fn getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error> {
3062 unsafe {
3063 let mut p = 0;
3064 let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
3065 self.cvt(rc)?;
3066 Ok(p)
3067 }
3068 }
3069
getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error>3070 fn getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error> {
3071 unsafe {
3072 let mut p = 0 as c_double;
3073 let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p);
3074 self.cvt(rc)?;
3075 Ok(p)
3076 }
3077 }
3078
3079 /// Returns the contents of the internal error buffer, if available.
3080 ///
3081 /// When an easy handle is created it configured the `CURLOPT_ERRORBUFFER`
3082 /// parameter and instructs libcurl to store more error information into a
3083 /// buffer for better error messages and better debugging. The contents of
3084 /// that buffer are automatically coupled with all errors for methods on
3085 /// this type, but if manually invoking APIs the contents will need to be
3086 /// extracted with this method.
3087 ///
3088 /// Put another way, you probably don't need this, you're probably already
3089 /// getting nice error messages!
3090 ///
3091 /// This function will clear the internal buffer, so this is an operation
3092 /// that mutates the handle internally.
take_error_buf(&self) -> Option<String>3093 pub fn take_error_buf(&self) -> Option<String> {
3094 let mut buf = self.inner.error_buf.borrow_mut();
3095 if buf[0] == 0 {
3096 return None;
3097 }
3098 let pos = buf.iter().position(|i| *i == 0).unwrap_or(buf.len());
3099 let msg = String::from_utf8_lossy(&buf[..pos]).into_owned();
3100 buf[0] = 0;
3101 Some(msg)
3102 }
3103
cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error>3104 fn cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error> {
3105 if rc == curl_sys::CURLE_OK {
3106 return Ok(());
3107 }
3108 let mut err = Error::new(rc);
3109 if let Some(msg) = self.take_error_buf() {
3110 err.set_extra(msg);
3111 }
3112 Err(err)
3113 }
3114 }
3115
3116 impl<H: fmt::Debug> fmt::Debug for Easy2<H> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3118 f.debug_struct("Easy")
3119 .field("handle", &self.inner.handle)
3120 .field("handler", &self.inner.handler)
3121 .finish()
3122 }
3123 }
3124
3125 impl<H> Drop for Easy2<H> {
drop(&mut self)3126 fn drop(&mut self) {
3127 unsafe {
3128 curl_sys::curl_easy_cleanup(self.inner.handle);
3129 }
3130 }
3131 }
3132
header_cb<H: Handler>( buffer: *mut c_char, size: size_t, nitems: size_t, userptr: *mut c_void, ) -> size_t3133 extern "C" fn header_cb<H: Handler>(
3134 buffer: *mut c_char,
3135 size: size_t,
3136 nitems: size_t,
3137 userptr: *mut c_void,
3138 ) -> size_t {
3139 let keep_going = panic::catch(|| unsafe {
3140 let data = slice::from_raw_parts(buffer as *const u8, size * nitems);
3141 (*(userptr as *mut Inner<H>)).handler.header(data)
3142 })
3143 .unwrap_or(false);
3144 if keep_going {
3145 size * nitems
3146 } else {
3147 !0
3148 }
3149 }
3150
write_cb<H: Handler>( ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void, ) -> size_t3151 extern "C" fn write_cb<H: Handler>(
3152 ptr: *mut c_char,
3153 size: size_t,
3154 nmemb: size_t,
3155 data: *mut c_void,
3156 ) -> size_t {
3157 panic::catch(|| unsafe {
3158 let input = slice::from_raw_parts(ptr as *const u8, size * nmemb);
3159 match (*(data as *mut Inner<H>)).handler.write(input) {
3160 Ok(s) => s,
3161 Err(WriteError::Pause) => curl_sys::CURL_WRITEFUNC_PAUSE,
3162 }
3163 })
3164 .unwrap_or(!0)
3165 }
3166
read_cb<H: Handler>( ptr: *mut c_char, size: size_t, nmemb: size_t, data: *mut c_void, ) -> size_t3167 extern "C" fn read_cb<H: Handler>(
3168 ptr: *mut c_char,
3169 size: size_t,
3170 nmemb: size_t,
3171 data: *mut c_void,
3172 ) -> size_t {
3173 panic::catch(|| unsafe {
3174 let input = slice::from_raw_parts_mut(ptr as *mut u8, size * nmemb);
3175 match (*(data as *mut Inner<H>)).handler.read(input) {
3176 Ok(s) => s,
3177 Err(ReadError::Pause) => curl_sys::CURL_READFUNC_PAUSE,
3178 Err(ReadError::Abort) => curl_sys::CURL_READFUNC_ABORT,
3179 }
3180 })
3181 .unwrap_or(!0)
3182 }
3183
seek_cb<H: Handler>( data: *mut c_void, offset: curl_sys::curl_off_t, origin: c_int, ) -> c_int3184 extern "C" fn seek_cb<H: Handler>(
3185 data: *mut c_void,
3186 offset: curl_sys::curl_off_t,
3187 origin: c_int,
3188 ) -> c_int {
3189 panic::catch(|| unsafe {
3190 let from = if origin == libc::SEEK_SET {
3191 SeekFrom::Start(offset as u64)
3192 } else {
3193 panic!("unknown origin from libcurl: {}", origin);
3194 };
3195 (*(data as *mut Inner<H>)).handler.seek(from) as c_int
3196 })
3197 .unwrap_or(!0)
3198 }
3199
progress_cb<H: Handler>( data: *mut c_void, dltotal: c_double, dlnow: c_double, ultotal: c_double, ulnow: c_double, ) -> c_int3200 extern "C" fn progress_cb<H: Handler>(
3201 data: *mut c_void,
3202 dltotal: c_double,
3203 dlnow: c_double,
3204 ultotal: c_double,
3205 ulnow: c_double,
3206 ) -> c_int {
3207 let keep_going = panic::catch(|| unsafe {
3208 (*(data as *mut Inner<H>))
3209 .handler
3210 .progress(dltotal, dlnow, ultotal, ulnow)
3211 })
3212 .unwrap_or(false);
3213 if keep_going {
3214 0
3215 } else {
3216 1
3217 }
3218 }
3219
3220 // 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_int3221 extern "C" fn debug_cb<H: Handler>(
3222 _handle: *mut curl_sys::CURL,
3223 kind: curl_sys::curl_infotype,
3224 data: *mut c_char,
3225 size: size_t,
3226 userptr: *mut c_void,
3227 ) -> c_int {
3228 panic::catch(|| unsafe {
3229 let data = slice::from_raw_parts(data as *const u8, size);
3230 let kind = match kind {
3231 curl_sys::CURLINFO_TEXT => InfoType::Text,
3232 curl_sys::CURLINFO_HEADER_IN => InfoType::HeaderIn,
3233 curl_sys::CURLINFO_HEADER_OUT => InfoType::HeaderOut,
3234 curl_sys::CURLINFO_DATA_IN => InfoType::DataIn,
3235 curl_sys::CURLINFO_DATA_OUT => InfoType::DataOut,
3236 curl_sys::CURLINFO_SSL_DATA_IN => InfoType::SslDataIn,
3237 curl_sys::CURLINFO_SSL_DATA_OUT => InfoType::SslDataOut,
3238 _ => return,
3239 };
3240 (*(userptr as *mut Inner<H>)).handler.debug(kind, data)
3241 });
3242 0
3243 }
3244
ssl_ctx_cb<H: Handler>( _handle: *mut curl_sys::CURL, ssl_ctx: *mut c_void, data: *mut c_void, ) -> curl_sys::CURLcode3245 extern "C" fn ssl_ctx_cb<H: Handler>(
3246 _handle: *mut curl_sys::CURL,
3247 ssl_ctx: *mut c_void,
3248 data: *mut c_void,
3249 ) -> curl_sys::CURLcode {
3250 let res = panic::catch(|| unsafe {
3251 match (*(data as *mut Inner<H>)).handler.ssl_ctx(ssl_ctx) {
3252 Ok(()) => curl_sys::CURLE_OK,
3253 Err(e) => e.code(),
3254 }
3255 });
3256 // Default to a generic SSL error in case of panic. This
3257 // shouldn't really matter since the error should be
3258 // propagated later on but better safe than sorry...
3259 res.unwrap_or(curl_sys::CURLE_SSL_CONNECT_ERROR)
3260 }
3261
3262 // 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_t3263 extern "C" fn opensocket_cb<H: Handler>(
3264 data: *mut c_void,
3265 _purpose: curl_sys::curlsocktype,
3266 address: *mut curl_sys::curl_sockaddr,
3267 ) -> curl_sys::curl_socket_t {
3268 let res = panic::catch(|| unsafe {
3269 (*(data as *mut Inner<H>))
3270 .handler
3271 .open_socket((*address).family, (*address).socktype, (*address).protocol)
3272 .unwrap_or(curl_sys::CURL_SOCKET_BAD)
3273 });
3274 res.unwrap_or(curl_sys::CURL_SOCKET_BAD)
3275 }
3276
double_seconds_to_duration(seconds: f64) -> Duration3277 fn double_seconds_to_duration(seconds: f64) -> Duration {
3278 let whole_seconds = seconds.trunc() as u64;
3279 let nanos = seconds.fract() * 1_000_000_000f64;
3280 Duration::new(whole_seconds, nanos as u32)
3281 }
3282
3283 #[test]
double_seconds_to_duration_whole_second()3284 fn double_seconds_to_duration_whole_second() {
3285 let dur = double_seconds_to_duration(1.0);
3286 assert_eq!(dur.as_secs(), 1);
3287 assert_eq!(dur.subsec_nanos(), 0);
3288 }
3289
3290 #[test]
double_seconds_to_duration_sub_second1()3291 fn double_seconds_to_duration_sub_second1() {
3292 let dur = double_seconds_to_duration(0.0);
3293 assert_eq!(dur.as_secs(), 0);
3294 assert_eq!(dur.subsec_nanos(), 0);
3295 }
3296
3297 #[test]
double_seconds_to_duration_sub_second2()3298 fn double_seconds_to_duration_sub_second2() {
3299 let dur = double_seconds_to_duration(0.5);
3300 assert_eq!(dur.as_secs(), 0);
3301 assert_eq!(dur.subsec_nanos(), 500_000_000);
3302 }
3303
3304 impl Auth {
3305 /// Creates a new set of authentications with no members.
3306 ///
3307 /// An `Auth` structure is used to configure which forms of authentication
3308 /// are attempted when negotiating connections with servers.
new() -> Auth3309 pub fn new() -> Auth {
3310 Auth { bits: 0 }
3311 }
3312
3313 /// HTTP Basic authentication.
3314 ///
3315 /// This is the default choice, and the only method that is in wide-spread
3316 /// use and supported virtually everywhere. This sends the user name and
3317 /// password over the network in plain text, easily captured by others.
basic(&mut self, on: bool) -> &mut Auth3318 pub fn basic(&mut self, on: bool) -> &mut Auth {
3319 self.flag(curl_sys::CURLAUTH_BASIC, on)
3320 }
3321
3322 /// HTTP Digest authentication.
3323 ///
3324 /// Digest authentication is defined in RFC 2617 and is a more secure way to
3325 /// do authentication over public networks than the regular old-fashioned
3326 /// Basic method.
digest(&mut self, on: bool) -> &mut Auth3327 pub fn digest(&mut self, on: bool) -> &mut Auth {
3328 self.flag(curl_sys::CURLAUTH_DIGEST, on)
3329 }
3330
3331 /// HTTP Digest authentication with an IE flavor.
3332 ///
3333 /// Digest authentication is defined in RFC 2617 and is a more secure way to
3334 /// do authentication over public networks than the regular old-fashioned
3335 /// Basic method. The IE flavor is simply that libcurl will use a special
3336 /// "quirk" that IE is known to have used before version 7 and that some
3337 /// servers require the client to use.
digest_ie(&mut self, on: bool) -> &mut Auth3338 pub fn digest_ie(&mut self, on: bool) -> &mut Auth {
3339 self.flag(curl_sys::CURLAUTH_DIGEST_IE, on)
3340 }
3341
3342 /// HTTP Negotiate (SPNEGO) authentication.
3343 ///
3344 /// Negotiate authentication is defined in RFC 4559 and is the most secure
3345 /// way to perform authentication over HTTP.
3346 ///
3347 /// You need to build libcurl with a suitable GSS-API library or SSPI on
3348 /// Windows for this to work.
gssnegotiate(&mut self, on: bool) -> &mut Auth3349 pub fn gssnegotiate(&mut self, on: bool) -> &mut Auth {
3350 self.flag(curl_sys::CURLAUTH_GSSNEGOTIATE, on)
3351 }
3352
3353 /// HTTP NTLM authentication.
3354 ///
3355 /// A proprietary protocol invented and used by Microsoft. It uses a
3356 /// challenge-response and hash concept similar to Digest, to prevent the
3357 /// password from being eavesdropped.
3358 ///
3359 /// You need to build libcurl with either OpenSSL, GnuTLS or NSS support for
3360 /// this option to work, or build libcurl on Windows with SSPI support.
ntlm(&mut self, on: bool) -> &mut Auth3361 pub fn ntlm(&mut self, on: bool) -> &mut Auth {
3362 self.flag(curl_sys::CURLAUTH_NTLM, on)
3363 }
3364
3365 /// NTLM delegating to winbind helper.
3366 ///
3367 /// Authentication is performed by a separate binary application that is
3368 /// executed when needed. The name of the application is specified at
3369 /// compile time but is typically /usr/bin/ntlm_auth
3370 ///
3371 /// Note that libcurl will fork when necessary to run the winbind
3372 /// application and kill it when complete, calling waitpid() to await its
3373 /// exit when done. On POSIX operating systems, killing the process will
3374 /// cause a SIGCHLD signal to be raised (regardless of whether
3375 /// CURLOPT_NOSIGNAL is set), which must be handled intelligently by the
3376 /// application. In particular, the application must not unconditionally
3377 /// call wait() in its SIGCHLD signal handler to avoid being subject to a
3378 /// race condition. This behavior is subject to change in future versions of
3379 /// libcurl.
3380 ///
3381 /// A proprietary protocol invented and used by Microsoft. It uses a
3382 /// challenge-response and hash concept similar to Digest, to prevent the
3383 /// password from being eavesdropped.
ntlm_wb(&mut self, on: bool) -> &mut Auth3384 pub fn ntlm_wb(&mut self, on: bool) -> &mut Auth {
3385 self.flag(curl_sys::CURLAUTH_NTLM_WB, on)
3386 }
3387
flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth3388 fn flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth {
3389 if on {
3390 self.bits |= bit as c_long;
3391 } else {
3392 self.bits &= !bit as c_long;
3393 }
3394 self
3395 }
3396 }
3397
3398 impl fmt::Debug for Auth {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3400 let bits = self.bits as c_ulong;
3401 f.debug_struct("Auth")
3402 .field("basic", &(bits & curl_sys::CURLAUTH_BASIC != 0))
3403 .field("digest", &(bits & curl_sys::CURLAUTH_DIGEST != 0))
3404 .field("digest_ie", &(bits & curl_sys::CURLAUTH_DIGEST_IE != 0))
3405 .field(
3406 "gssnegotiate",
3407 &(bits & curl_sys::CURLAUTH_GSSNEGOTIATE != 0),
3408 )
3409 .field("ntlm", &(bits & curl_sys::CURLAUTH_NTLM != 0))
3410 .field("ntlm_wb", &(bits & curl_sys::CURLAUTH_NTLM_WB != 0))
3411 .finish()
3412 }
3413 }
3414
3415 impl SslOpt {
3416 /// Creates a new set of SSL options.
new() -> SslOpt3417 pub fn new() -> SslOpt {
3418 SslOpt { bits: 0 }
3419 }
3420
3421 /// Tells libcurl to disable certificate revocation checks for those SSL
3422 /// backends where such behavior is present.
3423 ///
3424 /// Currently this option is only supported for WinSSL (the native Windows
3425 /// SSL library), with an exception in the case of Windows' Untrusted
3426 /// Publishers blacklist which it seems can't be bypassed. This option may
3427 /// have broader support to accommodate other SSL backends in the future.
3428 /// https://curl.haxx.se/docs/ssl-compared.html
no_revoke(&mut self, on: bool) -> &mut SslOpt3429 pub fn no_revoke(&mut self, on: bool) -> &mut SslOpt {
3430 self.flag(curl_sys::CURLSSLOPT_NO_REVOKE, on)
3431 }
3432
3433 /// Tells libcurl to not attempt to use any workarounds for a security flaw
3434 /// in the SSL3 and TLS1.0 protocols.
3435 ///
3436 /// If this option isn't used or this bit is set to 0, the SSL layer libcurl
3437 /// uses may use a work-around for this flaw although it might cause
3438 /// interoperability problems with some (older) SSL implementations.
3439 ///
3440 /// > WARNING: avoiding this work-around lessens the security, and by
3441 /// > setting this option to 1 you ask for exactly that. This option is only
3442 /// > supported for DarwinSSL, NSS and OpenSSL.
allow_beast(&mut self, on: bool) -> &mut SslOpt3443 pub fn allow_beast(&mut self, on: bool) -> &mut SslOpt {
3444 self.flag(curl_sys::CURLSSLOPT_ALLOW_BEAST, on)
3445 }
3446
flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt3447 fn flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt {
3448 if on {
3449 self.bits |= bit as c_long;
3450 } else {
3451 self.bits &= !bit as c_long;
3452 }
3453 self
3454 }
3455 }
3456
3457 impl fmt::Debug for SslOpt {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result3458 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3459 f.debug_struct("SslOpt")
3460 .field(
3461 "no_revoke",
3462 &(self.bits & curl_sys::CURLSSLOPT_NO_REVOKE != 0),
3463 )
3464 .field(
3465 "allow_beast",
3466 &(self.bits & curl_sys::CURLSSLOPT_ALLOW_BEAST != 0),
3467 )
3468 .finish()
3469 }
3470 }
3471