libcurl-tutorial.3 60 KB

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