eb44502f33bd146bae6f78f9e687029fb2051772
[platform/upstream/curl.git] / docs / libcurl / libcurl-tutorial.3
1 .\" **************************************************************************
2 .\" *                                  _   _ ____  _
3 .\" *  Project                     ___| | | |  _ \| |
4 .\" *                             / __| | | | |_) | |
5 .\" *                            | (__| |_| |  _ <| |___
6 .\" *                             \___|\___/|_| \_\_____|
7 .\" *
8 .\" * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
9 .\" *
10 .\" * This software is licensed as described in the file COPYING, which
11 .\" * you should have received as part of this distribution. The terms
12 .\" * are also available at http://curl.haxx.se/docs/copyright.html.
13 .\" *
14 .\" * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 .\" * copies of the Software, and permit persons to whom the Software is
16 .\" * furnished to do so, under the terms of the COPYING file.
17 .\" *
18 .\" * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 .\" * KIND, either express or implied.
20 .\" *
21 .\" **************************************************************************
22 .\"
23 .TH libcurl-tutorial 3 "4 Mar 2009" "libcurl" "libcurl programming"
24 .SH NAME
25 libcurl-tutorial \- libcurl programming tutorial
26 .SH "Objective"
27 This document attempts to describe the general principles and some basic
28 approaches to consider when programming with libcurl. The text will focus
29 mainly on the C interface but might apply fairly well on other interfaces as
30 well as they usually follow the C one pretty closely.
31
32 This document will refer to 'the user' as the person writing the source code
33 that uses libcurl. That would probably be you or someone in your position.
34 What will be generally referred to as 'the program' will be the collected
35 source code that you write that is using libcurl for transfers. The program
36 is outside libcurl and libcurl is outside of the program.
37
38 To get more details on all options and functions described herein, please
39 refer to their respective man pages.
40
41 .SH "Building"
42 There are many different ways to build C programs. This chapter will assume a
43 UNIX-style build process. If you use a different build system, you can still
44 read this to get general information that may apply to your environment as
45 well.
46 .IP "Compiling the Program"
47 Your compiler needs to know where the libcurl headers are located. Therefore
48 you must set your compiler's include path to point to the directory where you
49 installed them. The 'curl-config'[3] tool can be used to get this information:
50
51 $ curl-config --cflags
52
53 .IP "Linking the Program with libcurl"
54 When having compiled the program, you need to link your object files to create
55 a single executable. For that to succeed, you need to link with libcurl and
56 possibly also with other libraries that libcurl itself depends on. Like the
57 OpenSSL libraries, but even some standard OS libraries may be needed on the
58 command line. To figure out which flags to use, once again the 'curl-config'
59 tool comes to the rescue:
60
61 $ curl-config --libs
62
63 .IP "SSL or Not"
64 libcurl can be built and customized in many ways. One of the things that
65 varies from different libraries and builds is the support for SSL-based
66 transfers, like HTTPS and FTPS. If a supported SSL library was detected
67 properly at build-time, libcurl will be built with SSL support. To figure out
68 if an installed libcurl has been built with SSL support enabled, use
69 \&'curl-config' like this:
70
71 $ curl-config --feature
72
73 And if SSL is supported, the keyword 'SSL' will be written to stdout,
74 possibly together with a few other features that could be either on or off on
75 for different libcurls.
76
77 See also the "Features libcurl Provides" further down.
78 .IP "autoconf macro"
79 When you write your configure script to detect libcurl and setup variables
80 accordingly, we offer a prewritten macro that probably does everything you
81 need in this area. See docs/libcurl/libcurl.m4 file - it includes docs on how
82 to use it.
83
84 .SH "Portable Code in a Portable World"
85 The people behind libcurl have put a considerable effort to make libcurl work
86 on a large amount of different operating systems and environments.
87
88 You program libcurl the same way on all platforms that libcurl runs on. There
89 are only very few minor considerations that differ. If you just make sure to
90 write your code portable enough, you may very well create yourself a very
91 portable program. libcurl shouldn't stop you from that.
92
93 .SH "Global Preparation"
94 The program must initialize some of the libcurl functionality globally. That
95 means it should be done exactly once, no matter how many times you intend to
96 use the library. Once for your program's entire life time. This is done using
97
98  curl_global_init()
99
100 and it takes one parameter which is a bit pattern that tells libcurl what to
101 initialize. Using \fICURL_GLOBAL_ALL\fP will make it initialize all known
102 internal sub modules, and might be a good default option. The current two bits
103 that are specified are:
104 .RS
105 .IP "CURL_GLOBAL_WIN32"
106 which only does anything on Windows machines. When used on
107 a Windows machine, it'll make libcurl initialize the win32 socket
108 stuff. Without having that initialized properly, your program cannot use
109 sockets properly. You should only do this once for each application, so if
110 your program already does this or of another library in use does it, you
111 should not tell libcurl to do this as well.
112 .IP CURL_GLOBAL_SSL
113 which only does anything on libcurls compiled and built SSL-enabled. On these
114 systems, this will make libcurl initialize the SSL library properly for this
115 application. This only needs to be done once for each application so if your
116 program or another library already does this, this bit should not be needed.
117 .RE
118
119 libcurl has a default protection mechanism that detects if
120 \fIcurl_global_init(3)\fP hasn't been called by the time
121 \fIcurl_easy_perform(3)\fP is called and if that is the case, libcurl runs the
122 function itself with a guessed bit pattern. Please note that depending solely
123 on this is not considered nice nor very good.
124
125 When the program no longer uses libcurl, it should call
126 \fIcurl_global_cleanup(3)\fP, which is the opposite of the init call. It will
127 then do the reversed operations to cleanup the resources the
128 \fIcurl_global_init(3)\fP call initialized.
129
130 Repeated calls to \fIcurl_global_init(3)\fP and \fIcurl_global_cleanup(3)\fP
131 should be avoided. They should only be called once each.
132
133 .SH "Features libcurl Provides"
134 It is considered best-practice to determine libcurl features at run-time
135 rather than at build-time (if possible of course). By calling
136 \fIcurl_version_info(3)\fP and checking out the details of the returned
137 struct, your program can figure out exactly what the currently running libcurl
138 supports.
139
140 .SH "Handle the Easy libcurl"
141 libcurl first introduced the so called easy interface. All operations in the
142 easy interface are prefixed with 'curl_easy'.
143
144 Recent libcurl versions also offer the multi interface. More about that
145 interface, what it is targeted for and how to use it is detailed in a separate
146 chapter further down. You still need to understand the easy interface first,
147 so please continue reading for better understanding.
148
149 To use the easy interface, you must first create yourself an easy handle. You
150 need one handle for each easy session you want to perform. Basically, you
151 should use one handle for every thread you plan to use for transferring. You
152 must never share the same handle in multiple threads.
153
154 Get an easy handle with
155
156  easyhandle = curl_easy_init();
157
158 It returns an easy handle. Using that you proceed to the next step: setting
159 up your preferred actions. A handle is just a logic entity for the upcoming
160 transfer or series of transfers.
161
162 You set properties and options for this handle using
163 \fIcurl_easy_setopt(3)\fP. They control how the subsequent transfer or
164 transfers will be made. Options remain set in the handle until set again to
165 something different. Alas, multiple requests using the same handle will use
166 the same options.
167
168 Many of the options you set in libcurl are "strings", pointers to data
169 terminated with a zero byte. When you set strings with
170 \fIcurl_easy_setopt(3)\fP, libcurl makes its own copy so that they don't
171 need to be kept around in your application after being set[4].
172
173 One of the most basic properties to set in the handle is the URL. You set
174 your preferred URL to transfer with CURLOPT_URL in a manner similar to:
175
176 .nf
177  curl_easy_setopt(handle, CURLOPT_URL, "http://domain.com/");
178 .fi
179
180 Let's assume for a while that you want to receive data as the URL identifies a
181 remote resource you want to get here. Since you write a sort of application
182 that needs this transfer, I assume that you would like to get the data passed
183 to you directly instead of simply getting it passed to stdout. So, you write
184 your own function that matches this prototype:
185
186  size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);
187
188 You tell libcurl to pass all data to this function by issuing a function
189 similar to this:
190
191  curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);
192
193 You can control what data your callback function gets in the fourth argument
194 by setting another property:
195
196  curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &internal_struct);
197
198 Using that property, you can easily pass local data between your application
199 and the function that gets invoked by libcurl. libcurl itself won't touch the
200 data you pass with \fICURLOPT_WRITEDATA\fP.
201
202 libcurl offers its own default internal callback that will take care of the data
203 if you don't set the callback with \fICURLOPT_WRITEFUNCTION\fP. It will then
204 simply output the received data to stdout. You can have the default callback
205 write the data to a different file handle by passing a 'FILE *' to a file
206 opened for writing with the \fICURLOPT_WRITEDATA\fP option.
207
208 Now, we need to take a step back and have a deep breath. Here's one of those
209 rare platform-dependent nitpicks. Did you spot it? On some platforms[2],
210 libcurl won't be able to operate on files opened by the program. Thus, if you
211 use the default callback and pass in an open file with
212 \fICURLOPT_WRITEDATA\fP, it will crash. You should therefore avoid this to
213 make your program run fine virtually everywhere.
214
215 (\fICURLOPT_WRITEDATA\fP was formerly known as \fICURLOPT_FILE\fP. Both names
216 still work and do the same thing).
217
218 If you're using libcurl as a win32 DLL, you MUST use the
219 \fICURLOPT_WRITEFUNCTION\fP if you set \fICURLOPT_WRITEDATA\fP - or you will
220 experience crashes.
221
222 There are of course many more options you can set, and we'll get back to a few
223 of them later. Let's instead continue to the actual transfer:
224
225  success = curl_easy_perform(easyhandle);
226
227 \fIcurl_easy_perform(3)\fP will connect to the remote site, do the necessary
228 commands and receive the transfer. Whenever it receives data, it calls the
229 callback function we previously set. The function may get one byte at a time,
230 or it may get many kilobytes at once. libcurl delivers as much as possible as
231 often as possible. Your callback function should return the number of bytes it
232 \&"took care of". If that is not the exact same amount of bytes that was
233 passed to it, libcurl will abort the operation and return with an error code.
234
235 When the transfer is complete, the function returns a return code that informs
236 you if it succeeded in its mission or not. If a return code isn't enough for
237 you, you can use the CURLOPT_ERRORBUFFER to point libcurl to a buffer of yours
238 where it'll store a human readable error message as well.
239
240 If you then want to transfer another file, the handle is ready to be used
241 again. Mind you, it is even preferred that you re-use an existing handle if
242 you intend to make another transfer. libcurl will then attempt to re-use the
243 previous connection.
244
245 For some protocols, downloading a file can involve a complicated process of
246 logging in, setting the transfer mode, changing the current directory and
247 finally transferring the file data. libcurl takes care of all that
248 complication for you. Given simply the URL to a file, libcurl will take care
249 of all the details needed to get the file moved from one machine to another.
250
251 .SH "Multi-threading Issues"
252 The first basic rule is that you must \fBnever\fP simultaneously share a
253 libcurl handle (be it easy or multi or whatever) between multiple
254 threads. Only use one handle in one thread at any time. You can pass the
255 handles around among threads, but you must never use a single handle from more
256 than one thread at any given time.
257
258 libcurl is completely thread safe, except for two issues: signals and SSL/TLS
259 handlers. Signals are used for timing out name resolves (during DNS lookup) -
260 when built without c-ares support and not on Windows.
261
262 If you are accessing HTTPS or FTPS URLs in a multi-threaded manner, you are
263 then of course using the underlying SSL library multi-threaded and those libs
264 might have their own requirements on this issue. Basically, you need to
265 provide one or two functions to allow it to function properly. For all
266 details, see this:
267
268 OpenSSL
269
270  http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION
271
272 GnuTLS
273
274  http://www.gnu.org/software/gnutls/manual/html_node/Multi_002dthreaded-applications.html
275
276 NSS
277
278  is claimed to be thread-safe already without anything required.
279
280 PolarSSL
281
282  Required actions unknown.
283
284 yassl
285
286  Required actions unknown.
287
288 axTLS
289
290  Required actions unknown.
291
292 Secure Transport
293
294  The engine is fully thread-safe, and no additional steps are required.
295
296 When using multiple threads you should set the CURLOPT_NOSIGNAL option to 1
297 for all handles. Everything will or might work fine except that timeouts are
298 not honored during the DNS lookup - which you can work around by building
299 libcurl with c-ares support. c-ares is a library that provides asynchronous
300 name resolves. On some platforms, libcurl simply will not function properly
301 multi-threaded unless this option is set.
302
303 Also, note that CURLOPT_DNS_USE_GLOBAL_CACHE is not thread-safe.
304
305 .SH "When It Doesn't Work"
306 There will always be times when the transfer fails for some reason. You might
307 have set the wrong libcurl option or misunderstood what the libcurl option
308 actually does, or the remote server might return non-standard replies that
309 confuse the library which then confuses your program.
310
311 There's one golden rule when these things occur: set the CURLOPT_VERBOSE
312 option to 1. It'll cause the library to spew out the entire protocol
313 details it sends, some internal info and some received protocol data as well
314 (especially when using FTP). If you're using HTTP, adding the headers in the
315 received output to study is also a clever way to get a better understanding
316 why the server behaves the way it does. Include headers in the normal body
317 output with CURLOPT_HEADER set 1.
318
319 Of course, there are bugs left. We need to know about them to be able
320 to fix them, so we're quite dependent on your bug reports! When you do report
321 suspected bugs in libcurl, please include as many details as you possibly can: a
322 protocol dump that CURLOPT_VERBOSE produces, library version, as much as
323 possible of your code that uses libcurl, operating system name and version,
324 compiler name and version etc.
325
326 If CURLOPT_VERBOSE is not enough, you increase the level of debug data your
327 application receive by using the CURLOPT_DEBUGFUNCTION.
328
329 Getting some in-depth knowledge about the protocols involved is never wrong,
330 and if you're trying to do funny things, you might very well understand
331 libcurl and how to use it better if you study the appropriate RFC documents
332 at least briefly.
333
334 .SH "Upload Data to a Remote Site"
335 libcurl tries to keep a protocol independent approach to most transfers, thus
336 uploading to a remote FTP site is very similar to uploading data to a HTTP
337 server with a PUT request.
338
339 Of course, first you either create an easy handle or you re-use one existing
340 one. Then you set the URL to operate on just like before. This is the remote
341 URL, that we now will upload.
342
343 Since we write an application, we most likely want libcurl to get the upload
344 data by asking us for it. To make it do that, we set the read callback and
345 the custom pointer libcurl will pass to our read callback. The read callback
346 should have a prototype similar to:
347
348  size_t function(char *bufptr, size_t size, size_t nitems, void *userp);
349
350 Where bufptr is the pointer to a buffer we fill in with data to upload and
351 size*nitems is the size of the buffer and therefore also the maximum amount
352 of data we can return to libcurl in this call. The 'userp' pointer is the
353 custom pointer we set to point to a struct of ours to pass private data
354 between the application and the callback.
355
356  curl_easy_setopt(easyhandle, CURLOPT_READFUNCTION, read_function);
357
358  curl_easy_setopt(easyhandle, CURLOPT_READDATA, &filedata);
359
360 Tell libcurl that we want to upload:
361
362  curl_easy_setopt(easyhandle, CURLOPT_UPLOAD, 1L);
363
364 A few protocols won't behave properly when uploads are done without any prior
365 knowledge of the expected file size. So, set the upload file size using the
366 CURLOPT_INFILESIZE_LARGE for all known file sizes like this[1]:
367
368 .nf
369  /* in this example, file_size must be an curl_off_t variable */
370  curl_easy_setopt(easyhandle, CURLOPT_INFILESIZE_LARGE, file_size);
371 .fi
372
373 When you call \fIcurl_easy_perform(3)\fP this time, it'll perform all the
374 necessary operations and when it has invoked the upload it'll call your
375 supplied callback to get the data to upload. The program should return as much
376 data as possible in every invoke, as that is likely to make the upload perform
377 as fast as possible. The callback should return the number of bytes it wrote
378 in the buffer. Returning 0 will signal the end of the upload.
379
380 .SH "Passwords"
381 Many protocols use or even require that user name and password are provided
382 to be able to download or upload the data of your choice. libcurl offers
383 several ways to specify them.
384
385 Most protocols support that you specify the name and password in the URL
386 itself. libcurl will detect this and use them accordingly. This is written
387 like this:
388
389  protocol://user:password@example.com/path/
390
391 If you need any odd letters in your user name or password, you should enter
392 them URL encoded, as %XX where XX is a two-digit hexadecimal number.
393
394 libcurl also provides options to set various passwords. The user name and
395 password as shown embedded in the URL can instead get set with the
396 CURLOPT_USERPWD option. The argument passed to libcurl should be a char * to
397 a string in the format "user:password". In a manner like this:
398
399  curl_easy_setopt(easyhandle, CURLOPT_USERPWD, "myname:thesecret");
400
401 Another case where name and password might be needed at times, is for those
402 users who need to authenticate themselves to a proxy they use. libcurl offers
403 another option for this, the CURLOPT_PROXYUSERPWD. It is used quite similar
404 to the CURLOPT_USERPWD option like this:
405
406  curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "myname:thesecret");
407
408 There's a long time UNIX "standard" way of storing ftp user names and
409 passwords, namely in the $HOME/.netrc file. The file should be made private
410 so that only the user may read it (see also the "Security Considerations"
411 chapter), as it might contain the password in plain text. libcurl has the
412 ability to use this file to figure out what set of user name and password to
413 use for a particular host. As an extension to the normal functionality,
414 libcurl also supports this file for non-FTP protocols such as HTTP. To make
415 curl use this file, use the CURLOPT_NETRC option:
416
417  curl_easy_setopt(easyhandle, CURLOPT_NETRC, 1L);
418
419 And a very basic example of how such a .netrc file may look like:
420
421 .nf
422  machine myhost.mydomain.com
423  login userlogin
424  password secretword
425 .fi
426
427 All these examples have been cases where the password has been optional, or
428 at least you could leave it out and have libcurl attempt to do its job
429 without it. There are times when the password isn't optional, like when
430 you're using an SSL private key for secure transfers.
431
432 To pass the known private key password to libcurl:
433
434  curl_easy_setopt(easyhandle, CURLOPT_KEYPASSWD, "keypassword");
435
436 .SH "HTTP Authentication"
437 The previous chapter showed how to set user name and password for getting
438 URLs that require authentication. When using the HTTP protocol, there are
439 many different ways a client can provide those credentials to the server and
440 you can control which way libcurl will (attempt to) use them. The default HTTP
441 authentication method is called 'Basic', which is sending the name and
442 password in clear-text in the HTTP request, base64-encoded. This is insecure.
443
444 At the time of this writing, libcurl can be built to use: Basic, Digest, NTLM,
445 Negotiate, GSS-Negotiate and SPNEGO. You can tell libcurl which one to use
446 with CURLOPT_HTTPAUTH as in:
447
448  curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
449
450 And when you send authentication to a proxy, you can also set authentication
451 type the same way but instead with CURLOPT_PROXYAUTH:
452
453  curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
454
455 Both these options allow you to set multiple types (by ORing them together),
456 to make libcurl pick the most secure one out of the types the server/proxy
457 claims to support. This method does however add a round-trip since libcurl
458 must first ask the server what it supports:
459
460  curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH,
461  CURLAUTH_DIGEST|CURLAUTH_BASIC);
462
463 For convenience, you can use the 'CURLAUTH_ANY' define (instead of a list
464 with specific types) which allows libcurl to use whatever method it wants.
465
466 When asking for multiple types, libcurl will pick the available one it
467 considers "best" in its own internal order of preference.
468
469 .SH "HTTP POSTing"
470 We get many questions regarding how to issue HTTP POSTs with libcurl the
471 proper way. This chapter will thus include examples using both different
472 versions of HTTP POST that libcurl supports.
473
474 The first version is the simple POST, the most common version, that most HTML
475 pages using the <form> tag uses. We provide a pointer to the data and tell
476 libcurl to post it all to the remote site:
477
478 .nf
479     char *data="name=daniel&project=curl";
480     curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, data);
481     curl_easy_setopt(easyhandle, CURLOPT_URL, "http://posthere.com/");
482
483     curl_easy_perform(easyhandle); /* post away! */
484 .fi
485
486 Simple enough, huh? Since you set the POST options with the
487 CURLOPT_POSTFIELDS, this automatically switches the handle to use POST in the
488 upcoming request.
489
490 Ok, so what if you want to post binary data that also requires you to set the
491 Content-Type: header of the post? Well, binary posts prevent libcurl from
492 being able to do strlen() on the data to figure out the size, so therefore we
493 must tell libcurl the size of the post data. Setting headers in libcurl
494 requests are done in a generic way, by building a list of our own headers and
495 then passing that list to libcurl.
496
497 .nf
498  struct curl_slist *headers=NULL;
499  headers = curl_slist_append(headers, "Content-Type: text/xml");
500
501  /* post binary data */
502  curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, binaryptr);
503
504  /* set the size of the postfields data */
505  curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDSIZE, 23L);
506
507  /* pass our list of custom made headers */
508  curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);
509
510  curl_easy_perform(easyhandle); /* post away! */
511
512  curl_slist_free_all(headers); /* free the header list */
513 .fi
514
515 While the simple examples above cover the majority of all cases where HTTP
516 POST operations are required, they don't do multi-part formposts. Multi-part
517 formposts were introduced as a better way to post (possibly large) binary data
518 and were first documented in the RFC1867 (updated in RFC2388). They're called
519 multi-part because they're built by a chain of parts, each part being a single
520 unit of data. Each part has its own name and contents. You can in fact create
521 and post a multi-part formpost with the regular libcurl POST support described
522 above, but that would require that you build a formpost yourself and provide
523 to libcurl. To make that easier, libcurl provides \fIcurl_formadd(3)\fP. Using
524 this function, you add parts to the form. When you're done adding parts, you
525 post the whole form.
526
527 The following example sets two simple text parts with plain textual contents,
528 and then a file with binary contents and uploads the whole thing.
529
530 .nf
531  struct curl_httppost *post=NULL;
532  struct curl_httppost *last=NULL;
533  curl_formadd(&post, &last,
534               CURLFORM_COPYNAME, "name",
535               CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END);
536  curl_formadd(&post, &last,
537               CURLFORM_COPYNAME, "project",
538               CURLFORM_COPYCONTENTS, "curl", CURLFORM_END);
539  curl_formadd(&post, &last,
540               CURLFORM_COPYNAME, "logotype-image",
541               CURLFORM_FILECONTENT, "curl.png", CURLFORM_END);
542
543  /* Set the form info */
544  curl_easy_setopt(easyhandle, CURLOPT_HTTPPOST, post);
545
546  curl_easy_perform(easyhandle); /* post away! */
547
548  /* free the post data again */
549  curl_formfree(post);
550 .fi
551
552 Multipart formposts are chains of parts using MIME-style separators and
553 headers. It means that each one of these separate parts get a few headers set
554 that describe the individual content-type, size etc. To enable your
555 application to handicraft this formpost even more, libcurl allows you to
556 supply your own set of custom headers to such an individual form part. You can
557 of course supply headers to as many parts as you like, but this little example
558 will show how you set headers to one specific part when you add that to the
559 post handle:
560
561 .nf
562  struct curl_slist *headers=NULL;
563  headers = curl_slist_append(headers, "Content-Type: text/xml");
564
565  curl_formadd(&post, &last,
566               CURLFORM_COPYNAME, "logotype-image",
567               CURLFORM_FILECONTENT, "curl.xml",
568               CURLFORM_CONTENTHEADER, headers,
569               CURLFORM_END);
570
571  curl_easy_perform(easyhandle); /* post away! */
572
573  curl_formfree(post); /* free post */
574  curl_slist_free_all(headers); /* free custom header list */
575 .fi
576
577 Since all options on an easyhandle are "sticky", they remain the same until
578 changed even if you do call \fIcurl_easy_perform(3)\fP, you may need to tell
579 curl to go back to a plain GET request if you intend to do one as your
580 next request. You force an easyhandle to go back to GET by using the
581 CURLOPT_HTTPGET option:
582
583  curl_easy_setopt(easyhandle, CURLOPT_HTTPGET, 1L);
584
585 Just setting CURLOPT_POSTFIELDS to "" or NULL will *not* stop libcurl from
586 doing a POST. It will just make it POST without any data to send!
587
588 .SH "Showing Progress"
589
590 For historical and traditional reasons, libcurl has a built-in progress meter
591 that can be switched on and then makes it present a progress meter in your
592 terminal.
593
594 Switch on the progress meter by, oddly enough, setting CURLOPT_NOPROGRESS to
595 zero. This option is set to 1 by default.
596
597 For most applications however, the built-in progress meter is useless and
598 what instead is interesting is the ability to specify a progress
599 callback. The function pointer you pass to libcurl will then be called on
600 irregular intervals with information about the current transfer.
601
602 Set the progress callback by using CURLOPT_PROGRESSFUNCTION. And pass a
603 pointer to a function that matches this prototype:
604
605 .nf
606  int progress_callback(void *clientp,
607                        double dltotal,
608                        double dlnow,
609                        double ultotal,
610                        double ulnow);
611 .fi
612
613 If any of the input arguments is unknown, a 0 will be passed. The first
614 argument, the 'clientp' is the pointer you pass to libcurl with
615 CURLOPT_PROGRESSDATA. libcurl won't touch it.
616
617 .SH "libcurl with C++"
618
619 There's basically only one thing to keep in mind when using C++ instead of C
620 when interfacing libcurl:
621
622 The callbacks CANNOT be non-static class member functions
623
624 Example C++ code:
625
626 .nf
627 class AClass {
628     static size_t write_data(void *ptr, size_t size, size_t nmemb,
629                              void *ourpointer)
630     {
631       /* do what you want with the data */
632     }
633  }
634 .fi
635
636 .SH "Proxies"
637
638 What "proxy" means according to Merriam-Webster: "a person authorized to act
639 for another" but also "the agency, function, or office of a deputy who acts as
640 a substitute for another".
641
642 Proxies are exceedingly common these days. Companies often only offer Internet
643 access to employees through their proxies. Network clients or user-agents ask
644 the proxy for documents, the proxy does the actual request and then it returns
645 them.
646
647 libcurl supports SOCKS and HTTP proxies. When a given URL is wanted, libcurl
648 will ask the proxy for it instead of trying to connect to the actual host
649 identified in the URL.
650
651 If you're using a SOCKS proxy, you may find that libcurl doesn't quite support
652 all operations through it.
653
654 For HTTP proxies: the fact that the proxy is a HTTP proxy puts certain
655 restrictions on what can actually happen. A requested URL that might not be a
656 HTTP URL will be still be passed to the HTTP proxy to deliver back to
657 libcurl. This happens transparently, and an application may not need to
658 know. I say "may", because at times it is very important to understand that
659 all operations over a HTTP proxy use the HTTP protocol. For example, you
660 can't invoke your own custom FTP commands or even proper FTP directory
661 listings.
662
663 .IP "Proxy Options"
664
665 To tell libcurl to use a proxy at a given port number:
666
667  curl_easy_setopt(easyhandle, CURLOPT_PROXY, "proxy-host.com:8080");
668
669 Some proxies require user authentication before allowing a request, and you
670 pass that information similar to this:
671
672  curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "user:password");
673
674 If you want to, you can specify the host name only in the CURLOPT_PROXY
675 option, and set the port number separately with CURLOPT_PROXYPORT.
676
677 Tell libcurl what kind of proxy it is with CURLOPT_PROXYTYPE (if not, it will
678 default to assume a HTTP proxy):
679
680  curl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
681
682 .IP "Environment Variables"
683
684 libcurl automatically checks and uses a set of environment variables to know
685 what proxies to use for certain protocols. The names of the variables are
686 following an ancient de facto standard and are built up as "[protocol]_proxy"
687 (note the lower casing). Which makes the variable \&'http_proxy' checked for a
688 name of a proxy to use when the input URL is HTTP. Following the same rule,
689 the variable named 'ftp_proxy' is checked for FTP URLs. Again, the proxies are
690 always HTTP proxies, the different names of the variables simply allows
691 different HTTP proxies to be used.
692
693 The proxy environment variable contents should be in the format
694 \&"[protocol://][user:password@]machine[:port]". Where the protocol:// part is
695 simply ignored if present (so http://proxy and bluerk://proxy will do the
696 same) and the optional port number specifies on which port the proxy operates
697 on the host. If not specified, the internal default port number will be used
698 and that is most likely *not* the one you would like it to be.
699
700 There are two special environment variables. 'all_proxy' is what sets proxy
701 for any URL in case the protocol specific variable wasn't set, and
702 \&'no_proxy' defines a list of hosts that should not use a proxy even though a
703 variable may say so. If 'no_proxy' is a plain asterisk ("*") it matches all
704 hosts.
705
706 To explicitly disable libcurl's checking for and using the proxy environment
707 variables, set the proxy name to "" - an empty string - with CURLOPT_PROXY.
708 .IP "SSL and Proxies"
709
710 SSL is for secure point-to-point connections. This involves strong encryption
711 and similar things, which effectively makes it impossible for a proxy to
712 operate as a "man in between" which the proxy's task is, as previously
713 discussed. Instead, the only way to have SSL work over a HTTP proxy is to ask
714 the proxy to tunnel trough everything without being able to check or fiddle
715 with the traffic.
716
717 Opening an SSL connection over a HTTP proxy is therefor a matter of asking the
718 proxy for a straight connection to the target host on a specified port. This
719 is made with the HTTP request CONNECT. ("please mr proxy, connect me to that
720 remote host").
721
722 Because of the nature of this operation, where the proxy has no idea what kind
723 of data that is passed in and out through this tunnel, this breaks some of the
724 very few advantages that come from using a proxy, such as caching.  Many
725 organizations prevent this kind of tunneling to other destination port numbers
726 than 443 (which is the default HTTPS port number).
727
728 .IP "Tunneling Through Proxy"
729 As explained above, tunneling is required for SSL to work and often even
730 restricted to the operation intended for SSL; HTTPS.
731
732 This is however not the only time proxy-tunneling might offer benefits to
733 you or your application.
734
735 As tunneling opens a direct connection from your application to the remote
736 machine, it suddenly also re-introduces the ability to do non-HTTP
737 operations over a HTTP proxy. You can in fact use things such as FTP
738 upload or FTP custom commands this way.
739
740 Again, this is often prevented by the administrators of proxies and is
741 rarely allowed.
742
743 Tell libcurl to use proxy tunneling like this:
744
745  curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
746
747 In fact, there might even be times when you want to do plain HTTP
748 operations using a tunnel like this, as it then enables you to operate on
749 the remote server instead of asking the proxy to do so. libcurl will not
750 stand in the way for such innovative actions either!
751
752 .IP "Proxy Auto-Config"
753
754 Netscape first came up with this. It is basically a web page (usually using a
755 \&.pac extension) with a Javascript that when executed by the browser with the
756 requested URL as input, returns information to the browser on how to connect
757 to the URL. The returned information might be "DIRECT" (which means no proxy
758 should be used), "PROXY host:port" (to tell the browser where the proxy for
759 this particular URL is) or "SOCKS host:port" (to direct the browser to a SOCKS
760 proxy).
761
762 libcurl has no means to interpret or evaluate Javascript and thus it doesn't
763 support this. If you get yourself in a position where you face this nasty
764 invention, the following advice have been mentioned and used in the past:
765
766 - Depending on the Javascript complexity, write up a script that translates it
767 to another language and execute that.
768
769 - Read the Javascript code and rewrite the same logic in another language.
770
771 - Implement a Javascript interpreter; people have successfully used the
772 Mozilla Javascript engine in the past.
773
774 - Ask your admins to stop this, for a static proxy setup or similar.
775
776 .SH "Persistence Is The Way to Happiness"
777
778 Re-cycling the same easy handle several times when doing multiple requests is
779 the way to go.
780
781 After each single \fIcurl_easy_perform(3)\fP operation, libcurl will keep the
782 connection alive and open. A subsequent request using the same easy handle to
783 the same host might just be able to use the already open connection! This
784 reduces network impact a lot.
785
786 Even if the connection is dropped, all connections involving SSL to the same
787 host again, will benefit from libcurl's session ID cache that drastically
788 reduces re-connection time.
789
790 FTP connections that are kept alive save a lot of time, as the command-
791 response round-trips are skipped, and also you don't risk getting blocked
792 without permission to login again like on many FTP servers only allowing N
793 persons to be logged in at the same time.
794
795 libcurl caches DNS name resolving results, to make lookups of a previously
796 looked up name a lot faster.
797
798 Other interesting details that improve performance for subsequent requests
799 may also be added in the future.
800
801 Each easy handle will attempt to keep the last few connections alive for a
802 while in case they are to be used again. You can set the size of this "cache"
803 with the CURLOPT_MAXCONNECTS option. Default is 5. There is very seldom any
804 point in changing this value, and if you think of changing this it is often
805 just a matter of thinking again.
806
807 To force your upcoming request to not use an already existing connection (it
808 will even close one first if there happens to be one alive to the same host
809 you're about to operate on), you can do that by setting CURLOPT_FRESH_CONNECT
810 to 1. In a similar spirit, you can also forbid the upcoming request to be
811 "lying" around and possibly get re-used after the request by setting
812 CURLOPT_FORBID_REUSE to 1.
813
814 .SH "HTTP Headers Used by libcurl"
815 When you use libcurl to do HTTP requests, it'll pass along a series of headers
816 automatically. It might be good for you to know and understand these. You
817 can replace or remove them by using the CURLOPT_HTTPHEADER option.
818
819 .IP "Host"
820 This header is required by HTTP 1.1 and even many 1.0 servers and should be
821 the name of the server we want to talk to. This includes the port number if
822 anything but default.
823
824 .IP "Accept"
825 \&"*/*".
826
827 .IP "Expect"
828 When doing POST requests, libcurl sets this header to \&"100-continue" to ask
829 the server for an "OK" message before it proceeds with sending the data part
830 of the post. If the POSTed data amount is deemed "small", libcurl will not use
831 this header.
832
833 .SH "Customizing Operations"
834 There is an ongoing development today where more and more protocols are built
835 upon HTTP for transport. This has obvious benefits as HTTP is a tested and
836 reliable protocol that is widely deployed and has excellent proxy-support.
837
838 When you use one of these protocols, and even when doing other kinds of
839 programming you may need to change the traditional HTTP (or FTP or...)
840 manners. You may need to change words, headers or various data.
841
842 libcurl is your friend here too.
843
844 .IP CUSTOMREQUEST
845 If just changing the actual HTTP request keyword is what you want, like when
846 GET, HEAD or POST is not good enough for you, CURLOPT_CUSTOMREQUEST is there
847 for you. It is very simple to use:
848
849  curl_easy_setopt(easyhandle, CURLOPT_CUSTOMREQUEST, "MYOWNREQUEST");
850
851 When using the custom request, you change the request keyword of the actual
852 request you are performing. Thus, by default you make a GET request but you can
853 also make a POST operation (as described before) and then replace the POST
854 keyword if you want to. You're the boss.
855
856 .IP "Modify Headers"
857 HTTP-like protocols pass a series of headers to the server when doing the
858 request, and you're free to pass any amount of extra headers that you
859 think fit. Adding headers is this easy:
860
861 .nf
862  struct curl_slist *headers=NULL; /* init to NULL is important */
863
864  headers = curl_slist_append(headers, "Hey-server-hey: how are you?");
865  headers = curl_slist_append(headers, "X-silly-content: yes");
866
867  /* pass our list of custom made headers */
868  curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);
869
870  curl_easy_perform(easyhandle); /* transfer http */
871
872  curl_slist_free_all(headers); /* free the header list */
873 .fi
874
875 \&... and if you think some of the internally generated headers, such as
876 Accept: or Host: don't contain the data you want them to contain, you can
877 replace them by simply setting them too:
878
879 .nf
880  headers = curl_slist_append(headers, "Accept: Agent-007");
881  headers = curl_slist_append(headers, "Host: munged.host.line");
882 .fi
883
884 .IP "Delete Headers"
885 If you replace an existing header with one with no contents, you will prevent
886 the header from being sent. For instance, if you want to completely prevent the
887 \&"Accept:" header from being sent, you can disable it with code similar to this:
888
889  headers = curl_slist_append(headers, "Accept:");
890
891 Both replacing and canceling internal headers should be done with careful
892 consideration and you should be aware that you may violate the HTTP protocol
893 when doing so.
894
895 .IP "Enforcing chunked transfer-encoding"
896
897 By making sure a request uses the custom header "Transfer-Encoding: chunked"
898 when doing a non-GET HTTP operation, libcurl will switch over to "chunked"
899 upload, even though the size of the data to upload might be known. By default,
900 libcurl usually switches over to chunked upload automatically if the upload
901 data size is unknown.
902
903 .IP "HTTP Version"
904
905 All HTTP requests includes the version number to tell the server which version
906 we support. libcurl speaks HTTP 1.1 by default. Some very old servers don't
907 like getting 1.1-requests and when dealing with stubborn old things like that,
908 you can tell libcurl to use 1.0 instead by doing something like this:
909
910  curl_easy_setopt(easyhandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
911
912 .IP "FTP Custom Commands"
913
914 Not all protocols are HTTP-like, and thus the above may not help you when
915 you want to make, for example, your FTP transfers to behave differently.
916
917 Sending custom commands to a FTP server means that you need to send the
918 commands exactly as the FTP server expects them (RFC959 is a good guide
919 here), and you can only use commands that work on the control-connection
920 alone. All kinds of commands that require data interchange and thus need
921 a data-connection must be left to libcurl's own judgement. Also be aware
922 that libcurl will do its very best to change directory to the target
923 directory before doing any transfer, so if you change directory (with CWD
924 or similar) you might confuse libcurl and then it might not attempt to
925 transfer the file in the correct remote directory.
926
927 A little example that deletes a given file before an operation:
928
929 .nf
930  headers = curl_slist_append(headers, "DELE file-to-remove");
931
932  /* pass the list of custom commands to the handle */
933  curl_easy_setopt(easyhandle, CURLOPT_QUOTE, headers);
934
935  curl_easy_perform(easyhandle); /* transfer ftp data! */
936
937  curl_slist_free_all(headers); /* free the header list */
938 .fi
939
940 If you would instead want this operation (or chain of operations) to happen
941 _after_ the data transfer took place the option to \fIcurl_easy_setopt(3)\fP
942 would instead be called CURLOPT_POSTQUOTE and used the exact same way.
943
944 The custom FTP command will be issued to the server in the same order they are
945 added to the list, and if a command gets an error code returned back from the
946 server, no more commands will be issued and libcurl will bail out with an
947 error code (CURLE_QUOTE_ERROR). Note that if you use CURLOPT_QUOTE to send
948 commands before a transfer, no transfer will actually take place when a quote
949 command has failed.
950
951 If you set the CURLOPT_HEADER to 1, you will tell libcurl to get
952 information about the target file and output "headers" about it. The headers
953 will be in "HTTP-style", looking like they do in HTTP.
954
955 The option to enable headers or to run custom FTP commands may be useful to
956 combine with CURLOPT_NOBODY. If this option is set, no actual file content
957 transfer will be performed.
958
959 .IP "FTP Custom CUSTOMREQUEST"
960 If you do want to list the contents of a FTP directory using your own defined FTP
961 command, CURLOPT_CUSTOMREQUEST will do just that. "NLST" is the default one
962 for listing directories but you're free to pass in your idea of a good
963 alternative.
964
965 .SH "Cookies Without Chocolate Chips"
966 In the HTTP sense, a cookie is a name with an associated value. A server sends
967 the name and value to the client, and expects it to get sent back on every
968 subsequent request to the server that matches the particular conditions
969 set. The conditions include that the domain name and path match and that the
970 cookie hasn't become too old.
971
972 In real-world cases, servers send new cookies to replace existing ones to
973 update them. Server use cookies to "track" users and to keep "sessions".
974
975 Cookies are sent from server to clients with the header Set-Cookie: and
976 they're sent from clients to servers with the Cookie: header.
977
978 To just send whatever cookie you want to a server, you can use CURLOPT_COOKIE
979 to set a cookie string like this:
980
981  curl_easy_setopt(easyhandle, CURLOPT_COOKIE, "name1=var1; name2=var2;");
982
983 In many cases, that is not enough. You might want to dynamically save
984 whatever cookies the remote server passes to you, and make sure those cookies
985 are then used accordingly on later requests.
986
987 One way to do this, is to save all headers you receive in a plain file and
988 when you make a request, you tell libcurl to read the previous headers to
989 figure out which cookies to use. Set the header file to read cookies from with
990 CURLOPT_COOKIEFILE.
991
992 The CURLOPT_COOKIEFILE option also automatically enables the cookie parser in
993 libcurl. Until the cookie parser is enabled, libcurl will not parse or
994 understand incoming cookies and they will just be ignored. However, when the
995 parser is enabled the cookies will be understood and the cookies will be kept
996 in memory and used properly in subsequent requests when the same handle is
997 used. Many times this is enough, and you may not have to save the cookies to
998 disk at all. Note that the file you specify to CURLOPT_COOKIEFILE doesn't have
999 to exist to enable the parser, so a common way to just enable the parser and
1000 not read any cookies is to use the name of a file you know doesn't exist.
1001
1002 If you would rather use existing cookies that you've previously received with
1003 your Netscape or Mozilla browsers, you can make libcurl use that cookie file
1004 as input. The CURLOPT_COOKIEFILE is used for that too, as libcurl will
1005 automatically find out what kind of file it is and act accordingly.
1006
1007 Perhaps the most advanced cookie operation libcurl offers, is saving the
1008 entire internal cookie state back into a Netscape/Mozilla formatted cookie
1009 file. We call that the cookie-jar. When you set a file name with
1010 CURLOPT_COOKIEJAR, that file name will be created and all received cookies
1011 will be stored in it when \fIcurl_easy_cleanup(3)\fP is called. This enables
1012 cookies to get passed on properly between multiple handles without any
1013 information getting lost.
1014
1015 .SH "FTP Peculiarities We Need"
1016
1017 FTP transfers use a second TCP/IP connection for the data transfer. This is
1018 usually a fact you can forget and ignore but at times this fact will come
1019 back to haunt you. libcurl offers several different ways to customize how the
1020 second connection is being made.
1021
1022 libcurl can either connect to the server a second time or tell the server to
1023 connect back to it. The first option is the default and it is also what works
1024 best for all the people behind firewalls, NATs or IP-masquerading setups.
1025 libcurl then tells the server to open up a new port and wait for a second
1026 connection. This is by default attempted with EPSV first, and if that doesn't
1027 work it tries PASV instead. (EPSV is an extension to the original FTP spec
1028 and does not exist nor work on all FTP servers.)
1029
1030 You can prevent libcurl from first trying the EPSV command by setting
1031 CURLOPT_FTP_USE_EPSV to zero.
1032
1033 In some cases, you will prefer to have the server connect back to you for the
1034 second connection. This might be when the server is perhaps behind a firewall
1035 or something and only allows connections on a single port. libcurl then
1036 informs the remote server which IP address and port number to connect to.
1037 This is made with the CURLOPT_FTPPORT option. If you set it to "-", libcurl
1038 will use your system's "default IP address". If you want to use a particular
1039 IP, you can set the full IP address, a host name to resolve to an IP address
1040 or even a local network interface name that libcurl will get the IP address
1041 from.
1042
1043 When doing the "PORT" approach, libcurl will attempt to use the EPRT and the
1044 LPRT before trying PORT, as they work with more protocols. You can disable
1045 this behavior by setting CURLOPT_FTP_USE_EPRT to zero.
1046
1047 .SH "Headers Equal Fun"
1048
1049 Some protocols provide "headers", meta-data separated from the normal
1050 data. These headers are by default not included in the normal data stream,
1051 but you can make them appear in the data stream by setting CURLOPT_HEADER to
1052 1.
1053
1054 What might be even more useful, is libcurl's ability to separate the headers
1055 from the data and thus make the callbacks differ. You can for example set a
1056 different pointer to pass to the ordinary write callback by setting
1057 CURLOPT_WRITEHEADER.
1058
1059 Or, you can set an entirely separate function to receive the headers, by
1060 using CURLOPT_HEADERFUNCTION.
1061
1062 The headers are passed to the callback function one by one, and you can
1063 depend on that fact. It makes it easier for you to add custom header parsers
1064 etc.
1065
1066 \&"Headers" for FTP transfers equal all the FTP server responses. They aren't
1067 actually true headers, but in this case we pretend they are! ;-)
1068
1069 .SH "Post Transfer Information"
1070
1071  [ curl_easy_getinfo ]
1072
1073 .SH "Security Considerations"
1074
1075 The libcurl project takes security seriously.  The library is written with
1076 caution and precautions are taken to mitigate many kinds of risks encountered
1077 while operating with potentially malicious servers on the Internet.  It is a
1078 powerful library, however, which allows application writers to make trade offs
1079 between ease of writing and exposure to potential risky operations.  If
1080 used the right way, you can use libcurl to transfer data pretty safely.
1081
1082 Many applications are used in closed networks where users and servers
1083 can be trusted, but many others are used on arbitrary servers and are fed
1084 input from potentially untrusted users.  Following is a discussion about
1085 some risks in the ways in which applications commonly use libcurl and
1086 potential mitigations of those risks. It is by no means comprehensive, but
1087 shows classes of attacks that robust applications should consider. The
1088 Common Weakness Enumeration project at http://cwe.mitre.org/ is a good
1089 reference for many of these and similar types of weaknesses of which
1090 application writers should be aware.
1091
1092 .IP "Command Lines"
1093 If you use a command line tool (such as curl) that uses libcurl, and you give
1094 options to the tool on the command line those options can very likely get read
1095 by other users of your system when they use 'ps' or other tools to list
1096 currently running processes.
1097
1098 To avoid this problem, never feed sensitive things to programs using command
1099 line options. Write them to a protected file and use the \-K option to
1100 avoid this.
1101
1102 .IP ".netrc"
1103 \&.netrc is a pretty handy file/feature that allows you to login quickly and
1104 automatically to frequently visited sites. The file contains passwords in
1105 clear text and is a real security risk. In some cases, your .netrc is also
1106 stored in a home directory that is NFS mounted or used on another network
1107 based file system, so the clear text password will fly through your network
1108 every time anyone reads that file!
1109
1110 To avoid this problem, don't use .netrc files and never store passwords in
1111 plain text anywhere.
1112
1113 .IP "Clear Text Passwords"
1114 Many of the protocols libcurl supports send name and password unencrypted as
1115 clear text (HTTP Basic authentication, FTP, TELNET etc). It is very easy for
1116 anyone on your network or a network nearby yours to just fire up a network
1117 analyzer tool and eavesdrop on your passwords. Don't let the fact that HTTP
1118 Basic uses base64 encoded passwords fool you. They may not look readable at a
1119 first glance, but they very easily "deciphered" by anyone within seconds.
1120
1121 To avoid this problem, use HTTP authentication methods or other protocols that
1122 don't let snoopers see your password: HTTP with Digest, NTLM or GSS
1123 authentication, HTTPS, FTPS, SCP, SFTP and FTP-Kerberos are a few examples.
1124
1125 .IP "Redirects"
1126 The CURLOPT_FOLLOWLOCATION option automatically follows HTTP redirects sent
1127 by a remote server.  These redirects can refer to any kind of URL, not just
1128 HTTP.  A redirect to a file: URL would cause the libcurl to read (or write)
1129 arbitrary files from the local filesystem.  If the application returns
1130 the data back to the user (as would happen in some kinds of CGI scripts),
1131 an attacker could leverage this to read otherwise forbidden data (e.g.
1132 file://localhost/etc/passwd).
1133
1134 If authentication credentials are stored in the ~/.netrc file, or Kerberos
1135 is in use, any other URL type (not just file:) that requires
1136 authentication is also at risk.  A redirect such as
1137 ftp://some-internal-server/private-file would then return data even when
1138 the server is password protected.
1139
1140 In the same way, if an unencrypted SSH private key has been configured for
1141 the user running the libcurl application, SCP: or SFTP: URLs could access
1142 password or private-key protected resources,
1143 e.g. sftp://user@some-internal-server/etc/passwd
1144
1145 The CURLOPT_REDIR_PROTOCOLS and CURLOPT_NETRC options can be used to
1146 mitigate against this kind of attack.
1147
1148 A redirect can also specify a location available only on the machine running
1149 libcurl, including servers hidden behind a firewall from the attacker.
1150 e.g. http://127.0.0.1/ or http://intranet/delete-stuff.cgi?delete=all or
1151 tftp://bootp-server/pc-config-data
1152
1153 Apps can mitigate against this by disabling CURLOPT_FOLLOWLOCATION and
1154 handling redirects itself, sanitizing URLs as necessary. Alternately, an
1155 app could leave CURLOPT_FOLLOWLOCATION enabled but set CURLOPT_REDIR_PROTOCOLS
1156 and install a CURLOPT_OPENSOCKETFUNCTION callback function in which addresses
1157 are sanitized before use.
1158
1159 .IP "Private Resources"
1160 A user who can control the DNS server of a domain being passed in within a URL
1161 can change the address of the host to a local, private address which a
1162 server-side libcurl-using application could then use. e.g. the innocuous URL
1163 http://fuzzybunnies.example.com/ could actually resolve to the IP address of a
1164 server behind a firewall, such as 127.0.0.1 or 10.1.2.3.  Apps can mitigate
1165 against this by setting a CURLOPT_OPENSOCKETFUNCTION and checking the address
1166 before a connection.
1167
1168 All the malicious scenarios regarding redirected URLs apply just as well
1169 to non-redirected URLs, if the user is allowed to specify an arbitrary URL
1170 that could point to a private resource. For example, a web app providing
1171 a translation service might happily translate file://localhost/etc/passwd
1172 and display the result.  Apps can mitigate against this with the
1173 CURLOPT_PROTOCOLS option as well as by similar mitigation techniques for
1174 redirections.
1175
1176 A malicious FTP server could in response to the PASV command return an
1177 IP address and port number for a server local to the app running libcurl
1178 but behind a firewall.  Apps can mitigate against this by using the
1179 CURLOPT_FTP_SKIP_PASV_IP option or CURLOPT_FTPPORT.
1180
1181 .IP "IPv6 Addresses"
1182 libcurl will normally handle IPv6 addresses transparently and just as easily
1183 as IPv4 addresses. That means that a sanitizing function that filters out
1184 addressses like 127.0.0.1 isn't sufficient--the equivalent IPv6 addresses ::1,
1185 ::, 0:00::0:1, ::127.0.0.1 and ::ffff:7f00:1 supplied somehow by an attacker
1186 would all bypass a naive filter and could allow access to undesired local
1187 resources.  IPv6 also has special address blocks like link-local and site-local
1188 that generally shouldn't be accessed by a server-side libcurl-using
1189 application.  A poorly-configured firewall installed in a data center,
1190 organization or server may also be configured to limit IPv4 connections but
1191 leave IPv6 connections wide open.  In some cases, the CURL_IPRESOLVE_V4 option
1192 can be used to limit resolved addresses to IPv4 only and bypass these issues.
1193
1194 .IP Uploads
1195 When uploading, a redirect can cause a local (or remote) file to be
1196 overwritten.  Apps must not allow any unsanitized URL to be passed in
1197 for uploads.  Also, CURLOPT_FOLLOWLOCATION should not be used on uploads.
1198 Instead, the app should handle redirects itself, sanitizing each URL first.
1199
1200 .IP Authentication
1201 Use of CURLOPT_UNRESTRICTED_AUTH could cause authentication information to
1202 be sent to an unknown second server.  Apps can mitigate against this
1203 by disabling CURLOPT_FOLLOWLOCATION and handling redirects itself,
1204 sanitizing where necessary.
1205
1206 Use of the CURLAUTH_ANY option to CURLOPT_HTTPAUTH could result in user
1207 name and password being sent in clear text to an HTTP server.  Instead,
1208 use CURLAUTH_ANYSAFE which ensures that the password is encrypted over
1209 the network, or else fail the request.
1210
1211 Use of the CURLUSESSL_TRY option to CURLOPT_USE_SSL could result in user
1212 name and password being sent in clear text to an FTP server.  Instead,
1213 use CURLUSESSL_CONTROL to ensure that an encrypted connection is used or
1214 else fail the request.
1215
1216 .IP Cookies
1217 If cookies are enabled and cached, then a user could craft a URL which
1218 performs some malicious action to a site whose authentication is already
1219 stored in a cookie. e.g. http://mail.example.com/delete-stuff.cgi?delete=all
1220 Apps can mitigate against this by disabling cookies or clearing them
1221 between requests.
1222
1223 .IP "Dangerous URLs"
1224 SCP URLs can contain raw commands within the scp: URL, which is a side effect
1225 of how the SCP protocol is designed. e.g.
1226 scp://user:pass@host/a;date >/tmp/test;
1227 Apps must not allow unsanitized SCP: URLs to be passed in for downloads.
1228
1229 .IP "Denial of Service"
1230 A malicious server could cause libcurl to effectively hang by sending
1231 a trickle of data through, or even no data at all but just keeping the TCP
1232 connection open.  This could result in a denial-of-service attack. The
1233 CURLOPT_TIMEOUT and/or CURLOPT_LOW_SPEED_LIMIT options can be used to
1234 mitigate against this.
1235
1236 A malicious server could cause libcurl to effectively hang by starting to
1237 send data, then severing the connection without cleanly closing the
1238 TCP connection.  The app could install a CURLOPT_SOCKOPTFUNCTION callback
1239 function and set the TCP SO_KEEPALIVE option to mitigate against this.
1240 Setting one of the timeout options would also work against this attack.
1241
1242 A malicious server could cause libcurl to download an infinite amount of
1243 data, potentially causing all of memory or disk to be filled. Setting
1244 the CURLOPT_MAXFILESIZE_LARGE option is not sufficient to guard against this.
1245 Instead, the app should monitor the amount of data received within the
1246 write or progress callback and abort once the limit is reached.
1247
1248 A malicious HTTP server could cause an infinite redirection loop, causing a
1249 denial-of-service. This can be mitigated by using the CURLOPT_MAXREDIRS
1250 option.
1251
1252 .IP "Arbitrary Headers"
1253 User-supplied data must be sanitized when used in options like
1254 CURLOPT_USERAGENT, CURLOPT_HTTPHEADER, CURLOPT_POSTFIELDS and others that
1255 are used to generate structured data. Characters like embedded carriage
1256 returns or ampersands could allow the user to create additional headers or
1257 fields that could cause malicious transactions.
1258
1259 .IP "Server-supplied Names"
1260 A server can supply data which the application may, in some cases, use as
1261 a file name. The curl command-line tool does this with --remote-header-name,
1262 using the Content-disposition: header to generate a file name.  An application
1263 could also use CURLINFO_EFFECTIVE_URL to generate a file name from a
1264 server-supplied redirect URL. Special care must be taken to sanitize such
1265 names to avoid the possibility of a malicious server supplying one like
1266 "/etc/passwd", "\\autoexec.bat", "prn:" or even ".bashrc".
1267
1268 .IP "Server Certificates"
1269 A secure application should never use the CURLOPT_SSL_VERIFYPEER option to
1270 disable certificate validation. There are numerous attacks that are enabled
1271 by apps that fail to properly validate server TLS/SSL certificates,
1272 thus enabling a malicious server to spoof a legitimate one. HTTPS without
1273 validated certificates is potentially as insecure as a plain HTTP connection.
1274
1275 .IP "Showing What You Do"
1276 On a related issue, be aware that even in situations like when you have
1277 problems with libcurl and ask someone for help, everything you reveal in order
1278 to get best possible help might also impose certain security related
1279 risks. Host names, user names, paths, operating system specifics, etc. (not to
1280 mention passwords of course) may in fact be used by intruders to gain
1281 additional information of a potential target.
1282
1283 Be sure to limit access to application logs if they could hold private or
1284 security-related data.  Besides the obvious candidates like user names and
1285 passwords, things like URLs, cookies or even file names could also hold
1286 sensitive data.
1287
1288 To avoid this problem, you must of course use your common sense. Often, you
1289 can just edit out the sensitive data or just search/replace your true
1290 information with faked data.
1291
1292 .SH "Multiple Transfers Using the multi Interface"
1293
1294 The easy interface as described in detail in this document is a synchronous
1295 interface that transfers one file at a time and doesn't return until it is
1296 done.
1297
1298 The multi interface, on the other hand, allows your program to transfer
1299 multiple files in both directions at the same time, without forcing you
1300 to use multiple threads.  The name might make it seem that the multi
1301 interface is for multi-threaded programs, but the truth is almost the
1302 reverse.  The multi interface can allow a single-threaded application
1303 to perform the same kinds of multiple, simultaneous transfers that
1304 multi-threaded programs can perform.  It allows many of the benefits
1305 of multi-threaded transfers without the complexity of managing and
1306 synchronizing many threads.
1307
1308 To use this interface, you are better off if you first understand the basics
1309 of how to use the easy interface. The multi interface is simply a way to make
1310 multiple transfers at the same time by adding up multiple easy handles into
1311 a "multi stack".
1312
1313 You create the easy handles you want and you set all the options just like you
1314 have been told above, and then you create a multi handle with
1315 \fIcurl_multi_init(3)\fP and add all those easy handles to that multi handle
1316 with \fIcurl_multi_add_handle(3)\fP.
1317
1318 When you've added the handles you have for the moment (you can still add new
1319 ones at any time), you start the transfers by calling
1320 \fIcurl_multi_perform(3)\fP.
1321
1322 \fIcurl_multi_perform(3)\fP is asynchronous. It will only execute as little as
1323 possible and then return back control to your program. It is designed to never
1324 block.
1325
1326 The best usage of this interface is when you do a select() on all possible
1327 file descriptors or sockets to know when to call libcurl again. This also
1328 makes it easy for you to wait and respond to actions on your own application's
1329 sockets/handles. You figure out what to select() for by using
1330 \fIcurl_multi_fdset(3)\fP, that fills in a set of fd_set variables for you
1331 with the particular file descriptors libcurl uses for the moment.
1332
1333 When you then call select(), it'll return when one of the file handles signal
1334 action and you then call \fIcurl_multi_perform(3)\fP to allow libcurl to do
1335 what it wants to do. Take note that libcurl does also feature some time-out
1336 code so we advise you to never use very long timeouts on select() before you
1337 call \fIcurl_multi_perform(3)\fP, which thus should be called unconditionally
1338 every now and then even if none of its file descriptors have signaled
1339 ready. Another precaution you should use: always call
1340 \fIcurl_multi_fdset(3)\fP immediately before the select() call since the
1341 current set of file descriptors may change when calling a curl function.
1342
1343 If you want to stop the transfer of one of the easy handles in the stack, you
1344 can use \fIcurl_multi_remove_handle(3)\fP to remove individual easy
1345 handles. Remember that easy handles should be \fIcurl_easy_cleanup(3)\fPed.
1346
1347 When a transfer within the multi stack has finished, the counter of running
1348 transfers (as filled in by \fIcurl_multi_perform(3)\fP) will decrease. When
1349 the number reaches zero, all transfers are done.
1350
1351 \fIcurl_multi_info_read(3)\fP can be used to get information about completed
1352 transfers. It then returns the CURLcode for each easy transfer, to allow you
1353 to figure out success on each individual transfer.
1354
1355 .SH "SSL, Certificates and Other Tricks"
1356
1357  [ seeding, passwords, keys, certificates, ENGINE, ca certs ]
1358
1359 .SH "Sharing Data Between Easy Handles"
1360 You can share some data between easy handles when the easy interface is used,
1361 and some data is share automatically when you use the multi interface.
1362
1363 When you add easy handles to a multi handle, these easy handles will
1364 automatically share a lot of the data that otherwise would be kept on a
1365 per-easy handle basis when the easy interface is used.
1366
1367 The DNS cache is shared between handles within a multi handle, making
1368 subsequent name resolving faster, and the connection pool that is kept to
1369 better allow persistent connections and connection re-use is also shared. If
1370 you're using the easy interface, you can still share these between specific
1371 easy handles by using the share interface, see \fIlibcurl-share(3)\fP.
1372
1373 Some things are never shared automatically, not within multi handles, like for
1374 example cookies so the only way to share that is with the share interface.
1375 .SH "Footnotes"
1376
1377 .IP "[1]"
1378 libcurl 7.10.3 and later have the ability to switch over to chunked
1379 Transfer-Encoding in cases where HTTP uploads are done with data of an unknown
1380 size.
1381 .IP "[2]"
1382 This happens on Windows machines when libcurl is built and used as a
1383 DLL. However, you can still do this on Windows if you link with a static
1384 library.
1385 .IP "[3]"
1386 The curl-config tool is generated at build-time (on UNIX-like systems) and
1387 should be installed with the 'make install' or similar instruction that
1388 installs the library, header files, man pages etc.
1389 .IP "[4]"
1390 This behavior was different in versions before 7.17.0, where strings had to
1391 remain valid past the end of the \fIcurl_easy_setopt(3)\fP call.