2
0

libcurl-tutorial.3 61 KB

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