libcurl-the-guide 50 KB

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