]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/curl/docs/libcurl-the-guide
hello world
[icculus/iodoom3.git] / neo / curl / docs / libcurl-the-guide
1 $Id: libcurl-the-guide,v 1.23 2004/01/29 16:17:25 bagder Exp $
2                                   _   _ ____  _     
3                               ___| | | |  _ \| |    
4                              / __| | | | |_) | |    
5                             | (__| |_| |  _ <| |___ 
6                              \___|\___/|_| \_\_____|
7
8 PROGRAMMING WITH LIBCURL
9
10 About this Document
11
12  This document attempts to describe the general principles and some basic
13  approaches to consider when programming with libcurl. The text will focus
14  mainly on the C interface but might apply fairly well on other interfaces as
15  well as they usually follow the C one pretty closely.
16
17  This document will refer to 'the user' as the person writing the source code
18  that uses libcurl. That would probably be you or someone in your position.
19  What will be generally refered to as 'the program' will be the collected
20  source code that you write that is using libcurl for transfers. The program
21  is outside libcurl and libcurl is outside of the program.
22
23  To get the more details on all options and functions described herein, please
24  refer to their respective man pages.
25
26 Building
27
28  There are many different ways to build C programs. This chapter will assume a
29  unix-style build process. If you use a different build system, you can still
30  read this to get general information that may apply to your environment as
31  well.
32
33   Compiling the Program
34
35     Your compiler needs to know where the libcurl headers are
36     located. Therefore you must set your compiler's include path to point to
37     the directory where you installed them. The 'curl-config'[3] tool can be
38     used to get this information:
39
40         $ curl-config --cflags
41
42   Linking the Program with libcurl
43
44     When having compiled the program, you need to link your object files to
45     create a single executable. For that to succeed, you need to link with
46     libcurl and possibly also with other libraries that libcurl itself depends
47     on. Like OpenSSL librararies, but even some standard OS libraries may be
48     needed on the command line. To figure out which flags to use, once again
49     the 'curl-config' tool comes to the rescue:
50
51         $ curl-config --libs
52
53   SSL or Not
54
55     libcurl can be built and customized in many ways. One of the things that
56     varies from different libraries and builds is the support for SSL-based
57     transfers, like HTTPS and FTPS. If OpenSSL was detected properly at
58     build-time, libcurl will be built with SSL support. To figure out if an
59     installed libcurl has been built with SSL support enabled, use
60     'curl-config' like this:
61
62         $ curl-config --feature
63
64     And if SSL is supported, the keyword 'SSL' will be written to stdout,
65     possibly together with a few other features that can be on and off on
66     different libcurls.
67
68
69 Portable Code in a Portable World
70
71  The people behind libcurl have put a considerable effort to make libcurl work
72  on a large amount of different operating systems and environments.
73
74  You program libcurl the same way on all platforms that libcurl runs on. There
75  are only very few minor considerations that differs. If you just make sure to
76  write your code portable enough, you may very well create yourself a very
77  portable program. libcurl shouldn't stop you from that.
78
79
80 Global Preparation
81
82  The program must initialize some of the libcurl functionality globally. That
83  means it should be done exactly once, no matter how many times you intend to
84  use the library. Once for your program's entire life time. This is done using
85
86     curl_global_init()
87
88  and it takes one parameter which is a bit pattern that tells libcurl what to
89  intialize. Using CURL_GLOBAL_ALL will make it initialize all known internal
90  sub modules, and might be a good default option. The current two bits that
91  are specified are:
92
93   CURL_GLOBAL_WIN32 which only does anything on Windows machines. When used on
94   a Windows machine, it'll make libcurl intialize the win32 socket
95   stuff. Without having that initialized properly, your program cannot use
96   sockets properly. You should only do this once for each application, so if
97   your program already does this or of another library in use does it, you
98   should not tell libcurl to do this as well.
99
100   CURL_GLOBAL_SSL which only does anything on libcurls compiled and built
101   SSL-enabled. On these systems, this will make libcurl init OpenSSL properly
102   for this application. This is only needed to do once for each application so
103   if your program or another library already does this, this bit should not be
104   needed.
105
106  libcurl has a default protection mechanism that detects if curl_global_init()
107  hasn't been called by the time curl_easy_perform() is called and if that is
108  the case, libcurl runs the function itself with a guessed bit pattern. Please
109  note that depending solely on this is not considered nice nor very good.
110
111  When the program no longer uses libcurl, it should call
112  curl_global_cleanup(), which is the opposite of the init call. It will then
113  do the reversed operations to cleanup the resources the curl_global_init()
114  call initialized.
115
116  Repeated calls to curl_global_init() and curl_global_cleanup() should be
117  avoided. They should only be called once each.
118
119
120 Handle the Easy libcurl
121
122  libcurl version 7 is oriented around the so called easy interface. All
123  operations in the easy interface are prefixed with 'curl_easy'.
124
125  Future libcurls will also offer the multi interface. More about that
126  interface, what it is targeted for and how to use it is still only debated on
127  the libcurl mailing list and developer web pages. Join up to discuss and
128  figure out!
129
130  To use the easy interface, you must first create yourself an easy handle. You
131  need one handle for each easy session you want to perform. Basicly, you
132  should use one handle for every thread you plan to use for transferring. You
133  must never share the same handle in multiple threads.
134
135  Get an easy handle with
136
137     easyhandle = curl_easy_init();
138
139  It returns an easy handle. Using that you proceed to the next step: setting
140  up your preferred actions. A handle is just a logic entity for the upcoming
141  transfer or series of transfers.
142
143  You set properties and options for this handle using curl_easy_setopt(). They
144  control how the subsequent transfer or transfers will be made. Options remain
145  set in the handle until set again to something different. Alas, multiple
146  requests using the same handle will use the same options.
147
148  Many of the informationals you set in libcurl are "strings", pointers to data
149  terminated with a zero byte. Keep in mind that when you set strings with
150  curl_easy_setopt(), libcurl will not copy the data. It will merely point to
151  the data. You MUST make sure that the data remains available for libcurl to
152  use until finished or until you use the same option again to point to
153  something else.
154
155  One of the most basic properties to set in the handle is the URL. You set
156  your preferred URL to transfer with CURLOPT_URL in a manner similar to:
157
158     curl_easy_setopt(easyhandle, CURLOPT_URL, "http://curl.haxx.se/");
159
160  Let's assume for a while that you want to receive data as the URL indentifies
161  a remote resource you want to get here. Since you write a sort of application
162  that needs this transfer, I assume that you would like to get the data passed
163  to you directly instead of simply getting it passed to stdout. So, you write
164  your own function that matches this prototype:
165
166     size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);
167
168  You tell libcurl to pass all data to this function by issuing a function
169  similar to this:
170
171     curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, write_data);
172
173  You can control what data your function get in the forth argument by setting
174  another property:
175
176     curl_easy_setopt(easyhandle, CURLOPT_FILE, &internal_struct);
177
178  Using that property, you can easily pass local data between your application
179  and the function that gets invoked by libcurl. libcurl itself won't touch the
180  data you pass with CURLOPT_FILE.
181
182  libcurl offers its own default internal callback that'll take care of the
183  data if you don't set the callback with CURLOPT_WRITEFUNCTION. It will then
184  simply output the received data to stdout. You can have the default callback
185  write the data to a different file handle by passing a 'FILE *' to a file
186  opened for writing with the CURLOPT_FILE option.
187
188  Now, we need to take a step back and have a deep breath. Here's one of those
189  rare platform-dependent nitpicks. Did you spot it? On some platforms[2],
190  libcurl won't be able to operate on files opened by the program. Thus, if you
191  use the default callback and pass in a an open file with CURLOPT_FILE, it
192  will crash. You should therefore avoid this to make your program run fine
193  virtually everywhere.
194
195  There are of course many more options you can set, and we'll get back to a
196  few of them later. Let's instead continue to the actual transfer:
197
198     success = curl_easy_perform(easyhandle);
199
200  The curl_easy_perform() will connect to the remote site, do the necessary
201  commands and receive the transfer. Whenever it receives data, it calls the
202  callback function we previously set. The function may get one byte at a time,
203  or it may get many kilobytes at once. libcurl delivers as much as possible as
204  often as possible. Your callback function should return the number of bytes
205  it "took care of". If that is not the exact same amount of bytes that was
206  passed to it, libcurl will abort the operation and return with an error code.
207
208  When the transfer is complete, the function returns a return code that
209  informs you if it succeeded in its mission or not. If a return code isn't
210  enough for you, you can use the CURLOPT_ERRORBUFFER to point libcurl to a
211  buffer of yours where it'll store a human readable error message as well.
212
213  If you then want to transfer another file, the handle is ready to be used
214  again. Mind you, it is even preferred that you re-use an existing handle if
215  you intend to make another transfer. libcurl will then attempt to re-use the
216  previous
217
218
219 Multi-threading issues
220
221  libcurl is completely thread safe, except for two issues: signals and alarm
222  handlers. Signals are needed for a SIGPIPE handler, and the alarm() syscall
223  is used to catch timeouts (mostly during DNS lookup).
224
225  If you are accessing HTTPS or FTPS URLs in a multi-threaded manner, you are
226  then of course using OpenSSL multi-threaded and it has itself a few
227  requirements on this. Basicly, you need to provide one or two functions to
228  allow it to function properly. For all details, see this:
229
230    http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION
231
232  When using multiple threads you should first ignore SIGPIPE in your main
233  thread and set the CURLOPT_NOSIGNAL option to TRUE for all handles.
234
235  Everything will work fine except that timeouts are not honored during the DNS
236  lookup - which you can work around by building libcurl with ares-support.
237  Ares is a library that provides asynchronous name resolves. Unfortunately,
238  ares does not yet support IPv6.
239
240  For SIGPIPE info see the UNIX Socket FAQ at
241  http://www.unixguide.net/network/socketfaq/2.22.shtml
242
243  Also, note that CURLOPT_DNS_USE_GLOBAL_CACHE is not thread-safe.
244
245 When It Doesn't Work
246
247  There will always be times when the transfer fails for some reason. You might
248  have set the wrong libcurl option or misunderstood what the libcurl option
249  actually does, or the remote server might return non-standard replies that
250  confuse the library which then confuses your program.
251
252  There's one golden rule when these things occur: set the CURLOPT_VERBOSE
253  option to TRUE. It'll cause the library to spew out the entire protocol
254  details it sends, some internal info and some received protcol data as well
255  (especially when using FTP). If you're using HTTP, adding the headers in the
256  received output to study is also a clever way to get a better understanding
257  wht the server behaves the way it does. Include headers in the normal body
258  output with CURLOPT_HEADER set TRUE.
259
260  Of course there are bugs left. We need to get to know about them to be able
261  to fix them, so we're quite dependent on your bug reports! When you do report
262  suspected bugs in libcurl, please include as much details you possibly can: a
263  protocol dump that CURLOPT_VERBOSE produces, library version, as much as
264  possible of your code that uses libcurl, operating system name and version,
265  compiler name and version etc.
266
267  If CURLOPT_VERBOSE is not enough, you increase the level of debug data your
268  application receive by using the CURLOPT_DEBUGFUNCTION.
269
270  Getting some in-depth knowledge about the protocols involved is never wrong,
271  and if you're trying to do funny things, you might very well understand
272  libcurl and how to use it better if you study the appropriate RFC documents
273  at least briefly.
274
275
276 Upload Data to a Remote Site
277
278  libcurl tries to keep a protocol independent approach to most transfers, thus
279  uploading to a remote FTP site is very similar to uploading data to a HTTP
280  server with a PUT request.
281
282  Of course, first you either create an easy handle or you re-use one existing
283  one. Then you set the URL to operate on just like before. This is the remote
284  URL, that we now will upload.
285
286  Since we write an application, we most likely want libcurl to get the upload
287  data by asking us for it. To make it do that, we set the read callback and
288  the custom pointer libcurl will pass to our read callback. The read callback
289  should have a prototype similar to:
290
291     size_t function(char *bufptr, size_t size, size_t nitems, void *userp);
292
293  Where bufptr is the pointer to a buffer we fill in with data to upload and
294  size*nitems is the size of the buffer and therefore also the maximum amount
295  of data we can return to libcurl in this call. The 'userp' pointer is the
296  custom pointer we set to point to a struct of ours to pass private data
297  between the application and the callback.
298
299     curl_easy_setopt(easyhandle, CURLOPT_READFUNCTION, read_function);
300
301     curl_easy_setopt(easyhandle, CURLOPT_INFILE, &filedata);
302
303  Tell libcurl that we want to upload:
304
305     curl_easy_setopt(easyhandle, CURLOPT_UPLOAD, TRUE);
306
307  A few protocols won't behave properly when uploads are done without any prior
308  knowledge of the expected file size. So, set the upload file size using the
309  CURLOPT_INFILESIZE_LARGE for all known file sizes like this[1]:
310
311     /* in this example, file_size must be an off_t variable */
312     curl_easy_setopt(easyhandle, CURLOPT_INFILESIZE_LARGE, file_size);
313
314  When you call curl_easy_perform() this time, it'll perform all the necessary
315  operations and when it has invoked the upload it'll call your supplied
316  callback to get the data to upload. The program should return as much data as
317  possible in every invoke, as that is likely to make the upload perform as
318  fast as possible. The callback should return the number of bytes it wrote in
319  the buffer. Returning 0 will signal the end of the upload.
320
321
322 Passwords
323
324  Many protocols use or even require that user name and password are provided
325  to be able to download or upload the data of your choice. libcurl offers
326  several ways to specify them.
327
328  Most protocols support that you specify the name and password in the URL
329  itself. libcurl will detect this and use them accordingly. This is written
330  like this:
331
332         protocol://user:password@example.com/path/
333
334  If you need any odd letters in your user name or password, you should enter
335  them URL encoded, as %XX where XX is a two-digit hexadecimal number.
336
337  libcurl also provides options to set various passwords. The user name and
338  password as shown embedded in the URL can instead get set with the
339  CURLOPT_USERPWD option. The argument passed to libcurl should be a char * to
340  a string in the format "user:password:". In a manner like this:
341
342         curl_easy_setopt(easyhandle, CURLOPT_USERPWD, "myname:thesecret");
343
344  Another case where name and password might be needed at times, is for those
345  users who need to athenticate themselves to a proxy they use. libcurl offers
346  another option for this, the CURLOPT_PROXYUSERPWD. It is used quite similar
347  to the CURLOPT_USERPWD option like this:
348
349         curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "myname:thesecret");
350  
351  There's a long time unix "standard" way of storing ftp user names and
352  passwords, namely in the $HOME/.netrc file. The file should be made private
353  so that only the user may read it (see also the "Security Considerations"
354  chapter), as it might contain the password in plain text. libcurl has the
355  ability to use this file to figure out what set of user name and password to
356  use for a particular host. As an extension to the normal functionality,
357  libcurl also supports this file for non-FTP protocols such as HTTP. To make
358  curl use this file, use the CURLOPT_NETRC option:
359
360     curl_easy_setopt(easyhandle, CURLOPT_NETRC, TRUE);
361
362  And a very basic example of how such a .netrc file may look like:
363
364     machine myhost.mydomain.com
365     login userlogin
366     password secretword
367
368  All these examples have been cases where the password has been optional, or
369  at least you could leave it out and have libcurl attempt to do its job
370  without it. There are times when the password isn't optional, like when
371  you're using an SSL private key for secure transfers.
372
373  To pass the known private key password to libcurl:
374
375     curl_easy_setopt(easyhandle, CURLOPT_SSLKEYPASSWD, "keypassword");
376
377
378 HTTP Authentication
379
380  The previous chapter showed how to set user name and password for getting
381  URLs that require authentication. When using the HTTP protocol, there are
382  many different ways a client can provide those credentials to the server and
383  you can control what way libcurl will (attempt to) use. The default HTTP
384  authentication method is called 'Basic', which is sending the name and
385  password in clear-text in the HTTP request, base64-encoded. This is unsecure.
386
387  At the time of this writing libcurl can be built to use: Basic, Digest, NTLM,
388  Negotiate, GSS-Negotiate and SPNEGO. You can tell libcurl which one to use
389  with CURLOPT_HTTPAUTH as in:
390
391     curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
392
393  And when you send authentication to a proxy, you can also set authentication
394  type the same way but instead with CURLOPT_PROXYAUTH:
395
396     curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
397
398  Both these options allow you to set multiple types (by ORing them together),
399  to make libcurl pick the most secure one out of the types the server/proxy
400  claims to support. This method does however add a round-trip since libcurl
401  must first ask the server what it supports:
402
403     curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH,
404                                  CURLAUTH_DIGEST|CURLAUTH_BASIC);
405
406  For convenience, you can use the 'CURLAUTH_ANY' define (instead of a list
407  with specific types) which allows libcurl to use whatever method it wants.
408
409  When asking for multiple types, libcurl will pick the available one it
410  considers "best" in its own internal order of preference.
411
412
413 HTTP POSTing
414
415  We get many questions regarding how to issue HTTP POSTs with libcurl the
416  proper way. This chapter will thus include examples using both different
417  versions of HTTP POST that libcurl supports.
418
419  The first version is the simple POST, the most common version, that most HTML
420  pages using the <form> tag uses. We provide a pointer to the data and tell
421  libcurl to post it all to the remote site:
422
423     char *data="name=daniel&project=curl";
424     curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, data);
425     curl_easy_setopt(easyhandle, CURLOPT_URL, "http://posthere.com/");
426
427     curl_easy_perform(easyhandle); /* post away! */
428
429  Simple enough, huh? Since you set the POST options with the
430  CURLOPT_POSTFIELDS, this automaticly switches the handle to use POST in the
431  upcoming request.
432
433  Ok, so what if you want to post binary data that also requires you to set the
434  Content-Type: header of the post? Well, binary posts prevents libcurl from
435  being able to do strlen() on the data to figure out the size, so therefore we
436  must tell libcurl the size of the post data. Setting headers in libcurl
437  requests are done in a generic way, by building a list of our own headers and
438  then passing that list to libcurl.
439
440     struct curl_slist *headers=NULL;
441     headers = curl_slist_append(headers, "Content-Type: text/xml");
442
443     /* post binary data */
444     curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, binaryptr);
445
446     /* set the size of the postfields data */
447     curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDSIZE, 23);
448
449     /* pass our list of custom made headers */
450     curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);
451
452     curl_easy_perform(easyhandle); /* post away! */
453
454     curl_slist_free_all(headers); /* free the header list */
455
456  While the simple examples above cover the majority of all cases where HTTP
457  POST operations are required, they don't do multipart formposts. Multipart
458  formposts were introduced as a better way to post (possibly large) binary
459  data and was first documented in the RFC1867. They're called multipart
460  because they're built by a chain of parts, each being a single unit. Each
461  part has its own name and contents. You can in fact create and post a
462  multipart formpost with the regular libcurl POST support described above, but
463  that would require that you build a formpost yourself and provide to
464  libcurl. To make that easier, libcurl provides curl_formadd(). Using this
465  function, you add parts to the form. When you're done adding parts, you post
466  the whole form.
467
468  The following example sets two simple text parts with plain textual contents,
469  and then a file with binary contents and upload the whole thing.
470
471     struct curl_httppost *post=NULL;
472     struct curl_httppost *last=NULL;
473     curl_formadd(&post, &last,
474                  CURLFORM_COPYNAME, "name",
475                  CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END);
476     curl_formadd(&post, &last,
477                  CURLFORM_COPYNAME, "project",
478                  CURLFORM_COPYCONTENTS, "curl", CURLFORM_END);
479     curl_formadd(&post, &last,
480                  CURLFORM_COPYNAME, "logotype-image",
481                  CURLFORM_FILECONTENT, "curl.png", CURLFORM_END);
482
483     /* Set the form info */
484     curl_easy_setopt(easyhandle, CURLOPT_HTTPPOST, post);
485
486     curl_easy_perform(easyhandle); /* post away! */
487
488     /* free the post data again */
489     curl_formfree(post);
490
491  Multipart formposts are chains of parts using MIME-style separators and
492  headers. It means that each one of these separate parts get a few headers set
493  that describe the individual content-type, size etc. To enable your
494  application to handicraft this formpost even more, libcurl allows you to
495  supply your own set of custom headers to such an individual form part. You
496  can of course supply headers to as many parts you like, but this little
497  example will show how you set headers to one specific part when you add that
498  to the post handle:
499
500     struct curl_slist *headers=NULL;
501     headers = curl_slist_append(headers, "Content-Type: text/xml");
502
503     curl_formadd(&post, &last,
504                  CURLFORM_COPYNAME, "logotype-image",
505                  CURLFORM_FILECONTENT, "curl.xml",
506                  CURLFORM_CONTENTHEADER, headers,
507                  CURLFORM_END);
508
509     curl_easy_perform(easyhandle); /* post away! */
510
511     curl_formfree(post); /* free post */
512     curl_slist_free_all(post); /* free custom header list */
513
514  Since all options on an easyhandle are "sticky", they remain the same until
515  changed even if you do call curl_easy_perform(), you may need to tell curl to
516  go back to a plain GET request if you intend to do such a one as your next
517  request. You force an easyhandle to back to GET by using the CURLOPT_HTTPGET
518  option:
519
520     curl_easy_setopt(easyhandle, CURLOPT_HTTPGET, TRUE);
521
522  Just setting CURLOPT_POSTFIELDS to "" or NULL will *not* stop libcurl from
523  doing a POST. It will just make it POST without any data to send!
524
525
526 Showing Progress
527
528  For historical and traditional reasons, libcurl has a built-in progress meter
529  that can be switched on and then makes it presents a progress meter in your
530  terminal.
531
532  Switch on the progress meter by, oddly enough, set CURLOPT_NOPROGRESS to
533  FALSE. This option is set to TRUE by default.
534
535  For most applications however, the built-in progress meter is useless and
536  what instead is interesting is the ability to specify a progress
537  callback. The function pointer you pass to libcurl will then be called on
538  irregular intervals with information about the current transfer.
539
540  Set the progress callback by using CURLOPT_PROGRESSFUNCTION. And pass a
541  pointer to a function that matches this prototype:
542
543         int progress_callback(void *clientp,
544                               double dltotal,
545                               double dlnow,
546                               double ultotal,
547                               double ulnow);
548
549  If any of the input arguments is unknown, a 0 will be passed. The first
550  argument, the 'clientp' is the pointer you pass to libcurl with
551  CURLOPT_PROGRESSDATA. libcurl won't touch it.
552
553
554 libcurl with C++
555
556  There's basicly only one thing to keep in mind when using C++ instead of C
557  when interfacing libcurl:
558
559     "The Callbacks Must Be Plain C"
560
561  So if you want a write callback set in libcurl, you should put it within
562  'extern'. Similar to this:
563
564      extern "C" {
565        size_t write_data(void *ptr, size_t size, size_t nmemb,
566                          void *ourpointer)
567        {
568          /* do what you want with the data */
569        }
570     }
571
572  This will of course effectively turn the callback code into C. There won't be
573  any "this" pointer available etc.
574
575
576 Proxies
577
578  What "proxy" means according to Merriam-Webster: "a person authorized to act
579  for another" but also "the agency, function, or office of a deputy who acts
580  as a substitute for another".
581
582  Proxies are exceedingly common these days. Companies often only offer
583  internet access to employees through their HTTP proxies. Network clients or
584  user-agents ask the proxy for docuements, the proxy does the actual request
585  and then it returns them.
586
587  libcurl has full support for HTTP proxies, so when a given URL is wanted,
588  libcurl will ask the proxy for it instead of trying to connect to the actual
589  host identified in the URL.
590
591  The fact that the proxy is a HTTP proxy puts certain restrictions on what can
592  actually happen. A requested URL that might not be a HTTP URL will be still
593  be passed to the HTTP proxy to deliver back to libcurl. This happens
594  transparantly, and an application may not need to know. I say "may", because
595  at times it is very important to understand that all operations over a HTTP
596  proxy is using the HTTP protocol. For example, you can't invoke your own
597  custom FTP commands or even proper FTP directory listings.
598
599   Proxy Options
600
601     To tell libcurl to use a proxy at a given port number:
602
603        curl_easy_setopt(easyhandle, CURLOPT_PROXY, "proxy-host.com:8080");
604
605     Some proxies require user authentication before allowing a request, and
606     you pass that information similar to this:
607
608        curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, "user:password");
609
610     If you want to, you can specify the host name only in the CURLOPT_PROXY
611     option, and set the port number separately with CURLOPT_PROXYPORT.
612
613   Environment Variables
614
615     libcurl automaticly checks and uses a set of environment variables to know
616     what proxies to use for certain protocols. The names of the variables are
617     following an ancient de facto standard and are built up as
618     "[protocol]_proxy" (note the lower casing). Which makes the variable
619     'http_proxy' checked for a name of a proxy to use when the input URL is
620     HTTP. Following the same rule, the variable named 'ftp_proxy' is checked
621     for FTP URLs. Again, the proxies are always HTTP proxies, the different
622     names of the variables simply allows different HTTP proxies to be used.
623
624     The proxy environment variable contents should be in the format
625     "[protocol://]machine[:port]". Where the protocol:// part is simply
626     ignored if present (so http://proxy and bluerk://proxy will do the same)
627     and the optional port number specifies on which port the proxy operates on
628     the host. If not specified, the internal default port number will be used
629     and that is most likely *not* the one you would like it to be.
630
631     There are two special environment variables. 'all_proxy' is what sets
632     proxy for any URL in case the protocol specific variable wasn't set, and
633     'no_proxy' defines a list of hosts that should not use a proxy even though
634     a variable may say so. If 'no_proxy' is a plain asterisk ("*") it matches
635     all hosts.
636
637   SSL and Proxies
638
639     SSL is for secure point-to-point connections. This involves strong
640     encryption and similar things, which effectivly makes it impossible for a
641     proxy to operate as a "man in between" which the proxy's task is, as
642     previously discussed. Instead, the only way to have SSL work over a HTTP
643     proxy is to ask the proxy to tunnel trough everything without being able
644     to check or fiddle with the traffic.
645
646     Opening an SSL connection over a HTTP proxy is therefor a matter of asking
647     the proxy for a straight connection to the target host on a specified
648     port. This is made with the HTTP request CONNECT. ("please mr proxy,
649     connect me to that remote host").
650
651     Because of the nature of this operation, where the proxy has no idea what
652     kind of data that is passed in and out through this tunnel, this breaks
653     some of the very few advantages that come from using a proxy, such as
654     caching.  Many organizations prevent this kind of tunneling to other
655     destination port numbers than 443 (which is the default HTTPS port
656     number).
657
658   Tunneling Through Proxy
659
660     As explained above, tunneling is required for SSL to work and often even
661     restricted to the operation intended for SSL; HTTPS.
662
663     This is however not the only time proxy-tunneling might offer benefits to
664     you or your application.
665
666     As tunneling opens a direct connection from your application to the remote
667     machine, it suddenly also re-introduces the ability to do non-HTTP
668     operations over a HTTP proxy. You can in fact use things such as FTP
669     upload or FTP custom commands this way.
670
671     Again, this is often prevented by the adminstrators of proxies and is
672     rarely allowed.
673
674     Tell libcurl to use proxy tunneling like this:
675
676        curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, TRUE);
677
678     In fact, there might even be times when you want to do plain HTTP
679     operations using a tunnel like this, as it then enables you to operate on
680     the remote server instead of asking the proxy to do so. libcurl will not
681     stand in the way for such innovative actions either!
682
683   Proxy Auto-Config
684
685     Netscape first came up with this. It is basicly a web page (usually using
686     a .pac extension) with a javascript that when executed by the browser with
687     the requested URL as input, returns information to the browser on how to
688     connect to the URL. The returned information might be "DIRECT" (which
689     means no proxy should be used), "PROXY host:port" (to tell the browser
690     where the proxy for this particular URL is) or "SOCKS host:port" (to
691     direct the brower to a SOCKS proxy).
692
693     libcurl has no means to interpret or evaluate javascript and thus it
694     doesn't support this. If you get yourself in a position where you face
695     this nasty invention, the following advice have been mentioned and used in
696     the past:
697
698     - Depending on the javascript complexity, write up a script that
699       translates it to another language and execute that.
700
701     - Read the javascript code and rewrite the same logic in another language.
702
703     - Implement a javascript interpreted, people have successfully used the
704       Mozilla javascript engine in the past.
705
706     - Ask your admins to stop this, for a static proxy setup or similar.
707
708
709 Persistancy Is The Way to Happiness
710
711  Re-cycling the same easy handle several times when doing multiple requests is
712  the way to go.
713
714  After each single curl_easy_perform() operation, libcurl will keep the
715  connection alive and open. A subsequent request using the same easy handle to
716  the same host might just be able to use the already open connection! This
717  reduces network impact a lot.
718
719  Even if the connection is dropped, all connections involving SSL to the same
720  host again, will benefit from libcurl's session ID cache that drasticly
721  reduces re-connection time.
722
723  FTP connections that are kept alive saves a lot of time, as the command-
724  response roundtrips are skipped, and also you don't risk getting blocked
725  without permission to login again like on many FTP servers only allowing N
726  persons to be logged in at the same time.
727
728  libcurl caches DNS name resolving results, to make lookups of a previously
729  looked up name a lot faster.
730
731  Other interesting details that improve performance for subsequent requests
732  may also be added in the future.
733
734  Each easy handle will attempt to keep the last few connections alive for a
735  while in case they are to be used again. You can set the size of this "cache"
736  with the CURLOPT_MAXCONNECTS option. Default is 5. It is very seldom any
737  point in changing this value, and if you think of changing this it is often
738  just a matter of thinking again.
739
740  When the connection cache gets filled, libcurl must close an existing
741  connection in order to get room for the new one. To know which connection to
742  close, libcurl uses a "close policy" that you can affect with the
743  CURLOPT_CLOSEPOLICY option. There's only two polices implemented as of this
744  writing (libcurl 7.9.4) and they are:
745
746   CURLCLOSEPOLICY_LEAST_RECENTLY_USED simply close the one that hasn't been
747   used for the longest time. This is the default behavior.
748
749   CURLCLOSEPOLICY_OLDEST closes the oldest connection, the one that was
750   createst the longest time ago.
751
752  There are, or at least were, plans to support a close policy that would call
753  a user-specified callback to let the user be able to decide which connection
754  to dump when this is necessary and therefor is the CURLOPT_CLOSEFUNCTION an
755  existing option still today. Nothing ever uses this though and this will not
756  be used within the forseeable future either.
757
758  To force your upcoming request to not use an already existing connection (it
759  will even close one first if there happens to be one alive to the same host
760  you're about to operate on), you can do that by setting CURLOPT_FRESH_CONNECT
761  to TRUE. In a similar spirit, you can also forbid the upcoming request to be
762  "lying" around and possibly get re-used after the request by setting
763  CURLOPT_FORBID_REUSE to TRUE.
764
765
766 HTTP Headers Used by libcurl
767
768  When you use libcurl to do HTTP requeests, it'll pass along a series of
769  headers automaticly. It might be good for you to know and understand these
770  ones.
771
772   Host
773
774     This header is required by HTTP 1.1 and even many 1.0 servers and should
775     be the name of the server we want to talk to. This includes the port
776     number if anything but default.
777
778   Pragma
779
780     "no-cache". Tells a possible proxy to not grap a copy from the cache but
781     to fetch a fresh one.
782
783   Accept:
784
785     "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*". Cloned from a
786     browser once a hundred years ago.
787
788   Expect:
789
790     When doing multi-part formposts, libcurl will set this header to
791     "100-continue" to ask the server for an "OK" message before it proceeds
792     with sending the data part of the post.
793
794
795 Customizing Operations
796
797  There is an ongoing development today where more and more protocols are built
798  upon HTTP for transport. This has obvious benefits as HTTP is a tested and
799  reliable protocol that is widely deployed and have excellent proxy-support.
800
801  When you use one of these protocols, and even when doing other kinds of
802  programming you may need to change the traditional HTTP (or FTP or...)
803  manners. You may need to change words, headers or various data.
804
805  libcurl is your friend here too.
806
807   CUSTOMREQUEST
808
809     If just changing the actual HTTP request keyword is what you want, like
810     when GET, HEAD or POST is not good enough for you, CURLOPT_CUSTOMREQUEST
811     is there for you. It is very simple to use:
812
813        curl_easy_setopt(easyhandle, CURLOPT_CUSTOMREQUEST, "MYOWNRUQUEST");
814
815     When using the custom request, you change the request keyword of the
816     actual request you are performing. Thus, by default you make GET request
817     but you can also make a POST operation (as described before) and then
818     replace the POST keyword if you want to. You're the boss.
819
820   Modify Headers
821
822     HTTP-like protocols pass a series of headers to the server when doing the
823     request, and you're free to pass any amount of extra headers that you
824     think fit. Adding headers are this easy:
825
826        struct curl_slist *headers=NULL; /* init to NULL is important */
827
828        headers = curl_slist_append(headers, "Hey-server-hey: how are you?");
829        headers = curl_slist_append(headers, "X-silly-content: yes");
830
831        /* pass our list of custom made headers */
832        curl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, headers);
833
834        curl_easy_perform(easyhandle); /* transfer http */
835
836        curl_slist_free_all(headers); /* free the header list */
837
838    ... and if you think some of the internally generated headers, such as
839    Accept: or Host: don't contain the data you want them to contain, you can
840    replace them by simply setting them too:
841
842        headers = curl_slist_append(headers, "Accept: Agent-007");
843        headers = curl_slist_append(headers, "Host: munged.host.line");
844
845   Delete Headers
846
847     If you replace an existing header with one with no contents, you will
848     prevent the header from being sent. Like if you want to completely prevent
849     the "Accept:" header to be sent, you can disable it with code similar to
850     this:
851
852        headers = curl_slist_append(headers, "Accept:");
853
854     Both replacing and cancelling internal headers should be done with careful
855     consideration and you should be aware that you may violate the HTTP
856     protocol when doing so.
857
858   Enforcing chunked transfer-encoding
859
860     By making sure a request uses the custom header "Transfer-Encoding:
861     chunked" when doing a non-GET HTTP operation, libcurl will switch over to
862     "chunked" upload, even though the size of the data to upload might be
863     known. By default, libcurl usually switches over to chunked upload
864     automaticly if the upload data size is unknown.
865
866   HTTP Version
867
868     There's only one aspect left in the HTTP requests that we haven't yet
869     mentioned how to modify: the version field. All HTTP requests includes the
870     version number to tell the server which version we support. libcurl speak
871     HTTP 1.1 by default. Some very old servers don't like getting 1.1-requests
872     and when dealing with stubborn old things like that, you can tell libcurl
873     to use 1.0 instead by doing something like this:
874
875        curl_easy_setopt(easyhandle, CURLOPT_HTTP_VERSION,
876                                     CURLHTTP_VERSION_1_0);
877
878   FTP Custom Commands
879
880     Not all protocols are HTTP-like, and thus the above may not help you when
881     you want to make for example your FTP transfers to behave differently.
882
883     Sending custom commands to a FTP server means that you need to send the
884     comands exactly as the FTP server expects them (RFC959 is a good guide
885     here), and you can only use commands that work on the control-connection
886     alone. All kinds of commands that requires data interchange and thus needs
887     a data-connection must be left to libcurl's own judgement. Also be aware
888     that libcurl will do its very best to change directory to the target
889     directory before doing any transfer, so if you change directory (with CWD
890     or similar) you might confuse libcurl and then it might not attempt to
891     transfer the file in the correct remote directory.
892
893     A little example that deletes a given file before an operation:
894
895       headers = curl_slist_append(headers, "DELE file-to-remove");
896
897       /* pass the list of custom commands to the handle */
898       curl_easy_setopt(easyhandle, CURLOPT_QUOTE, headers);
899
900       curl_easy_perform(easyhandle); /* transfer ftp data! */
901
902       curl_slist_free_all(headers); /* free the header list */
903
904     If you would instead want this operation (or chain of operations) to
905     happen _after_ the data transfer took place the option to
906     curl_easy_setopt() would instead be called CURLOPT_POSTQUOTE and used the
907     exact same way.
908
909     The custom FTP command will be issued to the server in the same order they
910     are added to the list, and if a command gets an error code returned back
911     from the server, no more commands will be issued and libcurl will bail out
912     with an error code (CURLE_FTP_QUOTE_ERROR). Note that if you use
913     CURLOPT_QUOTE to send commands before a transfer, no transfer will
914     actually take place when a quote command has failed.
915
916     If you set the CURLOPT_HEADER to true, you will tell libcurl to get
917     information about the target file and output "headers" about it. The
918     headers will be in "HTTP-style", looking like they do in HTTP.
919
920     The option to enable headers or to run custom FTP commands may be useful
921     to combine with CURLOPT_NOBODY. If this option is set, no actual file
922     content transfer will be performed.
923
924   FTP Custom CUSTOMREQUEST
925
926     If you do what list the contents of a FTP directory using your own defined
927     FTP command, CURLOPT_CUSTOMREQUEST will do just that. "NLST" is the
928     default one for listing directories but you're free to pass in your idea
929     of a good alternative.
930
931
932 Cookies Without Chocolate Chips
933
934  In the HTTP sense, a cookie is a name with an associated value. A server
935  sends the name and value to the client, and expects it to get sent back on
936  every subsequent request to the server that matches the particular conditions
937  set. The conditions include that the domain name and path match and that the
938  cookie hasn't become too old.
939
940  In real-world cases, servers send new cookies to replace existing one to
941  update them. Server use cookies to "track" users and to keep "sessions".
942
943  Cookies are sent from server to clients with the header Set-Cookie: and
944  they're sent from clients to servers with the Cookie: header.
945
946  To just send whatever cookie you want to a server, you can use CURLOPT_COOKIE
947  to set a cookie string like this:
948
949     curl_easy_setopt(easyhandle, CURLOPT_COOKIE, "name1=var1; name2=var2;");
950
951  In many cases, that is not enough. You might want to dynamicly save whatever
952  cookies the remote server passes to you, and make sure those cookies are then
953  use accordingly on later requests.
954
955  One way to do this, is to save all headers you receive in a plain file and
956  when you make a request, you tell libcurl to read the previous headers to
957  figure out which cookies to use. Set header file to read cookies from with
958  CURLOPT_COOKIEFILE.
959
960  The CURLOPT_COOKIEFILE option also automaticly enables the cookie parser in
961  libcurl. Until the cookie parser is enabled, libcurl will not parse or
962  understand incoming cookies and they will just be ignored. However, when the
963  parser is enabled the cookies will be understood and the cookies will be kept
964  in memory and used properly in subsequent requests when the same handle is
965  used. Many times this is enough, and you may not have to save the cookies to
966  disk at all. Note that the file you specify to CURLOPT_COOKIEFILE doesn't
967  have to exist to enable the parser, so a common way to just enable the parser
968  and not read able might be to use a file name you know doesn't exist.
969
970  If you rather use existing cookies that you've previously received with your
971  Netscape or Mozilla browsers, you can make libcurl use that cookie file as
972  input. The CURLOPT_COOKIEFILE is used for that too, as libcurl will
973  automaticly find out what kind of file it is and act accordingly.
974
975  The perhaps most advanced cookie operation libcurl offers, is saving the
976  entire internal cookie state back into a Netscape/Mozilla formatted cookie
977  file. We call that the cookie-jar. When you set a file name with
978  CURLOPT_COOKIEJAR, that file name will be created and all received cookies
979  will be stored in it when curl_easy_cleanup() is called. This enabled cookies
980  to get passed on properly between multiple handles without any information
981  getting lost.
982
983
984 FTP Peculiarities We Need
985
986  FTP transfers use a second TCP/IP connection for the data transfer. This is
987  usually a fact you can forget and ignore but at times this fact will come
988  back to haunt you. libcurl offers several different ways to custom how the
989  second connection is being made.
990
991  libcurl can either connect to the server a second time or tell the server to
992  connect back to it. The first option is the default and it is also what works
993  best for all the people behind firewalls, NATs or IP-masquarading setups.
994  libcurl then tells the server to open up a new port and wait for a second
995  connection. This is by default attempted with EPSV first, and if that doesn't
996  work it tries PASV instead. (EPSV is an extension to the original FTP spec
997  and does not exist nor work on all FTP servers.)
998
999  You can prevent libcurl from first trying the EPSV command by setting
1000  CURLOPT_FTP_USE_EPSV to FALSE.
1001
1002  In some cases, you will prefer to have the server connect back to you for the
1003  second connection. This might be when the server is perhaps behind a firewall
1004  or something and only allows connections on a single port. libcurl then
1005  informs the remote server which IP address and port number to connect to.
1006  This is made with the CURLOPT_FTPPORT option. If you set it to "-", libcurl
1007  will use your system's "default IP address". If you want to use a particular
1008  IP, you can set the full IP address, a host name to resolve to an IP address
1009  or even a local network interface name that libcurl will get the IP address
1010  from.
1011
1012  When doing the "PORT" approach, libcurl will attempt to use the EPRT and the
1013  LPRT before trying PORT, as they work with more protocols. You can disable
1014  this behavior by setting CURLOPT_FTP_USE_EPRT to FALSE.
1015
1016
1017 Headers Equal Fun
1018
1019  Some protocols provide "headers", meta-data separated from the normal
1020  data. These headers are by default not included in the normal data stream,
1021  but you can make them appear in the data stream by setting CURLOPT_HEADER to
1022  TRUE.
1023
1024  What might be even more useful, is libcurl's ability to separate the headers
1025  from the data and thus make the callbacks differ. You can for example set a
1026  different pointer to pass to the ordinary write callback by setting
1027  CURLOPT_WRITEHEADER.
1028
1029  Or, you can set an entirely separate function to receive the headers, by
1030  using CURLOPT_HEADERFUNCTION.
1031
1032  The headers are passed to the callback function one by one, and you can
1033  depend on that fact. It makes it easier for you to add custom header parsers
1034  etc.
1035
1036  "Headers" for FTP transfers equal all the FTP server responses. They aren't
1037  actually true headers, but in this case we pretend they are! ;-)
1038
1039
1040 Post Transfer Information
1041
1042  [ curl_easy_getinfo ]
1043
1044
1045 Security Considerations
1046
1047  libcurl is in itself not insecure. If used the right way, you can use libcurl
1048  to transfer data pretty safely.
1049
1050  There are of course many things to consider that may loosen up this
1051  situation:
1052
1053   Command Lines
1054
1055     If you use a command line tool (such as curl) that uses libcurl, and you
1056     give option to the tool on the command line those options can very likely
1057     get read by other users of your system when they use 'ps' or other tools
1058     to list currently running processes.
1059
1060     To avoid this problem, never feed sensitive things to programs using
1061     command line options.
1062
1063   .netrc
1064
1065     .netrc is a pretty handy file/feature that allows you to login quickly and
1066     automaticly to frequently visited sites. The file contains passwords in
1067     clear text and is a real security risk. In some cases, your .netrc is also
1068     stored in a home directory that is NFS mounted or used on another network
1069     based file system, so the clear text password will fly through your
1070     network every time anyone reads that file!
1071
1072     To avoid this problem, don't use .netrc files and never store passwords in
1073     plain text anywhere.
1074
1075   Clear Text Passwords
1076
1077     Many of the protocols libcurl supports send name and password unencrypted
1078     as clear text (HTTP Basic authentication, FTP, TELNET etc). It is very
1079     easy for anyone on your network or a network nearby yours, to just fire up
1080     a network analyzer tool and evesdrop on your passwords. Don't let the fact
1081     that HTTP uses base64 encoded passwords fool you. They may not look
1082     readable at a first glance, but they very easily "deciphered" by anyone
1083     within seconds.
1084
1085     To avoid this problem, use protocols that don't let snoopers see your
1086     password: HTTPS, FTPS and FTP-kerberos are a few examples. HTTP Digest
1087     authentication allows this too, but isn't supported by libcurl as of this
1088     writing.
1089
1090   Showing What You Do
1091
1092     On a related issue, be aware that even in situations like when you have
1093     problems with libcurl and ask somone for help, everything you reveal in
1094     order to get best possible help might also impose certain security related
1095     risks. Host names, user names, paths, operating system specifics etc (not
1096     to mention passwords of course) may in fact be used by intruders to gain
1097     additional information of a potential target.
1098
1099     To avoid this problem, you must of course use your common sense. Often,
1100     you can just edit out the senstive data or just rearch/replace your true
1101     information with faked data.
1102
1103
1104 SSL, Certificates and Other Tricks
1105
1106  [ seeding, passwords, keys, certificates, ENGINE, ca certs ]
1107
1108 Multiple Transfers Using the multi Interface
1109
1110  The easy interface as described in detail in this document is a synchronous
1111  interface that transfers one file at a time and doesn't return until its
1112  done.
1113
1114  The multi interface on the other hand, allows your program to transfer
1115  multiple files in both directions at the same time, without forcing you to
1116  use multiple threads.
1117
1118  [fill in lots of more multi stuff here]
1119
1120 Future
1121
1122  [ sharing between handles, mutexes, pipelining ]
1123
1124
1125 -----
1126 Footnotes:
1127
1128 [1] = libcurl 7.10.3 and later have the ability to switch over to chunked
1129       Tranfer-Encoding in cases were HTTP uploads are done with data of an
1130       unknown size.
1131
1132 [2] = This happens on Windows machines when libcurl is built and used as a
1133       DLL. However, you can still do this on Windows if you link with a static
1134       library.
1135
1136 [3] = The curl-config tool is generated at build-time (on unix-like systems)
1137       and should be installed with the 'make install' or similar instruction
1138       that installs the library, header files, man pages etc.