libcurl-tutorial.3 61 KB

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