2
0

libcurl-tutorial.3 61 KB

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