Struct curl::easy::Easy
[−]
[src]
pub struct Easy { // some fields omitted }
Raw bindings to a libcurl "easy session".
This type corresponds to the CURL
type in libcurl, and is probably what
you want for just sending off a simple HTTP request and fetching a response.
Each easy handle can be thought of as a large builder before calling the
final perform
function.
There are many many configuration options for each Easy
handle, and they
should all have their own documentation indicating what it affects and how
it interacts with other options. Some implementations of libcurl can use
this handle to interact with many different protocols, although by default
this crate only guarantees the HTTP/HTTPS protocols working.
Note that almost all methods on this structure which configure various
properties return a Result
. This is largely used to detect whether the
underlying implementation of libcurl actually implements the option being
requested. If you're linked to a version of libcurl which doesn't support
the option, then an error will be returned. Some options also perform some
validation when they're set, and the error is returned through this vector.
Examples
Creating a handle which can be used later
use curl::easy::Easy; let handle = Easy::new();
Send an HTTP request, writing the response to stdout.
use std::io::{stdout, Write}; use curl::easy::Easy; let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); handle.write_function(|data| { Ok(stdout().write(data).unwrap()) }).unwrap(); handle.perform().unwrap();
Collect all output of an HTTP request to a vector.
use curl::easy::Easy; let mut data = Vec::new(); let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); { let mut transfer = handle.transfer(); transfer.write_function(|new_data| { data.extend_from_slice(new_data); Ok(new_data.len()) }).unwrap(); transfer.perform().unwrap(); } println!("{:?}", data);
More examples of various properties of an HTTP request can be found on the specific methods as well.
Methods
impl Easy
fn new() -> Easy
Creates a new "easy" handle which is the core of almost all operations in libcurl.
To use a handle, applications typically configure a number of options
followed by a call to perform
. Options are preserved across calls to
perform
and need to be reset manually (or via the reset
method) if
this is not desired.
fn verbose(&mut self, verbose: bool) -> Result<(), Error>
Configures this handle to have verbose output to help debug protocol information.
By default output goes to stderr, but the stderr
function on this type
can configure that. You can also use the debug_function
method to get
all protocol data sent and received.
By default, this option is false
.
fn show_header(&mut self, show: bool) -> Result<(), Error>
Indicates whether header information is streamed to the output body of this request.
This option is only relevant for protocols which have header metadata
(like http or ftp). It's not generally possible to extract headers
from the body if using this method, that use case should be intended for
the header_function
method.
To set HTTP headers, use the http_header
method.
By default, this option is false
and corresponds to
CURLOPT_HEADER
.
fn progress(&mut self, progress: bool) -> Result<(), Error>
Indicates whether a progress meter will be shown for requests done with this handle.
This will also prevent the progress_function
from being called.
By default this option is false
and corresponds to
CURLOPT_NOPROGRESS
.
fn signal(&mut self, signal: bool) -> Result<(), Error>
Inform libcurl whether or not it should install signal handlers or attempt to use signals to perform library functions.
If this option is disabled then timeouts during name resolution will not work unless libcurl is built against c-ares. Note that enabling this option, however, may not cause libcurl to work with multiple threads.
By default this option is false
and corresponds to CURLOPT_NOSIGNAL
.
Note that this default is different than libcurl as it is intended
that this library is threadsafe by default. See the libcurl docs for
some more information.
fn wildcard_match(&mut self, m: bool) -> Result<(), Error>
Indicates whether multiple files will be transferred based on the file name pattern.
The last part of a filename uses fnmatch-like pattern matching.
By default this option is false
and corresponds to
CURLOPT_WILDCARDMATCH
.
fn write_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(&[u8]) -> Result<usize, WriteError> + Send + 'static
Set callback for writing received data.
This callback function gets called by libcurl as soon as there is data received that needs to be saved.
The callback function will be passed as much data as possible in all
invokes, but you must not make any assumptions. It may be one byte, it
may be thousands. If show_header
is enabled, which makes header data
get passed to the write callback, you can get up to
CURL_MAX_HTTP_HEADER
bytes of header data passed into it. This
usually means 100K.
This function may be called with zero bytes data if the transferred file is empty.
The callback should return the number of bytes actually taken care of.
If that amount differs from the amount passed to your callback function,
it'll signal an error condition to the library. This will cause the
transfer to get aborted and the libcurl function used will return
an error with is_write_error
.
If your callback function returns Err(WriteError::Pause)
it will cause
this transfer to become paused. See unpause_write
for further details.
By default data is sent into the void, and this corresponds to the
CURLOPT_WRITEFUNCTION
and CURLOPT_WRITEDATA
options.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using write_function
to configure a
callback that can reference stack-local data.
Examples
use std::io::{stdout, Write}; use curl::easy::Easy; let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); handle.write_function(|data| { Ok(stdout().write(data).unwrap()) }).unwrap(); handle.perform().unwrap();
Writing to a stack-local buffer
use std::io::{stdout, Write}; use curl::easy::Easy; let mut buf = Vec::new(); let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); let mut transfer = handle.transfer(); transfer.write_function(|data| { buf.extend_from_slice(data); Ok(data.len()) }).unwrap(); transfer.perform().unwrap();
fn read_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(&mut [u8]) -> Result<usize, ReadError> + Send + 'static
Read callback for data uploads.
This callback function gets called by libcurl as soon as it needs to read data in order to send it to the peer - like if you ask it to upload or post data to the server.
Your function must then return the actual number of bytes that it stored in that memory area. Returning 0 will signal end-of-file to the library and cause it to stop the current transfer.
If you stop the current transfer by returning 0 "pre-maturely" (i.e before the server expected it, like when you've said you will upload N bytes and you upload less than N bytes), you may experience that the server "hangs" waiting for the rest of the data that won't come.
The read callback may return Err(ReadError::Abort)
to stop the
current operation immediately, resulting in a is_aborted_by_callback
error code from the transfer.
The callback can return Err(ReadError::Pause)
to cause reading from
this connection to pause. See unpause_read
for further details.
By default data not input, and this corresponds to the
CURLOPT_READFUNCTION
and CURLOPT_READDATA
options.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using read_function
to configure a
callback that can reference stack-local data.
Examples
Read input from stdin
use std::io::{stdin, Read}; use curl::easy::Easy; let mut handle = Easy::new(); handle.url("https://example.com/login").unwrap(); handle.read_function(|into| { Ok(stdin().read(into).unwrap()) }).unwrap(); handle.post(true).unwrap(); handle.perform().unwrap();
Reading from stack-local data:
use std::io::{stdin, Read}; use curl::easy::Easy; let mut data_to_upload = &b"foobar"[..]; let mut handle = Easy::new(); handle.url("https://example.com/login").unwrap(); handle.post(true).unwrap(); let mut transfer = handle.transfer(); transfer.read_function(|into| { Ok(data_to_upload.read(into).unwrap()) }).unwrap(); transfer.perform().unwrap();
fn seek_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(SeekFrom) -> SeekResult + Send + 'static
User callback for seeking in input stream.
This function gets called by libcurl to seek to a certain position in the input stream and can be used to fast forward a file in a resumed upload (instead of reading all uploaded bytes with the normal read function/callback). It is also called to rewind a stream when data has already been sent to the server and needs to be sent again. This may happen when doing a HTTP PUT or POST with a multi-pass authentication method, or when an existing HTTP connection is reused too late and the server closes the connection.
The callback function must return SeekResult::Ok
on success,
SeekResult::Fail
to cause the upload operation to fail or
SeekResult::CantSeek
to indicate that while the seek failed, libcurl
is free to work around the problem if possible. The latter can sometimes
be done by instead reading from the input or similar.
By default data this option is not set, and this corresponds to the
CURLOPT_SEEKFUNCTION
and CURLOPT_SEEKDATA
options.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using seek_function
to configure a
callback that can reference stack-local data.
fn progress_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(f64, f64, f64, f64) -> bool + Send + 'static
Callback to progress meter function
This function gets called by libcurl instead of its internal equivalent with a frequent interval. While data is being transferred it will be called very frequently, and during slow periods like when nothing is being transferred it can slow down to about one call per second.
The callback gets told how much data libcurl will transfer and has transferred, in number of bytes. The first argument is the total number of bytes libcurl expects to download in this transfer. The second argument is the number of bytes downloaded so far. The third argument is the total number of bytes libcurl expects to upload in this transfer. The fourth argument is the number of bytes uploaded so far.
Unknown/unused argument values passed to the callback will be set to zero (like if you only download data, the upload size will remain 0). Many times the callback will be called one or more times first, before it knows the data sizes so a program must be made to handle that.
Returning false
from this callback will cause libcurl to abort the
transfer and return is_aborted_by_callback
.
If you transfer data with the multi interface, this function will not be called during periods of idleness unless you call the appropriate libcurl function that performs transfers.
noprogress
must be set to 0 to make this function actually get
called.
By default this function calls an internal method and corresponds to
CURLOPT_XFERINFOFUNCTION
and CURLOPT_XFERINFODATA
.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using progress_function
to configure a
callback that can reference stack-local data.
fn debug_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(InfoType, &[u8]) + Send + 'static
Specify a debug callback
debug_function
replaces the standard debug function used when
verbose
is in effect. This callback receives debug information,
as specified in the type argument.
By default this option is not set and corresponds to the
CURLOPT_DEBUGFUNCTION
and CURLOPT_DEBUGDATA
options.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using debug_function
to configure a
callback that can reference stack-local data.
fn header_function<F>(&mut self, f: F) -> Result<(), Error> where F: FnMut(&[u8]) -> bool + Send + 'static
Callback that receives header data
This function gets called by libcurl as soon as it has received header
data. The header callback will be called once for each header and only
complete header lines are passed on to the callback. Parsing headers is
very easy using this. If this callback returns false
it'll signal an
error to the library. This will cause the transfer to get aborted and
the libcurl function in progress will return is_write_error
.
A complete HTTP header that is passed to this function can be up to CURL_MAX_HTTP_HEADER (100K) bytes.
It's important to note that the callback will be invoked for the headers of all responses received after initiating a request and not just the final response. This includes all responses which occur during authentication negotiation. If you need to operate on only the headers from the final response, you will need to collect headers in the callback yourself and use HTTP status lines, for example, to delimit response boundaries.
When a server sends a chunked encoded transfer, it may contain a trailer. That trailer is identical to a HTTP header and if such a trailer is received it is passed to the application using this callback as well. There are several ways to detect it being a trailer and not an ordinary header: 1) it comes after the response-body. 2) it comes after the final header line (CR LF) 3) a Trailer: header among the regular response-headers mention what header(s) to expect in the trailer.
For non-HTTP protocols like FTP, POP3, IMAP and SMTP this function will get called with the server responses to the commands that libcurl sends.
By default this option is not set and corresponds to the
CURLOPT_HEADERFUNCTION
and CURLOPT_HEADERDATA
options.
Note that the lifetime bound on this function is 'static
, but that
is often too restrictive. To use stack data consider calling the
transfer
method and then using header_function
to configure a
callback that can reference stack-local data.
Examples
use std::str; use curl::easy::Easy; let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); handle.header_function(|header| { print!("header: {}", str::from_utf8(header).unwrap()); true }).unwrap(); handle.perform().unwrap();
Collecting headers to a stack local vector
use std::str; use curl::easy::Easy; let mut headers = Vec::new(); let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); { let mut transfer = handle.transfer(); transfer.header_function(|header| { headers.push(str::from_utf8(header).unwrap().to_string()); true }).unwrap(); transfer.perform().unwrap(); } println!("{:?}", headers);
fn fail_on_error(&mut self, fail: bool) -> Result<(), Error>
Indicates whether this library will fail on HTTP response codes >= 400.
This method is not fail-safe especially when authentication is involved.
By default this option is false
and corresponds to
CURLOPT_FAILONERROR
.
fn url(&mut self, url: &str) -> Result<(), Error>
Provides the URL which this handle will work with.
The string provided must be URL-encoded with the format:
scheme://host:port/path
The syntax is not validated as part of this function and that is deferred until later.
By default this option is not set and perform
will not work until it
is set. This option corresponds to CURLOPT_URL
.
fn port(&mut self, port: u16) -> Result<(), Error>
Configures the port number to connect to, instead of the one specified in the URL or the default of the protocol.
fn proxy(&mut self, url: &str) -> Result<(), Error>
Provide the URL of a proxy to use.
By default this option is not set and corresponds to CURLOPT_PROXY
.
fn proxy_port(&mut self, port: u16) -> Result<(), Error>
Provide port number the proxy is listening on.
By default this option is not set (the default port for the proxy
protocol is used) and corresponds to CURLOPT_PROXYPORT
.
fn proxy_type(&mut self, kind: ProxyType) -> Result<(), Error>
Indicates the type of proxy being used.
By default this option is ProxyType::Http
and corresponds to
CURLOPT_PROXYTYPE
.
fn noproxy(&mut self, skip: &str) -> Result<(), Error>
Provide a list of hosts that should not be proxied to.
This string is a comma-separated list of hosts which should not use the
proxy specified for connections. A single *
character is also accepted
as a wildcard for all hosts.
By default this option is not set and corresponds to
CURLOPT_NOPROXY
.
fn http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error>
Inform curl whether it should tunnel all operations through the proxy.
This essentially means that a CONNECT
is sent to the proxy for all
outbound requests.
By default this option is false
and corresponds to
CURLOPT_HTTPPROXYTUNNEL
.
fn interface(&mut self, interface: &str) -> Result<(), Error>
Tell curl which interface to bind to for an outgoing network interface.
The interface name, IP address, or host name can be specified here.
By default this option is not set and corresponds to
CURLOPT_INTERFACE
.
fn set_local_port(&mut self, port: u16) -> Result<(), Error>
Indicate which port should be bound to locally for this connection.
By default this option is 0 (any port) and corresponds to
CURLOPT_LOCALPORT
.
fn local_port_range(&mut self, range: u16) -> Result<(), Error>
Indicates the number of attempts libcurl will perform to find a working port number.
By default this option is 1 and corresponds to
CURLOPT_LOCALPORTRANGE
.
fn dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error>
Sets the timeout of how long name resolves will be kept in memory.
This is distinct from DNS TTL options and is entirely speculative.
By default this option is 60s and corresponds to
CURLOPT_DNS_CACHE_TIMEOUT
.
fn buffer_size(&mut self, size: usize) -> Result<(), Error>
Specify the preferred receive buffer size, in bytes.
This is treated as a request, not an order, and the main point of this is that the write callback may get called more often with smaller chunks.
By default this option is the maximum write size and corresopnds to
CURLOPT_BUFFERSIZE
.
fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error>
Configures whether the TCP_NODELAY option is set, or Nagle's algorithm is disabled.
The purpose of Nagle's algorithm is to minimize the number of small packet's on the network, and disabling this may be less efficient in some situations.
By default this option is false
and corresponds to
CURLOPT_TCP_NODELAY
.
fn address_scope(&mut self, scope: u32) -> Result<(), Error>
Configures the scope for local IPv6 addresses.
Sets the scope_id value to use when connecting to IPv6 or link-local addresses.
By default this value is 0 and corresponds to CURLOPT_ADDRESS_SCOPE
fn username(&mut self, user: &str) -> Result<(), Error>
Configures the username to pass as authentication for this connection.
By default this value is not set and corresponds to CURLOPT_USERNAME
.
fn password(&mut self, pass: &str) -> Result<(), Error>
Configures the password to pass as authentication for this connection.
By default this value is not set and corresponds to CURLOPT_PASSWORD
.
fn proxy_username(&mut self, user: &str) -> Result<(), Error>
Configures the proxy username to pass as authentication for this connection.
By default this value is not set and corresponds to
CURLOPT_PROXYUSERNAME
.
fn proxy_password(&mut self, pass: &str) -> Result<(), Error>
Configures the proxy password to pass as authentication for this connection.
By default this value is not set and corresponds to
CURLOPT_PROXYPASSWORD
.
fn autoreferer(&mut self, enable: bool) -> Result<(), Error>
Indicates whether the referer header is automatically updated
By default this option is false
and corresponds to
CURLOPT_AUTOREFERER
.
fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error>
Enables automatic decompression of HTTP downloads.
Sets the contents of the Accept-Encoding header sent in an HTTP request. This enables decoding of a response with Content-Encoding.
Currently supported encoding are identity
, zlib
, and gzip
. A
zero-length string passed in will send all accepted encodings.
By default this option is not set and corresponds to
CURLOPT_ACCEPT_ENCODING
.
fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error>
Request the HTTP Transfer Encoding.
By default this option is false
and corresponds to
CURLOPT_TRANSFER_ENCODING
.
fn follow_location(&mut self, enable: bool) -> Result<(), Error>
Follow HTTP 3xx redirects.
Indicates whether any Location
headers in the response should get
followed.
By default this option is false
and corresponds to
CURLOPT_FOLLOWLOCATION
.
fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error>
Send credentials to hosts other than the first as well.
Sends username/password credentials even when the host changes as part of a redirect.
By default this option is false
and corresponds to
CURLOPT_UNRESTRICTED_AUTH
.
fn max_redirections(&mut self, max: u32) -> Result<(), Error>
Set the maximum number of redirects allowed.
A value of 0 will refuse any redirect.
By default this option is -1
(unlimited) and corresponds to
CURLOPT_MAXREDIRS
.
fn put(&mut self, enable: bool) -> Result<(), Error>
Make an HTTP PUT request.
By default this option is false
and corresponds to CURLOPT_PUT
.
fn post(&mut self, enable: bool) -> Result<(), Error>
Make an HTTP POST request.
This will also make the library use the
Content-Type: application/x-www-form-urlencoded
header.
POST data can be specified through post_fields
or by specifying a read
function.
By default this option is false
and corresponds to CURLOPT_POST
.
fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error>
Configures the data that will be uploaded as part of a POST.
Note that the data is copied into this handle and if that's not desired then the read callbacks can be used instead.
By default this option is not set and corresponds to
CURLOPT_COPYPOSTFIELDS
.
fn post_field_size(&mut self, size: u64) -> Result<(), Error>
Configures the size of data that's going to be uploaded as part of a POST operation.
This is called automaticsally as part of post_fields
and should only
be called if data is being provided in a read callback (and even then
it's optional).
By default this option is not set and corresponds to
CURLOPT_POSTFIELDSIZE_LARGE
.
fn referer(&mut self, referer: &str) -> Result<(), Error>
Sets the HTTP referer header
By default this option is not set and corresponds to CURLOPT_REFERER
.
fn useragent(&mut self, useragent: &str) -> Result<(), Error>
Sets the HTTP user-agent header
By default this option is not set and corresponds to
CURLOPT_USERAGENT
.
fn http_headers(&mut self, list: List) -> Result<(), Error>
Add some headers to this HTTP request.
If you add a header that is otherwise used internally, the value here
takes precedence. If a header is added with no content (like Accept:
)
the internally the header will get disabled. To add a header with no
content, use the form MyHeader;
(not the trailing semicolon).
Headers must not be CRLF terminated. Many replaced headers have common shortcuts which should be prefered.
By default this option is not set and corresponds to
CURLOPT_HTTPHEADER
Examples
use curl::easy::{Easy, List}; let mut list = List::new(); list.append("Foo: bar").unwrap(); list.append("Bar: baz").unwrap(); let mut handle = Easy::new(); handle.url("https://www.rust-lang.org/").unwrap(); handle.http_headers(list).unwrap(); handle.perform().unwrap();
fn cookie(&mut self, cookie: &str) -> Result<(), Error>
Set the contents of the HTTP Cookie header.
Pass a string of the form name=contents
for one cookie value or
name1=val1; name2=val2
for multiple values.
Using this option multiple times will only make the latest string
override the previous ones. This option will not enable the cookie
engine, use cookie_file
or cookie_jar
to do that.
By default this option is not set and corresponds to CURLOPT_COOKIE
.
fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>
Set the file name to read cookies from.
The cookie data can be in either the old Netscape / Mozilla cookie data format or just regular HTTP headers (Set-Cookie style) dumped to a file.
This also enables the cookie engine, making libcurl parse and send cookies on subsequent requests with this handle.
Given an empty or non-existing file or by passing the empty string ("") to this option, you can enable the cookie engine without reading any initial cookies.
If you use this option multiple times, you just add more files to read. Subsequent files will add more cookies.
By default this option is not set and corresponds to
CURLOPT_COOKIEFILE
.
fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error>
Set the file name to store cookies to.
This will make libcurl write all internally known cookies to the file when this handle is dropped. If no cookies are known, no file will be created. Specify "-" as filename to instead have the cookies written to stdout. Using this option also enables cookies for this session, so if you for example follow a location it will make matching cookies get sent accordingly.
Note that libcurl doesn't read any cookies from the cookie jar. If you
want to read cookies from a file, use cookie_file
.
By default this option is not set and corresponds to
CURLOPT_COOKIEJAR
.
fn cookie_session(&mut self, session: bool) -> Result<(), Error>
Start a new cookie session
Marks this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.
By default this option is false
and corresponds to
CURLOPT_COOKIESESSION
.
fn cookie_list(&mut self, cookie: &str) -> Result<(), Error>
Add to or manipulate cookies held in memory.
Such a cookie can be either a single line in Netscape / Mozilla format or just regular HTTP-style header (Set-Cookie: ...) format. This will also enable the cookie engine. This adds that single cookie to the internal cookie store.
Exercise caution if you are using this option and multiple transfers may occur. If you use the Set-Cookie format and don't specify a domain then the cookie is sent for any domain (even after redirects are followed) and cannot be modified by a server-set cookie. If a server sets a cookie of the same name (or maybe you've imported one) then both will be sent on a future transfer to that server, likely not what you intended. address these issues set a domain in Set-Cookie or use the Netscape format.
Additionally, there are commands available that perform actions if you pass in these exact strings:
- "ALL" - erases all cookies held in memory
- "SESS" - erases all session cookies held in memory
- "FLUSH" - write all known cookies to the specified cookie jar
- "RELOAD" - reread all cookies from the cookie file
By default this options corresponds to CURLOPT_COOKIELIST
fn get(&mut self, enable: bool) -> Result<(), Error>
Ask for a HTTP GET request.
By default this option is false
and corresponds to CURLOPT_HTTPGET
.
fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error>
Ignore the content-length header.
By default this option is false
and corresponds to
CURLOPT_IGNORE_CONTENT_LENGTH
.
fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error>
Enable or disable HTTP content decoding.
By default this option is true
and corresponds to
CURLOPT_HTTP_CONTENT_DECODING
.
fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error>
Enable or disable HTTP transfer decoding.
By default this option is true
and corresponds to
CURLOPT_HTTP_TRANSFER_DECODING
.
fn range(&mut self, range: &str) -> Result<(), Error>
Indicates the range that this request should retrieve.
The string provided should be of the form N-M
where either N
or M
can be left out. For HTTP transfers multiple ranges separated by commas
are also accepted.
By default this option is not set and corresponds to CURLOPT_RANGE
.
fn resume_from(&mut self, from: u64) -> Result<(), Error>
Set a point to resume transfer from
Specify the offset in bytes you want the transfer to start from.
By default this option is 0 and corresponds to
CURLOPT_RESUME_FROM_LARGE
.
fn custom_request(&mut self, request: &str) -> Result<(), Error>
Set a custom request string
Specifies that a custom request will be made (e.g. a custom HTTP method). This does not change how libcurl performs internally, just changes the string sent to the server.
By default this option is not set and corresponds to
CURLOPT_CUSTOMREQUEST
.
fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error>
Get the modification time of the remote resource
If true, libcurl will attempt to get the modification time of the
remote document in this operation. This requires that the remote server
sends the time or replies to a time querying command. The filetime
function can be used after a transfer to extract the received time (if
any).
By default this option is false
and corresponds to CURLOPT_FILETIME
fn nobody(&mut self, enable: bool) -> Result<(), Error>
Indicate whether to download the request without getting the body
This is useful, for example, for doing a HEAD request.
By default this option is false
and corresponds to CURLOPT_NOBODY
.
fn in_filesize(&mut self, size: u64) -> Result<(), Error>
Set the size of the input file to send off.
By default this option is not set and corresponds to
CURLOPT_INFILESIZE_LARGE
.
fn upload(&mut self, enable: bool) -> Result<(), Error>
Enable or disable data upload.
This means that a PUT request will be made for HTTP and probably wants
to be combined with the read callback as well as the in_filesize
method.
By default this option is false
and corresponds to CURLOPT_UPLOAD
.
fn max_filesize(&mut self, size: u64) -> Result<(), Error>
Configure the maximum file size to download.
By default this option is not set and corresponds to
CURLOPT_MAXFILESIZE_LARGE
.
fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error>
Selects a condition for a time request.
This value indicates how the time_value
option is interpreted.
By default this option is not set and corresponds to
CURLOPT_TIMECONDITION
.
fn time_value(&mut self, val: i64) -> Result<(), Error>
Sets the time value for a conditional request.
The value here should be the number of seconds elapsed since January 1,
1970. To pass how to interpret this value, use time_condition
.
By default this option is not set and corresponds to
CURLOPT_TIMEVALUE
.
fn timeout(&mut self, timeout: Duration) -> Result<(), Error>
Set maximum time the request is allowed to take.
Normally, name lookups can take a considerable time and limiting operations to less than a few minutes risk aborting perfectly normal operations.
If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second.
In unix-like systems, this might cause signals to be used unless
nosignal
is set.
Since this puts a hard limit for how long time a request is allowed to
take, it has limited use in dynamic use cases with varying transfer
times. You are then advised to explore low_speed_limit
,
low_speed_time
or using progress_function
to implement your own
timeout logic.
By default this option is not set and corresponds to
CURLOPT_TIMEOUT_MS
.
fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error>
Set the low speed limit in bytes per second.
This specifies the average transfer speed in bytes per second that the
transfer should be below during low_speed_time
for libcurl to consider
it to be too slow and abort.
By default this option is not set and corresponds to
CURLOPT_LOW_SPEED_LIMIT
.
fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error>
Set the low speed time period.
Specifies the window of time for which if the transfer rate is below
low_speed_limit
the request will be aborted.
By default this option is not set and corresponds to
CURLOPT_LOW_SPEED_TIME
.
fn max_send_speed(&mut self, speed: u64) -> Result<(), Error>
Rate limit data upload speed
If an upload exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value.
By default this option is not set (unlimited speed) and corresponds to
CURLOPT_MAX_SEND_SPEED_LARGE
.
fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error>
Rate limit data download speed
If a download exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value.
By default this option is not set (unlimited speed) and corresponds to
CURLOPT_MAX_RECV_SPEED_LARGE
.
fn max_connects(&mut self, max: u32) -> Result<(), Error>
Set the maximum connection cache size.
The set amount will be the maximum number of simultaneously open persistent connections that libcurl may cache in the pool associated with this handle. The default is 5, and there isn't much point in changing this value unless you are perfectly aware of how this works and changes libcurl's behaviour. This concerns connections using any of the protocols that support persistent connections.
When reaching the maximum limit, curl closes the oldest one in the cache to prevent increasing the number of open connections.
By default this option is set to 5 and corresponds to
CURLOPT_MAXCONNECTS
fn fresh_connect(&mut self, enable: bool) -> Result<(), Error>
Force a new connection to be used.
Makes the next transfer use a new (fresh) connection by force instead of trying to re-use an existing one. This option should be used with caution and only if you understand what it does as it may seriously impact performance.
By default this option is false
and corresponds to
CURLOPT_FRESH_CONNECT
.
fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error>
Make connection get closed at once after use.
Makes libcurl explicitly close the connection when done with the transfer. Normally, libcurl keeps all connections alive when done with one transfer in case a succeeding one follows that can re-use them. This option should be used with caution and only if you understand what it does as it can seriously impact performance.
By default this option is false
and corresponds to
CURLOPT_FORBID_REUSE
.
fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error>
Timeout for the connect phase
This is the maximum time that you allow the connection phase to the server to take. This only limits the connection phase, it has no impact once it has connected.
By default this value is 300 seconds and corresponds to
CURLOPT_CONNECTTIMEOUT_MS
.
fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error>
Specify which IP protocol version to use
Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP.
By default this value is "any" and corresponds to CURLOPT_IPRESOLVE
.
fn connect_only(&mut self, enable: bool) -> Result<(), Error>
Configure whether to stop when connected to target server
When enabled it tells the library to perform all the required proxy authentication and connection setup, but no data transfer, and then return.
The option can be used to simply test a connection to a server.
By default this value is false
and corresponds to
CURLOPT_CONNECT_ONLY
.
fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error>
Sets the SSL client certificate.
The string should be the file name of your client certificate. The
default format is "P12" on Secure Transport and "PEM" on other engines,
and can be changed with ssl_cert_type
.
With NSS or Secure Transport, this can also be the nickname of the certificate you wish to authenticate with as it is named in the security database. If you want to use a file from the current directory, please precede it with "./" prefix, in order to avoid confusion with a nickname.
When using a client certificate, you most likely also need to provide a
private key with ssl_key
.
By default this option is not set and corresponds to CURLOPT_SSLCERT
.
fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error>
Specify type of the client SSL certificate.
The string should be the format of your certificate. Supported formats are "PEM" and "DER", except with Secure Transport. OpenSSL (versions 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 or later) also support "P12" for PKCS#12-encoded files.
By default this option is "PEM" and corresponds to
CURLOPT_SSLCERTTYPE
.
fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error>
Specify private keyfile for TLS and SSL client cert.
The string should be the file name of your private key. The default
format is "PEM" and can be changed with ssl_key_type
.
(iOS and Mac OS X only) This option is ignored if curl was built against Secure Transport. Secure Transport expects the private key to be already present in the keychain or PKCS#12 file containing the certificate.
By default this option is not set and corresponds to CURLOPT_SSLKEY
.
fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error>
Set type of the private key file.
The string should be the format of your private key. Supported formats are "PEM", "DER" and "ENG".
The format "ENG" enables you to load the private key from a crypto
engine. In this case ssl_key
is used as an identifier passed to
the engine. You have to set the crypto engine with ssl_engine
.
"DER" format key file currently does not work because of a bug in
OpenSSL.
By default this option is "PEM" and corresponds to
CURLOPT_SSLKEYTYPE
.
fn key_password(&mut self, password: &str) -> Result<(), Error>
Set passphrase to private key.
This will be used as the password required to use the ssl_key
.
You never needed a pass phrase to load a certificate but you need one to
load your private key.
By default this option is not set and corresponds to
CURLOPT_KEYPASSWD
.
fn ssl_engine(&mut self, engine: &str) -> Result<(), Error>
Set the SSL engine identifier.
This will be used as the identifier for the crypto engine you want to use for your private key.
By default this option is not set and corresponds to
CURLOPT_SSLENGINE
.
fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error>
Make this handle's SSL engine the default.
By default this option is not set and corresponds to
CURLOPT_SSLENGINE_DEFAULT
.
fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error>
Set preferred TLS/SSL version.
By default this option is not set and corresponds to
CURLOPT_SSLVERSION
.
fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error>
Verify the certificate's name against host.
This should be disabled with great caution! It basically disables the security features of SSL if it is disabled.
By default this option is set to true
and corresponds to
CURLOPT_SSL_VERIFYHOST
.
fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error>
Verify the peer's SSL certificate.
This should be disabled with great caution! It basically disables the security features of SSL if it is disabled.
By default this option is set to true
and corresponds to
CURLOPT_SSL_VERIFYPEER
.
fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>
Specify the path to Certificate Authority (CA) bundle
The file referenced should hold one or more certificates to verify the peer with.
This option is by default set to the system path where libcurl's cacert bundle is assumed to be stored, as established at build time.
If curl is built against the NSS SSL library, the NSS PEM PKCS#11 module (libnsspem.so) needs to be available for this option to work properly.
By default this option is the system defaults, and corresponds to
CURLOPT_CAINFO
.
fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>
Set the issuer SSL certificate filename
Specifies a file holding a CA certificate in PEM format. If the option is set, an additional check against the peer certificate is performed to verify the issuer is indeed the one associated with the certificate provided by the option. This additional check is useful in multi-level PKI where one needs to enforce that the peer certificate is from a specific branch of the tree.
This option makes sense only when used in combination with the
ssl_verify_peer
option. Otherwise, the result of the check is not
considered as failure.
By default this option is not set and corresponds to
CURLOPT_ISSUERCERT
.
fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>
Specify directory holding CA certificates
Names a directory holding multiple CA certificates to verify the peer
with. If libcurl is built against OpenSSL, the certificate directory
must be prepared using the openssl c_rehash utility. This makes sense
only when used in combination with the ssl_verify_peer
option.
By default this option is not set and corresponds to CURLOPT_CAPATH
.
fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error>
Specify a Certificate Revocation List file
Names a file with the concatenation of CRL (in PEM format) to use in the certificate validation that occurs during the SSL exchange.
When curl is built to use NSS or GnuTLS, there is no way to influence the use of CRL passed to help in the verification process. When libcurl is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all the elements of the certificate chain if a CRL file is passed.
This option makes sense only when used in combination with the
ssl_verify_peer
option.
A specific error code (is_ssl_crl_badfile
) is defined with the
option. It is returned when the SSL exchange fails because the CRL file
cannot be loaded. A failure in certificate verification due to a
revocation information found in the CRL does not trigger this specific
error.
By default this option is not set and corresponds to CURLOPT_CRLFILE
.
fn certinfo(&mut self, enable: bool) -> Result<(), Error>
Request SSL certificate information
Enable libcurl's certificate chain info gatherer. With this enabled, libcurl will extract lots of information and data about the certificates in the certificate chain used in the SSL connection.
By default this option is false
and corresponds to
CURLOPT_CERTINFO
.
fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>
Specify a source for random data
The file will be used to read from to seed the random engine for SSL and more.
By default this option is not set and corresponds to
CURLOPT_RANDOM_FILE
.
fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error>
Specify EGD socket path.
Indicates the path name to the Entropy Gathering Daemon socket. It will be used to seed the random engine for SSL.
By default this option is not set and corresponds to
CURLOPT_EGDSOCKET
.
fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error>
Specify ciphers to use for TLS.
Holds the list of ciphers to use for the SSL connection. The list must be syntactically correct, it consists of one or more cipher strings separated by colons. Commas or spaces are also acceptable separators but colons are normally used, !, - and + can be used as operators.
For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA', ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when you compile OpenSSL.
You'll find more details about cipher lists on this URL:
https://www.openssl.org/docs/apps/ciphers.html
For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5', ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one uses this option then all known ciphers are disabled and only those passed in are enabled.
You'll find more details about the NSS cipher lists on this URL:
http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives
By default this option is not set and corresponds to
CURLOPT_SSL_CIPHER_LIST
.
fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error>
Enable or disable use of the SSL session-ID cache
By default all transfers are done using the cache enabled. While nothing ever should get hurt by attempting to reuse SSL session-IDs, there seem to be or have been broken SSL implementations in the wild that may require you to disable this in order for you to succeed.
This corresponds to the CURLOPT_SSL_SESSIONID_CACHE
option.
fn effective_url(&mut self) -> Result<Option<&str>, Error>
Get the last used URL
In cases when you've asked libcurl to follow redirects, it may
not be the same value you set with url
.
This methods corresponds to the CURLINFO_EFFECTIVE_URL
option.
Returns Ok(None)
if no effective url is listed or Err
if an error
happens or the underlying bytes aren't valid utf-8.
fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>
Get the last used URL, in bytes
In cases when you've asked libcurl to follow redirects, it may
not be the same value you set with url
.
This methods corresponds to the CURLINFO_EFFECTIVE_URL
option.
Returns Ok(None)
if no effective url is listed or Err
if an error
happens or the underlying bytes aren't valid utf-8.
fn response_code(&mut self) -> Result<u32, Error>
Get the last response code
The stored value will be zero if no server response code has been
received. Note that a proxy's CONNECT response should be read with
http_connectcode
and not this.
Corresponds to CURLINFO_RESPONSE_CODE
and returns an error if this
option is not supported.
fn http_connectcode(&mut self) -> Result<u32, Error>
Get the CONNECT response code
Returns the last received HTTP proxy response code to a CONNECT request. The returned value will be zero if no such response code was available.
Corresponds to CURLINFO_HTTP_CONNECTCODE
and returns an error if this
option is not supported.
fn filetime(&mut self) -> Result<Option<i64>, Error>
Get the remote time of the retrieved document
Returns the remote time of the retrieved document (in number of seconds
since 1 Jan 1970 in the GMT/UTC time zone). If you get None
, it can be
because of many reasons (it might be unknown, the server might hide it
or the server doesn't support the command that tells document time etc)
and the time of the document is unknown.
Note that you must tell the server to collect this information before
the transfer is made, by using the filetime
method to
or you will unconditionally get a None
back.
This corresponds to CURLINFO_FILETIME
and may return an error if the
option is not supported
fn redirect_count(&mut self) -> Result<u32, Error>
Get the number of redirects
Corresponds to CURLINFO_REDIRECT_COUNT
and may return an error if the
option isn't supported.
fn redirect_url(&mut self) -> Result<Option<&str>, Error>
Get the URL a redirect would go to
Returns the URL a redirect would take you to if you would enable
follow_location
. This can come very handy if you think using the
built-in libcurl redirect logic isn't good enough for you but you would
still prefer to avoid implementing all the magic of figuring out the new
URL.
Corresponds to CURLINFO_REDIRECT_URL
and may return an error if the
url isn't valid utf-8 or an error happens.
fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error>
Get the URL a redirect would go to, in bytes
Returns the URL a redirect would take you to if you would enable
follow_location
. This can come very handy if you think using the
built-in libcurl redirect logic isn't good enough for you but you would
still prefer to avoid implementing all the magic of figuring out the new
URL.
Corresponds to CURLINFO_REDIRECT_URL
and may return an error.
fn header_size(&mut self) -> Result<u64, Error>
Get size of retrieved headers
Corresponds to CURLINFO_HEADER_SIZE
and may return an error if the
option isn't supported.
fn request_size(&mut self) -> Result<u64, Error>
Get size of sent request.
Corresponds to CURLINFO_REQUEST_SIZE
and may return an error if the
option isn't supported.
fn content_type(&mut self) -> Result<Option<&str>, Error>
Get Content-Type
Returns the content-type of the downloaded object. This is the value
read from the Content-Type: field. If you get None
, it means that the
server didn't send a valid Content-Type header or that the protocol
used doesn't support this.
Corresponds to CURLINFO_CONTENT_TYPE
and may return an error if the
option isn't supported.
fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error>
Get Content-Type, in bytes
Returns the content-type of the downloaded object. This is the value
read from the Content-Type: field. If you get None
, it means that the
server didn't send a valid Content-Type header or that the protocol
used doesn't support this.
Corresponds to CURLINFO_CONTENT_TYPE
and may return an error if the
option isn't supported.
fn os_errno(&mut self) -> Result<i32, Error>
Get errno number from last connect failure.
Note that the value is only set on failure, it is not reset upon a successful operation. The number is OS and system specific.
Corresponds to CURLINFO_OS_ERRNO
and may return an error if the
option isn't supported.
fn primary_ip(&mut self) -> Result<Option<&str>, Error>
Get IP address of last connection.
Returns a string holding the IP address of the most recent connection done with this curl handle. This string may be IPv6 when that is enabled.
Corresponds to CURLINFO_PRIMARY_IP
and may return an error if the
option isn't supported.
fn primary_port(&mut self) -> Result<u16, Error>
Get the latest destination port number
Corresponds to CURLINFO_PRIMARY_PORT
and may return an error if the
option isn't supported.
fn local_ip(&mut self) -> Result<Option<&str>, Error>
Get local IP address of last connection
Returns a string holding the IP address of the local end of most recent connection done with this curl handle. This string may be IPv6 when that is enabled.
Corresponds to CURLINFO_LOCAL_IP
and may return an error if the
option isn't supported.
fn local_port(&mut self) -> Result<u16, Error>
Get the latest local port number
Corresponds to CURLINFO_LOCAL_PORT
and may return an error if the
option isn't supported.
fn cookies(&mut self) -> Result<List, Error>
Get all known cookies
Returns a linked-list of all cookies cURL knows (expired ones, too).
Corresponds to the CURLINFO_COOKIELIST
option and may return an error
if the option isn't supported.
fn perform(&self) -> Result<(), Error>
After options have been set, this will perform the transfer described by the options.
This performs the request in a synchronous fashion. This can be used multiple times for one easy handle and libcurl will attempt to re-use the same connection for all transfers.
This method will preserve all options configured in this handle for the
next request, and if that is not desired then the options can be
manually reset or the reset
method can be called.
Note that this method takes &self
, which is quite important! This
allows applications to close over the handle in various callbacks to
call methods like unpause_write
and unpause_read
while a transfer is
in progress.
fn transfer<'data, 'easy>(&'easy mut self) -> Transfer<'easy, 'data>
Creates a new scoped transfer which can be used to set callbacks and data which only live for the scope of the returned object.
An Easy
handle is often reused between different requests to cache
connections to servers, but often the lifetime of the data as part of
each transfer is unique. This function serves as an ability to share an
Easy
across many transfers while ergonomically using possibly
stack-local data as part of each transfer.
Configuration can be set on the Easy
and then a Transfer
can be
created to set scoped configuration (like callbacks). Finally, the
perform
method on the Transfer
function can be used.
When the Transfer
option is dropped then all configuration set on the
transfer itself will be reset.
fn unpause_read(&self) -> Result<(), Error>
Unpause reading on a connection.
Using this function, you can explicitly unpause a connection that was previously paused.
A connection can be paused by letting the read or the write callbacks
return ReadError::Pause
or WriteError::Pause
.
To unpause, you may for example call this from the progress callback which gets called at least once per second, even if the connection is paused.
The chance is high that you will get your write callback called before this function returns.
fn unpause_write(&self) -> Result<(), Error>
Unpause writing on a connection.
Using this function, you can explicitly unpause a connection that was previously paused.
A connection can be paused by letting the read or the write callbacks
return ReadError::Pause
or WriteError::Pause
. A write callback that
returns pause signals to the library that it couldn't take care of any
data at all, and that data will then be delivered again to the callback
when the writing is later unpaused.
To unpause, you may for example call this from the progress callback which gets called at least once per second, even if the connection is paused.
fn url_encode(&mut self, s: &[u8]) -> String
URL encodes a string s
fn url_decode(&mut self, s: &str) -> Vec<u8>
URL decodes a string s
, returning None
if it fails
fn reset(&mut self)
Re-initializes this handle to the default values.
This puts the handle to the same state as it was in when it was just created. This does, however, keep live connections, the session id cache, the dns cache, and cookies.
fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error>
Receives data from a connected socket.
Only useful after a successful perform
with the connect_only
option
set as well.
fn send(&mut self, data: &[u8]) -> Result<usize, Error>
Sends data over the connected socket.
Only useful after a successful perform
with the connect_only
option
set as well.
fn raw(&self) -> *mut CURL
Get a pointer to the raw underlying CURL handle.