libcurl Programming Tutorial


This tutorial attempts to describe the general principles and some basic approaches to consider when programming with libcurl. The text will focus mainly on the C interface but may apply to other interfaces as well as they usually follow the C interface closely.

This tutorial will refer to 'the user' as the person writing the source code that uses libcurl. That would probably be you or someone in your position. What will be generally referred to as 'the program' will be the collected source code that you write that is using libcurl for transfers. The program is outside libcurl and libcurl is outside of the program.

To get more information on all options and functions described, refer to their respective MAN pages.

Global Preparation

The program must initialize some of the libcurl functionality globally. That means it should be done exactly once, no matter how many times you intend to use the library. Once for your program's entire lifetime. This is performed by using:


and it takes one parameter which is a bit pattern that instructs libcurl what to initialize. Using CURL_GLOBAL_ALL will make it initialize all known internal sub modules, and might be a good default option.

libcurl has a default protection mechanism that detects if curl_global_init has not been called by the time curl_easy_perform is called and if that is the case, libcurl runs the function itself with a guessed bit pattern. Note that depending solely on this is not considered ideal.

When the program no longer uses libcurl, it should call curl_global_cleanup, which is the opposite of the init call. It will then do the reversed operations to cleanup the resources the curl_global_init call initialized.

Repeated calls to curl_global_init and curl_global_cleanup should be avoided. They should only be called once each.

Features libcurl Provides

It is considered best-practice to determine libcurl features at runtime rather than at build-time (if possible). By calling curl_version_info and checking out the details of the returned struct, your program can figure out exactly what the currently running libcurl supports.

Handle the Easy libcurl

libcurl first introduced the so called easy interface. All operations in the easy interface are prefixed with curl_easy.

Recent libcurl versions also offer the multi interface. More about that interface, what it is targeted for and how to use it is detailed in a separate chapter further down. You still need to understand the easy interface first, so please continue reading for better understanding.

To use the easy interface, first create yourself an easy handle. You need one handle for each easy session you want to perform. You should use one handle for every thread you plan to use for transferring. Do not share the same handle in multiple threads.

Get an easy handle with

easyhandle = curl_easy_init;

It returns an easy handle. Using that you proceed to the next step: setting up your preferred actions. A handle is just a logic entity for the upcoming transfer or series of transfers.

You set properties and options for this handle using curl_easy_setopt. They control how the subsequent transfer or transfers will be made. Options remain set in the handle until set again to something different. Multiple requests using the same handle will use the same options.

Many of the options you set in libcurl are "strings", pointers to data terminated with a zero byte. When you set strings with curl_easy_setopt, libcurl makes its own copy so that they do not need to be kept around in your application after being set.

One of the most basic properties to set in the handle is the URL. You set your preferred URL to transfer with CURLOPT_URL in a manner similar to:

curl_easy_setopt(handle, CURLOPT_URL, "");

Assume that you want to receive data as the URL identifies a remote resource you want to get here. Since you write a sort of application that needs this transfer, I assume that you would like to get the data passed to you directly instead of getting it passed to stdout. So, you write your own function that matches this prototype:

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);

You instruct libcurl to pass all data to this function by issuing a function similar to this:

curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);

You can control what data your callback function gets in the fourth argument by setting another property:

curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &internal_struct);

Using that property, you can pass local data between your application and the function that gets invoked by libcurl. libcurl itself will not touch the data you pass with CURLOPT_WRITEDATA.

There are many more options you can set, and a few of them will be discussed later. Instead, continue to the actual transfer:

success = curl_easy_perform(easyhandle);

curl_easy_perform will connect to the remote site, do the necessary commands and receive the transfer. Whenever it receives data, it calls the callback function we previously set. The function may get one byte at a time, or it may get many kilobytes at the same time. libcurl delivers as much as possible as often as possible. Your callback function should return the number of bytes it "took care of". If that is not the exact same amount of bytes that was passed to it, libcurl will abort the operation and return with an error code.

When the transfer is complete, the function returns a return code that informs you if it succeeded in its mission or not. If a return code is not enough for you, you can use the CURLOPT_ERRORBUFFER to point libcurl to a buffer of yours where it will store a human readable error message as well.

If you then want to transfer another file, the handle is ready to be used again. It is even preferred that you reuse an existing handle if you intend to make another transfer. libcurl will then attempt to reuse the previous connection.

For some protocols, downloading a file can involve a complicated process of logging in, setting the transfer mode, changing the current directory and finally transferring the file data. libcurl takes care of all that complication for you. Given the URL to a file, libcurl will take care of all the details needed to get the file moved from one machine to another.

Multithreading Issues

The first basic rule is to never share a libcurl handle (be it easy or multi or whatever) between multiple threads. Only use one handle in one thread at a time.

Also, note that CURLOPT_DNS_USE_GLOBAL_CACHE is not thread-safe.

When It Does Not Work

There will always be times when the transfer fails for some reason. You might have set an incorrect libcurl option or misunderstood what the libcurl option actually does, or the remote server might return non-standard replies that confuse the library which then confuses your program.

There is an important rule when such things occur: set the CURLOPT_VERBOSE option to 1. It will cause the library to send out the entire protocol details it sends, some internal info and some received protocol data as well. If using HTTP, adding the headers in the received output to study is also a useful way to get a better understanding why the server behaves the way it does. Include headers in the normal body output with CURLOPT_HEADER set to 1.

If CURLOPT_VERBOSE is not enough, you increase the level of debug data your application receive by using the CURLOPT_DEBUGFUNCTION.

Getting in-depth knowledge about the protocols involved is useful, and depending on what you are attempting to perform, you might well understand libcurl and how to use it better if you study the appropriate RFC documents at least briefly.

Upload Data to a Remote Site

First either create an easy handle or reuse an existing one. Then you set the URL to operate on just like before. This is the remote URL, that we now will upload.

Since we write an application, we most likely want libcurl to get the upload data by asking us for it. To make it do that, we set the read callback and the custom pointer libcurl will pass to our read callback. The read callback should have a prototype similar to:

size_t function(char *bufptr, size_t size, size_t nitems, void *userp);

Where bufptr is the pointer to a buffer we fill in with data to upload and size*nitems is the size of the buffer and also the maximum amount of data we can return to libcurl in this call. The 'userp' pointer is the custom pointer we set to point to a struct of ours to pass private data between the application and the callback.

curl_easy_setopt(easyhandle, CURLOPT_READFUNCTION, read_function);

curl_easy_setopt(easyhandle, CURLOPT_READDATA, &filedata);

Instruct libcurl that we want to upload:

curl_easy_setopt(easyhandle, CURLOPT_UPLOAD, 1L);

A few protocols will not behave properly when uploads are done without any prior knowledge of the expected file size. So, set the upload file size using the CURLOPT_INFILESIZE_LARGE for all known file sizes like this:

/* in this example, file_size must be an curl_off_t variable */ curl_easy_setopt(easyhandle, CURLOPT_INFILESIZE_LARGE, file_size);

When you call curl_easy_perform this time, it will perform all the necessary operations and when it has invoked the upload it will call your supplied callback to get the data to upload. The program should return as much data as possible in every invoke, as that is likely to make the upload perform as fast as possible. The callback should return the number of bytes it wrote in the buffer. Returning 0 will signal the end of the upload.


Many protocols use or even require that user name and password are provided to be able to download or upload the data of your choice. libcurl offers several ways to specify them.

Most protocols support that you specify the name and password in the URL itself. libcurl will detect this and use them accordingly. This is written like this:


If you need any odd letters in your user name or password, you should enter them URL encoded, as %nn, where nn is a two-digit hexadecimal number. libcurl also provides options to set various passwords. The user name and password as shown embedded in the URL can instead get set with the CURLOPT_USERPWD option. The argument passed to libcurl should be a char * to a string in the format "user:password". In a manner like this:

curl_easy_setopt(easyhandle, CURLOPT_USERPWD, "myname:thesecret");

Another case where name and password might be needed at times, is for those users who need to authenticate themselves to a proxy they use. libcurl offers another option for this, the CURLOPT_PROXYUSERPWD. It is used quite similar to the CURLOPT_USERPWD option like this:

curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "myname:thesecret");

HTTP Authentication

The previous chapter showed how to set user name and password for getting URLs that require authentication. When using the HTTP protocol, there are many different ways a client can provide those credentials to the server and you can control which way libcurl will (attempt to) use them. The default HTTP authentication method is called 'Basic', which is sending the name and password in clear-text in the HTTP request, base64-encoded. This is insecure.

At the time of this writing, libcurl can be built to use: Basic, Digest, NTLM, Negotiate, GSS-Negotiate and SPNEGO. You can instruct libcurl which one to use with CURLOPT_HTTPAUTH as in:

curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);

And when you send authentication to a proxy, you can also set authentication type the same way but instead with CURLOPT_PROXYAUTH:

curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);

Both these options allow you to set multiple types (by ORing them together), to make libcurl pick the most secure one out of the types the server/proxy claims to support. However, this method does add a round-trip since libcurl must first ask the server what it supports:


For convenience, you can use the CURLAUTH_ANY define (instead of a list with specific types) which allows libcurl to use whatever method it wants.

When asking for multiple types, libcurl will pick the available one it considers "best" in its own internal order of preference.


We get many questions regarding how to issue HTTP POSTs with libcurl the proper way. This chapter will include examples using both different versions of HTTP POST that libcurl supports.

The first version is the simple POST, the most common version, that most HTML pages using the <form> tag uses. We provide a pointer to the data and instruct libcurl to post it all to the remote site:

char *data="name=daniel&project=curl"; curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, data); curl_easy_setopt(easyhandle, CURLOPT_URL, "");

curl_easy_perform(easyhandle); /* post away! */

Set the POST options with the CURLOPT_POSTFIELDS, this automatically switches the handle to use POST in the upcoming request.

If you need to post binary data that also requires you to set the Content-Type: header of the post? Binary posts prevent libcurl from being able to perform strlen on the data to figure out the size, so therefore we must instruct libcurl the size of the post data. Setting headers in libcurl requests are done in a generic way, by building a list of our own headers and then passing that list to libcurl.

struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: text/xml");

/* post binary data */ curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, binaryptr);

/* set the size of the postfields data */ curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDSIZE, 23L);

/* pass our list of custom made headers */ curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);

curl_easy_perform(easyhandle); /* post away! */

curl_slist_free_all(headers); /* free the header list */

While the examples above cover most cases where HTTP POST operations are required, they do not do multi-part formposts. Multi-part formposts were introduced as a better way to post (possibly large) binary data and were first documented in the RFC 1867 (updated in RFC2388). They are called multi-part because they are built by a chain of parts, each part being a single unit of data. Each part has its own name and contents. You can in fact create and post a multi-part formpost with the regular libcurl POST support described above, but that would require that you build a formpost yourself and provide to libcurl. To make that easier, libcurl provides curl_formadd. Using this function, you add parts to the form. When done adding parts, you post the whole form.

The following example sets two text parts with plain textual contents, and then a file with binary contents and uploads the whole thing.

struct curl_httppost *post=NULL; struct curl_httppost *last=NULL; curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END); curl_formadd(&post, &last, CURLFORM_COPYNAME, "project", CURLFORM_COPYCONTENTS, "curl", CURLFORM_END); curl_formadd(&post, &last, CURLFORM_COPYNAME, "logotype-image", CURLFORM_FILECONTENT, "curl.png", CURLFORM_END);

/* Set the form info */ curl_easy_setopt(easyhandle, CURLOPT_HTTPPOST, post);

curl_easy_perform(easyhandle); /* post away! */

/* free the post data again */ curl_formfree(post);

Multipart formposts are chains of parts using MIME-style separators and headers. It means that each one of these separate parts get a few headers set that describe the individual content-type, size etc. To enable your application to handicraft this formpost even more, libcurl allows you to supply your own set of custom headers to such an individual form part. You can supply headers to as many parts as you like, but this little example will show how you set headers to one specific part when you add that to the post handle:

struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: text/xml");

curl_formadd(&post, &last, CURLFORM_COPYNAME, "logotype-image", CURLFORM_FILECONTENT, "curl.xml", CURLFORM_CONTENTHEADER, headers, CURLFORM_END);

curl_easy_perform(easyhandle); /* post away! */

curl_formfree(post); /* free post */ curl_slist_free_all(headers); /* free custom header list */

Since all options on an easyhandle are "sticky", they remain the same until changed even if you do call curl_easy_perform, you may need to instruct curl to go back to a plain GET request if you intend to do one as your next request. You force an easyhandle to go back to GET by using the CURLOPT_HTTPGET option:

curl_easy_setopt(easyhandle, CURLOPT_HTTPGET, 1L);

Setting CURLOPT_POSTFIELDS to "" or NULL will not stop libcurl from performing a POST. It will make it POST without any data to send.

Showing Progress

For historical and traditional reasons, libcurl has a built-in progress meter that can be switched on and then makes it present a progress meter in your terminal.

Switch on the progress meter by, oddly enough, setting CURLOPT_NOPROGRESS to zero. This option is set to 1 by default.

For most applications however, the built-in progress meter is inadequate and what instead is interesting is the ability to specify a progress callback. The function pointer you pass to libcurl will then be called on irregular intervals with information about the current transfer.

Set the progress callback by using CURLOPT_PROGRESSFUNCTION. And pass a pointer to a function that matches this prototype:

int progress_callback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow);

If any of the input arguments is unknown, a 0 will be passed. The first argument, the 'clientp' is the pointer you pass to libcurl with CURLOPT_PROGRESSDATA. libcurl will not touch it.

libcurl with C++

Understand that when using C++, instead of C, when interfacing libcurl:

The callbacks CANNOT be non-static class member functions.

Example C++ code:

class AClass { static size_t write_data(void *ptr, size_t size, size_t nmemb, void *ourpointer) { /* do what you want with the data */ } }


What "proxy" means according to Merriam-Webster: "a person authorized to act for another" but also "the agency, function, or office of a deputy who acts as a substitute for another".

Proxies are exceedingly common these days. Companies often only offer Internet access to employees through their proxies. Network clients or user-agents ask the proxy for documents, the proxy performs the actual requests and then returns them.

libcurl supports SOCKS and HTTP proxies. When a given URL is wanted, libcurl will ask the proxy for it instead of trying to connect to the actual host identified in the URL.

If using a SOCKS proxy, you may find that libcurl does not quite support all operations through it.

For HTTP proxies: the fact that the proxy is a HTTP proxy puts certain restrictions on what can actually happen. A requested URL that might not be a HTTP URL will be still be passed to the HTTP proxy to deliver back to libcurl. This happens transparently, and an application may not need to know. I say "may", because at times it is important to understand that all operations over a HTTP proxy use the HTTP protocol.

Default Proxy Settings

Cafe libcurl automatically applies system proxy settings. For information, see Proxy Settings.

Proxy Options

To instruct libcurl to use a proxy at a given port number:

curl_easy_setopt(easyhandle, CURLOPT_PROXY, "");

Some proxies require user authentication before allowing a request, and you pass that information similar to this:

curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "user:password");

If you want to, you can specify the hostname only in the CURLOPT_PROXY option, and set the port number separately with CURLOPT_PROXYPORT.

Instruct libcurl what type of proxy it is with CURLOPT_PROXYTYPE (if not, it will default to assume a HTTP proxy):

curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);

SSL and Proxies

SSL is for secure point-to-point connections. This involves strong encryption and similar things, which effectively makes it impossible for a proxy to operate as a "man in between" which the proxy's task is, as previously discussed. Instead, the only way to have SSL work over a HTTP proxy is to ask the proxy to tunnel trough everything without being able to check or fiddle with the traffic.

Opening an SSL connection over a HTTP proxy is therefore a matter of asking the proxy for a straight connection to the target host on a specified port. This is made with the HTTP request CONNECT. ("please mr proxy, connect me to that remote host").

Because of the nature of this operation, where the proxy has no indication on what type of data is passed in and out through this tunnel, this breaks some of the few advantages that come from using a proxy, such as caching. Many organizations prevent this type of tunneling to other destination port numbers than 443 (which is the default HTTPS port number).

Tunneling Through Proxy

As explained above, tunneling is required for SSL to work and often even restricted to the operation intended for SSL; HTTPS.

However, this is not the only time proxy-tunneling might offer benefits to you or your application.

As tunneling opens a direct connection from your application to the remote machine, it suddenly also reintroduces the ability to do non-HTTP operations over a HTTP proxy.

Again, this is often prevented by the administrators of proxies and is rarely allowed.

Instruct libcurl to use proxy tunneling like this:

curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);

In fact, there might even be times when you want to do plain HTTP operations using a tunnel like this, as it then enables you to operate on the remote server instead of asking the proxy to do so. libcurl will not stand in the way for such innovative actions either!

Persistence Is The Way to Happiness

Recycling the same easy handle several times when performing multiple requests is the way to go.

After each single curl_easy_perform operation, libcurl will keep the connection alive and open. A subsequent request using the same easy handle to the same host might just be able to use the already open connection! This reduces network affect a lot.

Even if the connection is dropped, all connections involving SSL to the same host again, will benefit from libcurl's session ID cache that drastically reduces reconnect time.

libcurl caches DNS name resolving results, to make lookups of a previously looked up name a lot faster.

Other interesting details that improve performance for subsequent requests may also be added in the future.

Each easy handle will attempt to keep the last few connections alive for a while in case they are to be used again. You can set the size of this "cache" with the CURLOPT_MAXCONNECTS option. Default is 5. There is seldom any reason to change this value.

To force your upcoming request to not use an already existing connection (it will even close one first if there happens to be one alive to the same host about to be operated on), set CURLOPT_FRESH_CONNECT to 1. Similarly, you can also forbid the upcoming request to be "lying" around and possibly get reused after the request by setting CURLOPT_FORBID_REUSE to 1.

HTTP Headers Used by libcurl

When you use libcurl to do HTTP requests, it will pass along a series of headers automatically. It might be good for you to know and understand these. You can replace or remove them by using the CURLOPT_HTTPHEADER option.


This header is required by HTTP 1.1 and even many 1.0 servers and should be the name of the server we want to communicate with. This includes the port number if anything but default.


"no-cache". Instructs a possible proxy to not grab a copy from the cache but to fetch a fresh one.




When performing POST requests, libcurl sets this header to "100-continue" to ask the server for an "OK" message before it proceeds with sending the data part of the post. If the POSTed data amount is deemed "small", libcurl will not use this header.

Customizing Operations

There is an ongoing development today where more and more protocols are built upon HTTP for transport. This has obvious benefits as HTTP is a tested and reliable protocol that is widely deployed and has excellent proxy-support.

When you use one of these protocols, and even when performing other types of programming you may need to change the traditional HTTP manners. You may need to change words, headers or various data.

libcurl is your friend here too.


If just changing the actual HTTP request keyword is what you want, like when GET, HEAD or POST is not adequate, CURLOPT_CUSTOMREQUEST is available. Use as shown here:

curl_easy_setopt(easyhandle, CURLOPT_CUSTOMREQUEST, "MYOWNREQUEST");

When using the custom request, you change the request keyword of the actual request you are performing. By default you make a GET request but you can also make a POST operation (as described before) and then replace the POST keyword if you want to.

Modify Headers

HTTP-like protocols pass a series of headers to the server when performing the request, and you are free to pass any appropriate amount of extra headers. Adding headers is this easy:

struct curl_slist *headers=NULL; /* init to NULL is important */

headers = curl_slist_append(headers, "Hey-server-hey: how are you?"); headers = curl_slist_append(headers, "X-silly-content: yes");

/* pass our list of custom made headers */ curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);

curl_easy_perform(easyhandle); /* transfer http */

curl_slist_free_all(headers); /* free the header list *

... and if some of the internally generated headers, such as Accept: or Host: do not contain the data you want them to contain, you can replace them by setting them too:

headers = curl_slist_append(headers, "Accept: Agent-007"); headers = curl_slist_append(headers, "Host:");

Delete Headers

If you replace an existing header with one with no contents, you will prevent the header from being sent. For instance, if you want to completely prevent the "Accept:" header from being sent, you can disable it with code similar to this:

headers = curl_slist_append(headers, "Accept:");

Both replacing and canceling internal headers should be done with careful consideration and you should note that you may violate the HTTP protocol when doing so.

Enforcing chunked transfer-encoding

By making sure a request uses the custom header "Transfer-Encoding: chunked" when performing a non-GET HTTP operation, libcurl will switch over to "chunked" upload, even though the size of the data to upload might be known. By default, libcurl usually switches over to chunked upload automatically if the upload data size is unknown.

HTTP Version

All HTTP requests includes the version number to instruct the server which version we support. libcurl speaks HTTP 1.1 by default. Some older servers do not readily accept 1.1-requests and so when dealing with such situations, you can instruct libcurl to use 1.0 instead by performing something similar to the following:

curl_easy_setopt(easyhandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

Cookies Without Chocolate Chips

In the HTTP sense, a cookie is a name with an associated value. A server sends the name and value to the client, and expects it to get sent back on every subsequent request to the server that matches the particular conditions set. The conditions include that the domain name and path match and that the cookie has not become too old.

In real-world cases, servers send new cookies to replace existing ones to update them. Server use cookies to "track" users and to keep "sessions".

Cookies are sent from server to clients with the header Set-Cookie: and they are sent from clients to servers with the Cookie: header.

To just send whatever cookie you want to a server, you can use CURLOPT_COOKIE to set a cookie string like this:

curl_easy_setopt(easyhandle, CURLOPT_COOKIE, "name1=var1; name2=var2;");

In many cases, that is not enough. You might want to dynamically save whatever cookies the remote server passes to you, and make sure those cookies are then used accordingly on later requests.

Headers Equal Fun

In the HTTP sense, a cookie is a name with an associated value. A server sends the name and value to the client, and expects it to get sent back on every subsequent request to the server that matches the particular conditions set. The conditions include that the domain name and path match and that the cookie has not become too old.

In real-world cases, servers send new cookies to replace existing ones to update them. Server use cookies to "track" users and to keep "sessions".

Cookies are sent from server to clients with the header Set-Cookie: and they are sent from clients to servers with the Cookie: header.

To just send whatever cookie you want to a server, you can use CURLOPT_COOKIE to set a cookie string like this:

curl_easy_setopt(easyhandle, CURLOPT_COOKIE, "name1=var1; name2=var2;");

In many cases, that is not enough. You might want to dynamically save whatever cookies the remote server passes to you, and make sure those cookies are then used accordingly on later requests.

Post Transfer Information

For information, see curl_easy_getinfo.

Security Considerations

The libcurl project takes security seriously. The library is written with caution and precautions are taken to mitigate many risks encountered while operating with potentially malicious servers on the Internet. It is a powerful library, however, which allows application writers to make trade offs between ease of writing and exposure to potential risky operations. If used correctly, you can use libcurl to transfer data fairly safely.

Many applications are used in closed networks where users and servers can be trusted, but many others are used on arbitrary servers and are fed input from potentially untrusted users. Following is a discussion about some risks in the ways in which applications commonly use libcurl and potential mitigations of those risks. It is by no means comprehensive, but shows classes of attacks that robust applications should consider. The Common Weakness Enumeration project ( is a good reference for many of these and similar types of weaknesses of which application writers should consider.

Clear Text Passwords

Many of the protocols libcurl supports send name and password unencrypted as clear text (HTTP Basic authentication). It is easy for anyone on your network or a network nearby yours to just fire up a network analyzer tool and eavesdrop on your passwords. Do not let the fact that HTTP Basic uses base64 encoded passwords fool you. They may not look readable at a first glance, but they can be "deciphered" within seconds.

To avoid this problem, use HTTP authentication methods or other protocols that do not let snoopers see your password: HTTP with Digest, NTLM, HTTPS are a few examples.

Private Resources

A user who can control the DNS server of a domain being passed in within a URL can change the address of the host to a local, private address which the libcurl application will then use. e.g. The innocuous URL could actually resolve to the IP address of a server behind a firewall, such as or Apps can mitigate against this by setting a CURLOPT_OPENSOCKETFUNCTION and checking the address before a connection.

All the malicious scenarios regarding redirected URLs apply just as well to non-redirected URLs, if the user is allowed to specify an arbitrary URL that could point to a private resource.


Use of CURLOPT_UNRESTRICTED_AUTH could cause authentication information to be sent to an unknown second server. Apps can mitigate against this by disabling CURLOPT_FOLLOWLOCATION and handling redirects itself, sanitizing where necessary.

Use of the CURLAUTH_ANY option to CURLOPT_HTTPAUTH could result in user name and password being sent in clear text to an HTTP server. Instead, use CURLAUTH_ANYSAFE which ensures that the password is encrypted over the network, or else fail the request.


If cookies are enabled and cached, then a user could craft a URL which performs some malicious action to a site whose authentication is already stored in a cookie. e.g. Apps can mitigate against this by disabling cookies or clearing them between requests.

Denial of Service

A malicious server could cause libcurl to effectively hang by sending a trickle of data through, or even no data but keeping the TCP connection open. This could result in a denial-of-service attack. The CURLOPT_TIMEOUT and/or CURLOPT_LOW_SPEED_LIMIT options can be used to mitigate against this.

A malicious server could cause libcurl to effectively hang by starting to send data, then severing the connection without cleanly closing the TCP connection. The app could install a CURLOPT_SOCKOPTFUNCTION callback function and set the TCP SO_KEEPALIVE option to mitigate against this. Setting one of the timeout options would also work against this attack.

A malicious server could cause libcurl to download an infinite amount of data, potentially causing all of memory or disk to be filled. Setting the CURLOPT_MAXFILESIZE_LARGE option is not sufficient to guard against this. Instead, the app should monitor the amount of data received within the write or progress callback and abort when the limit is reached.

A malicious HTTP server could cause an infinite redirection loop, causing a denial-of-service. This can be mitigated by using the CURLOPT_MAXREDIRS option.

Arbitrary Headers

User-supplied data must be sanitized when used in options like CURLOPT_USERAGENT, CURLOPT_HTTPHEADER, CURLOPT_POSTFIELDS and others that are used to generate structured data. Characters like embedded carriage returns or ampersands could allow the user to create additional headers or fields that could cause malicious transactions.

Server-supplied Names

A server can supply data which the application may, in some cases, use as a file name. The curl command-line tool does this with --remote-header-name, using the Content-disposition: header to generate a file name. An application could also use CURLINFO_EFFECTIVE_URL to generate a file name from a server-supplied redirect URL. Special care must be taken to sanitize such names to avoid the possibility of a malicious server supplying one like "/etc/passwd", "autoexec.bat" or even ".bashrc".

Server Certificates

A secure application should never use the CURLOPT_SSL_VERIFYPEER option to disable certificate validation. There are numerous attacks that are enabled by apps that fail to properly validate server TLS/SSL certificates, enabling a malicious server to spoof a legitimate one. HTTPS without validated certificates is potentially as insecure as a plain HTTP connection.

Showing What You Do

On a related issue, even in situations like when you have problems with libcurl and ask someone for help, everything you reveal to get the best possible help might also impose certain security related risks. Hostnames, user names, paths, operating system specifics, etc (and passwords ) may in fact be used by intruders to gain additional information of a potential target.

To avoid this problem, you can edit out the sensitive data or just search/replace your true information with faked data.

Multiple Transfers Using the multi Interface

The easy interface as described in detail in this tutorial is a synchronous interface that transfers one file at a time and does not return until it is done.

Conversely, the multi interface allows your program to transfer multiple files in both directions at the same time, without forcing you to use multiple threads. The name might make it seem that the multi interface is for multithreaded programs, but the reality is almost the reverse. The multi interface can allow a single-threaded application to perform the same types of multiple, simultaneous transfers that multithreaded programs can perform. It allows many of the benefits of multithreaded transfers without the complexity of managing and synchronizing many threads.

To use this interface, it is advantageous if you first understand the basics of how to use the easy interface. The multi interface is a way to make multiple transfers at the same time by adding up multiple easy handles into a "multi stack".

You create the easy handles you want and you set all the options just like you have been told above, and then you create a multi handle with curl_multi_init and add all those easy handles to that multi handle with curl_multi_add_handle.

When you have added the handles you have for the moment (you can still add new ones at any time), you start the transfers by calling curl_multi_perform.

curl_multi_perform is asynchronous. It will only execute as little as possible and then return back control to your program. It is designed to never block. If it returns CURLM_CALL_MULTI_PERFORM you better call it again soon, as that is a signal that it still has local data to send or remote data to receive.

The best usage of this interface is when you do a select on all possible file descriptors or sockets to know when to call libcurl again. This also makes it easy for you to wait and respond to actions on your own application's sockets/handles. You determine what to select for by using curl_multi_fdset, that fills in a set of fd_set variables for you with the particular file descriptors libcurl uses for the moment.

When you then call select, it will return when one of the file handles signal action and you then call curl_multi_perform to allow libcurl to do what it wants to do. Take note that libcurl does also feature some time-out code so we advise you to never use long timeouts on select before you call curl_multi_perform, which should be occasionally called unconditionally, even if none of its file descriptors have signaled ready. Another precaution you should use: always call curl_multi_fdset immediately before the select call since the current set of file descriptors may change when calling a curl function.

If you want to stop the transfer of one of the easy handles in the stack, you can use curl_multi_remove_handle to remove individual easy handles. Remember to use curl_easy_cleanup on easy handles.

When a transfer within the multi stack has finished, the counter of running transfers (as filled in by curl_multi_perform) will decrease. When the number reaches zero, all transfers are done.

curl_multi_info_read can be used to get information about completed transfers. It then returns the CURLcode for each easy transfer, to allow you to figure out success on each individual transfer.

See Also

HTTP Client Library (libcurl)

Revision History

2013/11/27 Worked link tags.
2013/09/12 Converted.