libcurl-tutorial.3 61 KB

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