MyWebUniversity.com Home Page
 



OpenSolaris man pages main menu


libcurl programming                           libcurl-tutorial(3)



NAME
     libcurl-tutorial - libcurl programming tutorial

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

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

     To get more details on all options and  functions  described
     herein, please refer to their respective man pages.


Building
     There are many different ways  to  build  C  programs.  This
     chapter will assume a UNIX-style build process. If you use a
     different build system, you can still read this to get  gen-
     eral information that may apply to your environment as well.

     Compiling the Program
          Your compiler needs to know where the  libcurl  headers
          are  located.  Therefore  you  must set your compiler's
          include path  to  point  to  the  directory  where  you
          installed  them.  The 'curl-config'[3] tool can be used
          to get this information:

          $ curl-config --cflags


     Linking the Program with libcurl
          When having compiled the program, you need to link your
          object files to create a single executable. For that to
          succeed, you need to link  with  libcurl  and  possibly
          also  with  other libraries that libcurl itself depends
          on. Like the OpenSL libraries, but even some  standard
          OS libraries may be needed on the command line. To fig-
          ure out which flags  to  use,  once  again  the  'curl-
          config' tool comes to the rescue:

          $ curl-config --libs


     SL or Not



libcurl             Last change: 17 Nov 2008                    1






libcurl programming                           libcurl-tutorial(3)



          libcurl can be built and customized in many  ways.  One
          of  the things that varies from different libraries and
          builds is the support  for  SL-based  transfers,  like
          HTPS and FTPS. If a supported SL library was detected
          properly at build-time, libcurl will be built with  SL
          support. To figure out if an installed libcurl has been
          built with SL support enabled, use 'curl-config'  like
          this:

          $ curl-config --feature

          And if SL is supported,  the  keyword  'SL'  will  be
          written  to  stdout, possibly together with a few other
          features that could be either on or  off  on  for  dif-
          ferent libcurls.

          See also the "Features libcurl Provides" further down.

     autoconf macro
          When you write your configure script to detect  libcurl
          and  setup variables accordingly, we offer a prewritten
          macro that probably does everything you  need  in  this
          area.  See  docs/libcurl/libcurl.m4  file - it includes
          docs on how to use it.


Portable Code in a Portable World
     The people behind libcurl have put a considerable effort  to
     make  libcurl  work on a large amount of different operating
     systems and environments.

     You program libcurl the same way on all platforms that  lib-
     curl  runs  on. There are only very few minor considerations
     that differ. If you just make sure to write your code  port-
     able  enough, you may very well create yourself a very port-
     able program. libcurl shouldn't stop you from that.


Global Preparation
     The program must initialize some of the libcurl  functional-
     ity  globally. That means it should be done exactly once, no
     matter how many times you intend to use  the  library.  Once
     for your program's entire life time. This is done using

      curlglobalinit()

     and it takes one parameter which is a bit pattern that tells
     libcurl  what to initialize. Using CURLGLOBALAL will make
     it initialize all known internal sub modules, and might be a
     good default option. The current two bits that are specified
     are:




libcurl             Last change: 17 Nov 2008                    2






libcurl programming                           libcurl-tutorial(3)



          CURLGLOBALWIN32
               which only does anything on Windows machines. When
               used on a Windows machine, it'll make libcurl ini-
               tialize the win32  socket  stuff.  Without  having
               that initialized properly, your program cannot use
               sockets properly. You should only do this once for
               each  application, so if your program already does
               this or of another library in  use  does  it,  you
               should not tell libcurl to do this as well.

          CURLGLOBALSL
               which only does anything on libcurls compiled  and
               built  SL-enabled.  On  these  systems, this will
               make libcurl initialize the SL  library  properly
               for  this  application. This only needs to be done
               once for each application so if  your  program  or
               another library already does this, this bit should
               not be needed.

     libcurl has a default protection mechanism that  detects  if
     curlglobalinit(3)   hasn't   been   called   by  the  time
     curleasyperform(3) is called and if that is the case, lib-
     curl  runs  the  function itself with a guessed bit pattern.
     Please note that depending solely on this is not  considered
     nice nor very good.

     When the program no longer  uses  libcurl,  it  should  call
     curlglobalcleanup(3),  which  is  the opposite of the init
     call. It will then do the reversed operations to cleanup the
     resources the curlglobalinit(3) call initialized.

     Repeated     calls      to      curlglobalinit(3)      and
     curlglobalcleanup(3)  should  be avoided. They should only
     be called once each.


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


Handle the Easy libcurl
     libcurl first introduced the so called easy  interface.  All
     operations   in   the   easy  interface  are  prefixed  with
     'curleasy'.

     Recent libcurl versions also offer the multi interface. More
     about that interface, what it is targeted for and how to use
     it is detailed in a separate chapter further down. You still



libcurl             Last change: 17 Nov 2008                    3






libcurl programming                           libcurl-tutorial(3)



     need  to understand the easy interface first, so please con-
     tinue reading for better understanding.

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

     Get an easy handle with

      easyhandle = curleasyinit();

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

     You  set  properties  and  options  for  this  handle  using
     curleasysetopt(3).   They   control   how  the  subsequent
     transfer or transfers will be made. Options  remain  set  in
     the  handle  until  set  again to something different. Alas,
     multiple requests using the same handle will  use  the  same
     options.

     Many of the  options  you  set  in  libcurl  are  "strings",
     pointers  to  data terminated with a zero byte. When you set
     strings with curleasysetopt(3), libcurl makes its own copy
     so  that  they don't need to be kept around in your applica-
     tion after being set[4].

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

      curleasysetopt(handle, CURLOPTURL, "http:/domain.com/");

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

      sizet writedata(void *buffer, sizet size, sizet  nmemb,
     void *userp);

     You tell libcurl to pass all data to this function by  issu-
     ing a function similar to this:

      curleasysetopt(easyhandle,         CURLOPTWRITEFUNCTION,



libcurl             Last change: 17 Nov 2008                    4






libcurl programming                           libcurl-tutorial(3)



     writedata);

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

      curleasysetopt(easyhandle,             CURLOPTWRITEDATA,
     &internalstruct);

     Using that property, you can easily pass local data  between
     your  application and the function that gets invoked by lib-
     curl. libcurl itself won't touch  the  data  you  pass  with
     CURLOPTWRITEDATA.

     libcurl offers its own  default  internal  callback  that'll
     take  care  of  the  data if you don't set the callback with
     CURLOPTWRITEFUNCTION.  It  will  then  simply  output   the
     received  data  to stdout. You can have the default callback
     write the data to a different file handle by passing a 'FILE
     *'  to  a file opened for writing with the CURLOPTWRITEDATA
     option.

     Now, we need to take a step back and  have  a  deep  breath.
     Here's  one  of  those rare platform-dependent nitpicks. Did
     you spot it? On some platforms[2], libcurl won't be able  to
     operate on files opened by the program. Thus, if you use the
     default  callback  and   pass   in   an   open   file   with
     CURLOPTWRITEDATA, it will crash. You should therefore avoid
     this to make your program run fine virtually everywhere.

     (CURLOPTWRITEDATA was formerly known as CURLOPTFILE.  Both
     names still work and do the same thing).

     If you're using libcurl as a win32 DL,  you  MUST  use  the
     CURLOPTWRITEFUNCTION  if you set CURLOPTWRITEDATA - or you
     will experience crashes.

     There are of course many more options you can set, and we'll
     get  back  to a few of them later. Let's instead continue to
     the actual transfer:

      success = curleasyperform(easyhandle);

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




libcurl             Last change: 17 Nov 2008                    5






libcurl programming                           libcurl-tutorial(3)



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

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

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


Multi-threading Issues
     The first basic rule is that you must never share a  libcurl
     handle  (be  it  easy or multi or whatever) between multiple
     threads. Only use one handle in one thread at a time.

     libcurl is completely thread safe, except  for  two  issues:
     signals  and  SL/TLS  handlers. Signals are used for timing
     out name resolves (during DNS lookup) - when  built  without
     c-ares support and not on Windows.

     If you are accessing HTPS or FTPS URLs in a  multi-threaded
     manner,  you  are  then  of  course using the underlying SL
     library multi-threaded and those libs might have  their  own
     requirements  on  this issue. Basically, you need to provide
     one or two functions to allow it to function  properly.  For
     all details, see this:

     OpenSL

      http:/www.openssl.org/docs/crypto/threads.html#DESCRIPTION

     GnuTLS

      http:/www.gnu.org/software/gnutls/manual/htmlnode/Multi002dthreaded-
     applications.html

     NS

      is claimed  to  be  thread-safe  already  without  anything
     required.




libcurl             Last change: 17 Nov 2008                    6






libcurl programming                           libcurl-tutorial(3)



     yassl

      Required actions unknown.

     When   using   multiple   threads   you   should   set   the
     CURLOPTNOSIGNAL  option  to  1  for all handles. Everything
     will or might work fine except that timeouts are not honored
     during  the DNS lookup - which you can work around by build-
     ing libcurl with c-ares support. c-ares is  a  library  that
     provides asynchronous name resolves. On some platforms, lib-
     curl simply will not function properly multi-threaded unless
     this option is set.

     Also, note that CURLOPTDNSUSEGLOBALCACHE is not  thread-
     safe.


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

     There's one golden rule when these  things  occur:  set  the
     CURLOPTVERBOSE option to 1. It'll cause the library to spew
     out the entire protocol details it sends, some internal info
     and  some  received  protocol  data as well (especially when
     using FTP). If you're using HTP, adding the headers in  the
     received  output  to  study  is  also  a clever way to get a
     better understanding why the server behaves the way it does.
     Include   headers   in   the   normal   body   output   with
     CURLOPTHEADER set 1.

     Of course, there are bugs left. We need to know  about  them
     to be able to fix them, so we're quite dependent on your bug
     reports! When you  do  report  suspected  bugs  in  libcurl,
     please include as many details as you possibly can: a proto-
     col dump that CURLOPTVERBOSE produces, library version,  as
     much  as  possible of your code that uses libcurl, operating
     system name and version, compiler name and version etc.

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

     Getting some in-depth knowledge about the protocols involved
     is never wrong, and if you're trying to do funny things, you
     might very well understand libcurl and how to use it  better
     if you study the appropriate RFC documents at least briefly.





libcurl             Last change: 17 Nov 2008                    7






libcurl programming                           libcurl-tutorial(3)



Upload Data to a Remote Site
     libcurl tries to keep a  protocol  independent  approach  to
     most  transfers, thus uploading to a remote FTP site is very
     similar to uploading data  to  a  HTP  server  with  a  PUT
     request.

     Of course, first you either create an  easy  handle  or  you
     re-use  one existing one. Then you set the URL to operate on
     just like before. This is the remote URL, that we  now  will
     upload.

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

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

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

      curleasysetopt(easyhandle,          CURLOPTREADFUNCTION,
     readfunction);

      curleasysetopt(easyhandle, CURLOPTREADATA, &filedata);

     Tell libcurl that we want to upload:

      curleasysetopt(easyhandle, CURLOPTUPLOAD, 1L);

     A few protocols won't behave properly when uploads are  done
     without  any  prior knowledge of the expected file size. So,
     set the upload file size using the  CURLOPTINFILESIZELARGE
     for all known file sizes like this[1]:

      /* in this example, filesize must be an curlofft variable */
      curleasysetopt(easyhandle, CURLOPTINFILESIZELARGE, filesize);

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



libcurl             Last change: 17 Nov 2008                    8






libcurl programming                           libcurl-tutorial(3)



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

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

      protocol:/user:password@example.com/path/

     If you need any odd letters in your user name  or  password,
     you  should  enter  them  URL  encoded, as %X where X is a
     two-digit hexadecimal number.

     libcurl also provides options to set various passwords.  The
     user  name  and  password  as  shown embedded in the URL can
     instead get set with the CURLOPTUSERPWD option.  The  argu-
     ment passed to libcurl should be a char * to a string in the
     format "user:password:". In a manner like this:

      curleasysetopt(easyhandle,               CURLOPTUSERPWD,
     "myname:thesecret");

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

      curleasysetopt(easyhandle,          CURLOPTPROXYUSERPWD,
     "myname:thesecret");

     There's a long time UNIX "standard" way of storing ftp  user
     names  and  passwords,  namely in the $HOME/.netrc file. The
     file should be made private so that only the user  may  read
     it  (see  also the "Security Considerations" chapter), as it
     might contain the password in plain text.  libcurl  has  the
     ability to use this file to figure out what set of user name
     and password to use for a particular host. As  an  extension
     to the normal functionality, libcurl also supports this file
     for non-FTP protocols such as HTP. To make  curl  use  this
     file, use the CURLOPTNETRC option:

      curleasysetopt(easyhandle, CURLOPTNETRC, 1L);

     And a very basic example of how such a .netrc file may  look
     like:

      machine myhost.mydomain.com
      login userlogin
      password secretword



libcurl             Last change: 17 Nov 2008                    9






libcurl programming                           libcurl-tutorial(3)



     All these examples have been cases where  the  password  has
     been  optional,  or at least you could leave it out and have
     libcurl attempt to do its job without it.  There  are  times
     when  the password isn't optional, like when you're using an
     SL private key for secure transfers.

     To pass the known private key password to libcurl:

      curleasysetopt(easyhandle,  CURLOPTKEYPASWD,  "keypass-
     word");


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

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

      curleasysetopt(easyhandle,              CURLOPTHTPAUTH,
     CURLAUTHDIGEST);

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

      curleasysetopt(easyhandle,             CURLOPTPROXYAUTH,
     CURLAUTHNTLM);

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

      curleasysetopt(easyhandle, CURLOPTHTPAUTH,
      CURLAUTHDIGESTCURLAUTHBASIC);

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

     When asking for multiple types, libcurl will pick the avail-
     able  one  it  considers "best" in its own internal order of



libcurl             Last change: 17 Nov 2008                   10






libcurl programming                           libcurl-tutorial(3)



     preference.


HTP POSTing
     We get many questions regarding how to issue HTP POSTs with
     libcurl the proper way. This chapter will thus include exam-
     ples using both different versions of HTP POST that libcurl
     supports.

     The first version is the simple POST, the most  common  ver-
     sion,  that  most  HTML  pages using the 
tag uses. We provide a pointer to the data and tell libcurl to post it all to the remote site: char *data="name=daniel&project=curl"; curleasysetopt(easyhandle, CURLOPTPOSTFIELDS, data); curleasysetopt(easyhandle, CURLOPTURL, "http:/posthere.com/"); curleasyperform(easyhandle); /* post away! */ Simple enough, huh? Since you set the POST options with the CURLOPTPOSTFIELDS, this automatically switches the handle to use POST in the upcoming request. Ok, so what if you want to post binary data that also requires you to set the Content-Type: header of the post? Well, binary posts prevent libcurl from being able to do strlen() on the data to figure out the size, so therefore we must tell libcurl the size of the post data. Setting headers in libcurl requests are done in a generic way, by building a list of our own headers and then passing that list to lib- curl. struct curlslist *headers=NUL; headers = curlslistappend(headers, "Content-Type: text/xml"); /* post binary data */ curleasysetopt(easyhandle, CURLOPTPOSTFIELDS, binaryptr); /* set the size of the postfields data */ curleasysetopt(easyhandle, CURLOPTPOSTFIELDSIZE, 23L); /* pass our list of custom made headers */ curleasysetopt(easyhandle, CURLOPTHTPHEADER, headers); curleasyperform(easyhandle); /* post away! */ curlslistfreeall(headers); /* free the header list */ While the simple examples above cover the majority of all cases where HTP POST operations are required, they don't do multi-part formposts. Multi-part formposts were introduced libcurl Last change: 17 Nov 2008 11 libcurl programming libcurl-tutorial(3) as a better way to post (possibly large) binary data and were first documented in the RFC1867. They're called multi- part because they're built by a chain of parts, each being a single unit. Each part has its own name and contents. You can in fact create and post a multi-part formpost with the regular libcurl POST support described above, but that would require that you build a formpost yourself and provide to libcurl. To make that easier, libcurl provides curlformadd(3). Using this function, you add parts to the form. When you're done adding parts, you post the whole form. The following example sets two simple text parts with plain textual contents, and then a file with binary contents and uploads the whole thing. struct curlhttppost *post=NUL; struct curlhttppost *last=NUL; curlformadd(&post, &last, CURLFORMCOPYNAME, "name", CURLFORMCOPYCONTENTS, "daniel", CURLFORMEND); curlformadd(&post, &last, CURLFORMCOPYNAME, "project", CURLFORMCOPYCONTENTS, "curl", CURLFORMEND); curlformadd(&post, &last, CURLFORMCOPYNAME, "logotype-image", CURLFORMFILECONTENT, "curl.png", CURLFORMEND); /* Set the form info */ curleasysetopt(easyhandle, CURLOPTHTPOST, post); curleasyperform(easyhandle); /* post away! */ /* free the post data again */ curlformfree(post); Multipart formposts are chains of parts using MIME-style separators and headers. It means that each one of these separate parts get a few headers set that describe the indi- vidual content-type, size etc. To enable your application to handicraft this formpost even more, libcurl allows you to supply your own set of custom headers to such an individual form part. You can of course supply headers to as many parts as you like, but this little example will show how you set headers to one specific part when you add that to the post handle: struct curlslist *headers=NUL; headers = curlslistappend(headers, "Content-Type: text/xml"); curlformadd(&post, &last, CURLFORMCOPYNAME, "logotype-image", libcurl Last change: 17 Nov 2008 12 libcurl programming libcurl-tutorial(3) CURLFORMFILECONTENT, "curl.xml", CURLFORMCONTENTHEADER, headers, CURLFORMEND); curleasyperform(easyhandle); /* post away! */ curlformfree(post); /* free post */ curlslistfreeall(post); /* free custom header list */ Since all options on an easyhandle are "sticky", they remain the same until changed even if you do call curleasyperform(3), you may need to tell curl to go back to a plain GET request if you intend to do one as your next request. You force an easyhandle to go back to GET by using the CURLOPTHTPGET option: curleasysetopt(easyhandle, CURLOPTHTPGET, 1L); Just setting CURLOPTPOSTFIELDS to "" or NUL will *not* stop libcurl from doing a POST. It will just make it POST without any data to send! Showing Progress For historical and traditional reasons, libcurl has a built-in progress meter that can be switched on and then makes it present a progress meter in your terminal. Switch on the progress meter by, oddly enough, setting CURLOPTNOPROGRES to zero. This option is set to 1 by default. For most applications however, the built-in progress meter is useless and what instead is interesting is the ability to specify a progress callback. The function pointer you pass to libcurl will then be called on irregular intervals with information about the current transfer. Set the progress callback by using CURLOPTPROGRESFUNCTION. And pass a pointer to a function that matches this proto- type: int progresscallback(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); If any of the input arguments is unknown, a 0 will be passed. The first argument, the 'clientp' is the pointer you pass to libcurl with CURLOPTPROGRESDATA. libcurl won't touch it. libcurl Last change: 17 Nov 2008 13 libcurl programming libcurl-tutorial(3) libcurl with C] There's basically only one thing to keep in mind when using C] instead of C when interfacing libcurl: The callbacks CANOT be non-static class member functions Example C] code: class AClass { static sizet writedata(void *ptr, sizet size, sizet nmemb, void *ourpointer) { /* do what you want with the data */ } } Proxies What "proxy" means according to Merriam-Webster: "a person authorized to act for another" but also "the agency, func- tion, or office of a deputy who acts as a substitute for another". Proxies are exceedingly common these days. Companies often only offer Internet access to employees through their prox- ies. Network clients or user-agents ask the proxy for docu- ments, the proxy does the actual request and then it returns them. libcurl supports SOCKS and HTP proxies. When a given URL is wanted, libcurl will ask the proxy for it instead of trying to connect to the actual host identified in the URL. If you're using a SOCKS proxy, you may find that libcurl doesn't quite support all operations through it. For HTP proxies: the fact that the proxy is a HTP proxy puts certain restrictions on what can actually happen. A requested URL that might not be a HTP URL will be still be passed to the HTP proxy to deliver back to libcurl. This happens transparently, and an application may not need to know. I say "may", because at times it is very important to understand that all operations over a HTP proxy use the HTP protocol. For example, you can't invoke your own custom FTP commands or even proper FTP directory listings. Proxy Options To tell libcurl to use a proxy at a given port number: curleasysetopt(easyhandle, CURLOPTPROXY, "proxy- libcurl Last change: 17 Nov 2008 14 libcurl programming libcurl-tutorial(3) host.com:8080"); Some proxies require user authentication before allow- ing a request, and you pass that information similar to this: curleasysetopt(easyhandle, CURLOPTPROXYUSERPWD, "user:password"); If you want to, you can specify the host name only in the CURLOPTPROXY option, and set the port number separately with CURLOPTPROXYPORT. Tell libcurl what kind of proxy it is with CURLOPTPROXYTYPE (if not, it will default to assume a HTP proxy): curleasysetopt(easyhandle, CURLOPTPROXYTYPE, CURLPROXYSOCKS4); Environment Variables libcurl automatically checks and uses a set of environ- ment variables to know what proxies to use for certain protocols. The names of the variables are following an ancient de facto standard and are built up as "[protocol]proxy" (note the lower casing). Which makes the variable HTP. Following the same rule, the vari- able named 'ftpproxy' is checked for FTP URLs. Again, the proxies are always HTP proxies, the different names of the variables simply allows different HTP proxies to be used. The proxy environment variable contents should be in the format "[protocol:/][user:password@]machine[:port]". Where the protocol:/ part is simply ignored if present (so http:/proxy and bluerk:/proxy will do the same) and the optional port number specifies on which port the proxy operates on the host. If not specified, the internal default port number will be used and that is most likely *not* the one you would like it to be. There are two special environment variables. 'allproxy' is what sets proxy for any URL in case the protocol specific variable wasn't set, and 'noproxy' defines a list of hosts that should not use a proxy even though a variable may say so. If 'noproxy' is a plain asterisk ("*") it matches all hosts. To explicitly disable libcurl's checking for and using libcurl Last change: 17 Nov 2008 15 libcurl programming libcurl-tutorial(3) the proxy environment variables, set the proxy name to "" - an empty string - with CURLOPTPROXY. SL and Proxies SL is for secure point-to-point connections. This involves strong encryption and similar things, which effectively makes it impossible for a proxy to operate as a "man in between" which the proxy's task is, as previously discussed. Instead, the only way to have SL work over a HTP proxy is to ask the proxy to tunnel trough everything without being able to check or fiddle with the traffic. Opening an SL connection over a HTP proxy is therefor a matter of asking the proxy for a straight connection to the target host on a specified port. This is made with the HTP request CONECT. ("please mr proxy, con- nect me to that remote host"). Because of the nature of this operation, where the proxy has no idea what kind of data that is passed in and out through this tunnel, this breaks some of the very few advantages that come from using a proxy, such as caching. Many organizations prevent this kind of tunneling to other destination port numbers than 443 (which is the default HTPS port number). Tunneling Through Proxy As explained above, tunneling is required for SL to work and often even restricted to the operation intended for SL; HTPS. This is however not the only time proxy-tunneling might offer benefits to you or your application. As tunneling opens a direct connection from your appli- cation to the remote machine, it suddenly also re- introduces the ability to do non-HTP operations over a HTP proxy. You can in fact use things such as FTP upload or FTP custom commands this way. Again, this is often prevented by the administrators of proxies and is rarely allowed. Tell libcurl to use proxy tunneling like this: curleasysetopt(easyhandle, CURLOPTHTPROXYTUNEL, 1L); In fact, there might even be times when you want to do libcurl Last change: 17 Nov 2008 16 libcurl programming libcurl-tutorial(3) plain HTP operations using a tunnel like this, as it then enables you to operate on the remote server instead of asking the proxy to do so. libcurl will not stand in the way for such innovative actions either! Proxy Auto-Config Netscape first came up with this. It is basically a web page (usually using a .pac extension) with a javascript that when executed by the browser with the requested URL as input, returns information to the browser on how to connect to the URL. The returned information might be "DIRECT" (which means no proxy should be used), "PROXY host:port" (to tell the browser where the proxy for this particular URL is) or "SOCKS host:port" (to direct the browser to a SOCKS proxy). libcurl has no means to interpret or evaluate javas- cript and thus it doesn't support this. If you get yourself in a position where you face this nasty inven- tion, the following advice have been mentioned and used in the past: - Depending on the javascript complexity, write up a script that translates it to another language and exe- cute that. - Read the javascript code and rewrite the same logic in another language. - Implement a javascript interpreted, people have suc- cessfully used the Mozilla javascript engine in the past. - Ask your admins to stop this, for a static proxy setup or similar. Persistence Is The Way to Happiness Re-cycling the same easy handle several times when doing multiple requests is the way to go. After each single curleasyperform(3) operation, libcurl will keep the connection alive and open. A subsequent request using the same easy handle to the same host might just be able to use the already open connection! This reduces network impact a lot. Even if the connection is dropped, all connections involving SL to the same host again, will benefit from libcurl's ses- sion ID cache that drastically reduces re-connection time. libcurl Last change: 17 Nov 2008 17 libcurl programming libcurl-tutorial(3) FTP connections that are kept alive save a lot of time, as the command- response round-trips are skipped, and also you don't risk getting blocked without permission to login again like on many FTP servers only allowing N persons to be logged in at the same time. libcurl caches DNS name resolving results, to make lookups of a previously looked up name a lot faster. Other interesting details that improve performance for sub- sequent requests may also be added in the future. Each easy handle will attempt to keep the last few connec- tions alive for a while in case they are to be used again. You can set the size of this "cache" with the CURLOPTMAXCONECTS option. Default is 5. There is very sel- dom any point in changing this value, and if you think of changing this it is often just a matter of thinking again. To force your upcoming request to not use an already exist- ing connection (it will even close one first if there hap- pens to be one alive to the same host you're about to oper- ate on), you can do that by setting CURLOPTFRESHCONECT to 1. In a similar spirit, you can also forbid the upcoming request to be "lying" around and possibly get re-used after the request by setting CURLOPTFORBIDREUSE to 1. HTP Headers Used by libcurl When you use libcurl to do HTP requests, it'll pass along a series of headers automatically. It might be good for you to know and understand these. You can replace or remove them by using the CURLOPTHTPHEADER option. Host This header is required by HTP 1.1 and even many 1.0 servers and should be the name of the server we want to talk to. This includes the port number if anything but default. Pragma "no-cache". Tells a possible proxy to not grab a copy from the cache but to fetch a fresh one. Accept "*/*". Expect When doing POST requests, libcurl sets this header to libcurl Last change: 17 Nov 2008 18 libcurl programming libcurl-tutorial(3) "100-continue" to ask the server for an "OK" message before it proceeds with sending the data part of the post. If the POSTed data amount is deemed "small", lib- curl will not use this header. Customizing Operations There is an ongoing development today where more and more protocols are built upon HTP for transport. This has obvi- ous benefits as HTP is a tested and reliable protocol that is widely deployed and has excellent proxy-support. When you use one of these protocols, and even when doing other kinds of programming you may need to change the tradi- tional HTP (or FTP or...) manners. You may need to change words, headers or various data. libcurl is your friend here too. CUSTOMREQUEST If just changing the actual HTP request keyword is what you want, like when GET, HEAD or POST is not good enough for you, CURLOPTCUSTOMREQUEST is there for you. It is very simple to use: curleasysetopt(easyhandle, CURLOPTCUSTOMREQUEST, "MYOWNRUQUEST"); When using the custom request, you change the request keyword of the actual request you are performing. Thus, by default you make a GET request but you can also make a POST operation (as described before) and then replace the POST keyword if you want to. You're the boss. Modify Headers HTP-like protocols pass a series of headers to the server when doing the request, and you're free to pass any amount of extra headers that you think fit. Adding headers is this easy: struct curlslist *headers=NUL; /* init to NUL is important */ headers = curlslistappend(headers, "Hey-server-hey: how are you?"); headers = curlslistappend(headers, "X-silly-content: yes"); /* pass our list of custom made headers */ curleasysetopt(easyhandle, CURLOPTHTPHEADER, headers); curleasyperform(easyhandle); /* transfer http */ libcurl Last change: 17 Nov 2008 19 libcurl programming libcurl-tutorial(3) curlslistfreeall(headers); /* free the header list */ ... and if you think some of the internally generated headers, such as Accept: or Host: don't contain the data you want them to contain, you can replace them by simply setting them too: headers = curlslistappend(headers, "Accept: Agent-007"); headers = curlslistappend(headers, "Host: munged.host.line"); Delete Headers If you replace an existing header with one with no con- tents, you will prevent the header from being sent. For instance, if you want to completely prevent the "Accept:" header from being sent, you can disable it with code similar to this: headers = curlslistappend(headers, "Accept:"); Both replacing and canceling internal headers should be done with careful consideration and you should be aware that you may violate the HTP protocol when doing so. Enforcing chunked transfer-encoding By making sure a request uses the custom header "Transfer-Encoding: chunked" when doing a non-GET HTP operation, libcurl will switch over to "chunked" upload, even though the size of the data to upload might be known. By default, libcurl usually switches over to chunked upload automatically if the upload data size is unknown. HTP Version All HTP requests includes the version number to tell the server which version we support. libcurl speaks HTP 1.1 by default. Some very old servers don't like getting 1.1-requests and when dealing with stubborn old things like that, you can tell libcurl to use 1.0 instead by doing something like this: curleasysetopt(easyhandle, CURLOPTHTPVERSION, CURLHTPVERSION10); FTP Custom Commands Not all protocols are HTP-like, and thus the above may libcurl Last change: 17 Nov 2008 20 libcurl programming libcurl-tutorial(3) not help you when you want to make, for example, your FTP transfers to behave differently. Sending custom commands to a FTP server means that you need to send the commands exactly as the FTP server expects them (RFC959 is a good guide here), and you can only use commands that work on the control-connection alone. All kinds of commands that require data inter- change and thus need a data-connection must be left to libcurl's own judgment. Also be aware that libcurl will do its very best to change directory to the target directory before doing any transfer, so if you change directory (with CWD or similar) you might confuse lib- curl and then it might not attempt to transfer the file in the correct remote directory. A little example that deletes a given file before an operation: headers = curlslistappend(headers, "DELE file-to-remove"); /* pass the list of custom commands to the handle */ curleasysetopt(easyhandle, CURLOPTQUOTE, headers); curleasyperform(easyhandle); /* transfer ftp data! */ curlslistfreeall(headers); /* free the header list */ If you would instead want this operation (or chain of operations) to happen after the data transfer took place the option to curleasysetopt(3) would instead be called CURLOPTPOSTQUOTE and used the exact same way. The custom FTP command will be issued to the server in the same order they are added to the list, and if a command gets an error code returned back from the server, no more commands will be issued and libcurl will bail out with an error code (CURLEQUOTEROR). Note that if you use CURLOPTQUOTE to send commands before a transfer, no transfer will actually take place when a quote command has failed. If you set the CURLOPTHEADER to 1, you will tell lib- curl to get information about the target file and out- put "headers" about it. The headers will be in "HTP- style", looking like they do in HTP. The option to enable headers or to run custom FTP com- mands may be useful to combine with CURLOPTNOBODY. If this option is set, no actual file content transfer will be performed. libcurl Last change: 17 Nov 2008 21 libcurl programming libcurl-tutorial(3) FTP Custom CUSTOMREQUEST If you do want to list the contents of a FTP directory using your own defined FTP command, CURLOPTCUSTOMREQUEST will do just that. "NLST" is the default one for listing directories but you're free to pass in your idea of a good alternative. Cookies Without Chocolate Chips In the HTP sense, a cookie is a name with an associated value. A server sends the name and value to the client, and expects it to get sent back on every subsequent request to the server that matches the particular conditions set. The conditions include that the domain name and path match and that the cookie hasn't become too old. In real-world cases, servers send new cookies to replace existing ones to update them. Server use cookies to "track" users and to keep "sessions". Cookies are sent from server to clients with the header Set-Cookie: and they're sent from clients to servers with the Cookie: header. To just send whatever cookie you want to a server, you can use CURLOPTCOKIE to set a cookie string like this: curleasysetopt(easyhandle, CURLOPTCOKIE, "name1=var1; name2=var2;"); In many cases, that is not enough. You might want to dynami- cally save whatever cookies the remote server passes to you, and make sure those cookies are then used accordingly on later requests. One way to do this, is to save all headers you receive in a plain file and when you make a request, you tell libcurl to read the previous headers to figure out which cookies to use. Set the header file to read cookies from with CURLOPTCOKIEFILE. The CURLOPTCOKIEFILE option also automatically enables the cookie parser in libcurl. Until the cookie parser is enabled, libcurl will not parse or understand incoming cook- ies and they will just be ignored. However, when the parser is enabled the cookies will be understood and the cookies will be kept in memory and used properly in subsequent requests when the same handle is used. Many times this is enough, and you may not have to save the cookies to disk at all. Note that the file you specify to CURLOPTCOKIEFILE doesn't have to exist to enable the parser, so a common way to just enable the parser and not read any cookies is to use libcurl Last change: 17 Nov 2008 22 libcurl programming libcurl-tutorial(3) the name of a file you know doesn't exist. If you would rather use existing cookies that you've previ- ously received with your Netscape or Mozilla browsers, you can make libcurl use that cookie file as input. The CURLOPTCOKIEFILE is used for that too, as libcurl will automatically find out what kind of file it is and act accordingly. Perhaps the most advanced cookie operation libcurl offers, is saving the entire internal cookie state back into a Netscape/Mozilla formatted cookie file. We call that the cookie-jar. When you set a file name with CURLOPTCOKIEJAR, that file name will be created and all received cookies will be stored in it when curleasycleanup(3) is called. This enables cookies to get passed on properly between multiple handles without any information getting lost. FTP Peculiarities We Need FTP transfers use a second TCP/IP connection for the data transfer. This is usually a fact you can forget and ignore but at times this fact will come back to haunt you. libcurl offers several different ways to customize how the second connection is being made. libcurl can either connect to the server a second time or tell the server to connect back to it. The first option is the default and it is also what works best for all the peo- ple behind firewalls, NATs or IP-masquerading setups. lib- curl then tells the server to open up a new port and wait for a second connection. This is by default attempted with EPSV first, and if that doesn't work it tries PASV instead. (EPSV is an extension to the original FTP spec and does not exist nor work on all FTP servers.) You can prevent libcurl from first trying the EPSV command by setting CURLOPTFTPUSEPSV to zero. In some cases, you will prefer to have the server connect back to you for the second connection. This might be when the server is perhaps behind a firewall or something and only allows connections on a single port. libcurl then informs the remote server which IP address and port number to connect to. This is made with the CURLOPTFTPORT option. If you set it to "-", libcurl will use your system's "default IP address". If you want to use a particular IP, you can set the full IP address, a host name to resolve to an IP address or even a local network interface name that libcurl will get the IP address from. When doing the "PORT" approach, libcurl will attempt to use libcurl Last change: 17 Nov 2008 23 libcurl programming libcurl-tutorial(3) the EPRT and the LPRT before trying PORT, as they work with more protocols. You can disable this behavior by setting CURLOPTFTPUSEPRT to zero. Headers Equal Fun Some protocols provide "headers", meta-data separated from the normal data. These headers are by default not included in the normal data stream, but you can make them appear in the data stream by setting CURLOPTHEADER to 1. What might be even more useful, is libcurl's ability to sep- arate the headers from the data and thus make the callbacks differ. You can for example set a different pointer to pass to the ordinary write callback by setting CURLOPTWRITEHEADER. Or, you can set an entirely separate function to receive the headers, by using CURLOPTHEADERFUNCTION. The headers are passed to the callback function one by one, and you can depend on that fact. It makes it easier for you to add custom header parsers etc. "Headers" for FTP transfers equal all the FTP server res- ponses. They aren't actually true headers, but in this case we pretend they are! ;-) Post Transfer Information [ curleasygetinfo ] Security Considerations libcurl is in itself not insecure. If used the right way, you can use libcurl to transfer data pretty safely. There are of course many things to consider that may loosen up this situation: Command Lines If you use a command line tool (such as curl) that uses libcurl, and you give option to the tool on the command line those options can very likely get read by other users of your system when they use 'ps' or other tools to list currently running processes. To avoid this problem, never feed sensitive things to programs using command line options. libcurl Last change: 17 Nov 2008 24 libcurl programming libcurl-tutorial(3) .netrc .netrc is a pretty handy file/feature that allows you to login quickly and automatically to frequently visited sites. The file contains passwords in clear text and is a real security risk. In some cases, your .netrc is also stored in a home directory that is NFS mounted or used on another network based file system, so the clear text password will fly through your net- work every time anyone reads that file! To avoid this problem, don't use .netrc files and never store passwords in plain text anywhere. Clear Text Passwords Many of the protocols libcurl supports send name and password unencrypted as clear text (HTP Basic authen- tication, FTP, TELNET etc). It is very easy for anyone on your network or a network nearby yours, to just fire up a network analyzer tool and eavesdrop on your pass- words. Don't let the fact that HTP Basic uses base64 encoded passwords fool you. They may not look readable at a first glance, but they very easily "deciphered" by anyone within seconds. To avoid this problem, use HTP athentication methods or other protocols that don't let snoopers see your password: HTP with Digest, NTLM or GS authentication, HTPS, FTPS, SCP, SFTP and FTP-kerberos are a few exam- ples. Showing What You Do On a related issue, be aware that even in situations like when you have problems with libcurl and ask some- one for help, everything you reveal in order to get best possible help might also impose certain security related risks. Host names, user names, paths, operating system specifics, etc (not to mention passwords of course) may in fact be used by intruders to gain addi- tional information of a potential target. To avoid this problem, you must of course use your com- mon sense. Often, you can just edit out the sensitive data or just search/replace your true information with faked data. Multiple Transfers Using the multi Interface The easy interface as described in detail in this document is a synchronous interface that transfers one file at a time and doesn't return until it is done. libcurl Last change: 17 Nov 2008 25 libcurl programming libcurl-tutorial(3) The multi interface, on the other hand, allows your program to transfer multiple files in both directions at the same time, without forcing you to use multiple threads. The name might make it seem that the multi interface is for multi- threaded programs, but the truth is almost the reverse. The multi interface can allow a single-threaded application to perform the same kinds of multiple, simultaneous transfers that multi-threaded programs can perform. It allows many of the benefits of multi-threaded transfers without the com- plexity of managing and synchronizing many threads. To use this interface, you are better off if you first understand the basics of how to use the easy interface. The multi interface is simply a way to make multiple transfers at the same time by adding up multiple easy handles into a "multi stack". You create the easy handles you want and you set all the options just like you have been told above, and then you create a multi handle with curlmultiinit(3) and add all those easy handles to that multi handle with curlmultiaddhandle(3). When you've added the handles you have for the moment (you can still add new ones at any time), you start the transfers by calling curlmultiperform(3). curlmultiperform(3) is asynchronous. It will only execute as little as possible and then return back control to your program. It is designed to never block. If it returns CURLMCALMULTIPERFORM you better call it again soon, as that is a signal that it still has local data to send or remote data to receive. The best usage of this interface is when you do a select() on all possible file descriptors or sockets to know when to call libcurl again. This also makes it easy for you to wait and respond to actions on your own application's sockets/handles. You figure out what to select() for by using curlmultifdset(3), that fills in a set of fdset variables for you with the particular file descriptors lib- curl uses for the moment. When you then call select(), it'll return when one of the file handles signal action and you then call curlmultiperform(3) to allow libcurl to do what it wants to do. Take note that libcurl does also feature some time- out code so we advise you to never use very long timeouts on select() before you call curlmultiperform(3), which thus should be called unconditionally every now and then even if none of its file descriptors have signaled ready. Another precaution you should use: always call curlmultifdset(3) libcurl Last change: 17 Nov 2008 26 libcurl programming libcurl-tutorial(3) immediately before the select() call since the current set of file descriptors may change when calling a curl function. If you want to stop the transfer of one of the easy handles in the stack, you can use curlmultiremovehandle(3) to remove individual easy handles. Remember that easy handles should be curleasycleanup(3)ed. When a transfer within the multi stack has finished, the counter of running transfers (as filled in by curlmultiperform(3)) will decrease. When the number reaches zero, all transfers are done. curlmultiinforead(3) can be used to get information about completed transfers. It then returns the CURLcode for each easy transfer, to allow you to figure out success on each individual transfer. SL, Certificates and Other Tricks [ seeding, passwords, keys, certificates, ENGINE, ca certs ] Sharing Data Between Easy Handles [ fill in ] Footnotes [1] libcurl 7.10.3 and later have the ability to switch over to chunked Transfer-Encoding in cases where HTP uploads are done with data of an unknown size. [2] This happens on Windows machines when libcurl is built and used as a DL. However, you can still do this on Windows if you link with a static library. [3] The curl-config tool is generated at build-time (on UNIX-like systems) and should be installed with the 'make install' or similar instruction that installs the library, header files, man pages etc. [4] This behavior was different in versions before 7.17.0, where strings had to remain valid past the end of the curleasysetopt(3) call. ATRIBUTES See attributes(5) for descriptions of the following attri- butes: libcurl Last change: 17 Nov 2008 27 libcurl programming libcurl-tutorial(3) ATRIBUTE TYPE ATRIBUTE VALUE Availability SUNWcurl Interface Stability Uncommitted NOTES Source for C-URL is available on http:/opensolaris.org. libcurl Last change: 17 Nov 2008 28
OpenSolaris man pages main menu

Contact us      |       About us      |       Term of use      |       Copyright © 2000-2010 MyWebUniversity.com ™