http.c 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, 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 http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifndef CURL_DISABLE_HTTP
  24. #ifdef HAVE_NETINET_IN_H
  25. #include <netinet/in.h>
  26. #endif
  27. #ifdef HAVE_NETDB_H
  28. #include <netdb.h>
  29. #endif
  30. #ifdef HAVE_ARPA_INET_H
  31. #include <arpa/inet.h>
  32. #endif
  33. #ifdef HAVE_NET_IF_H
  34. #include <net/if.h>
  35. #endif
  36. #ifdef HAVE_SYS_IOCTL_H
  37. #include <sys/ioctl.h>
  38. #endif
  39. #ifdef HAVE_SYS_PARAM_H
  40. #include <sys/param.h>
  41. #endif
  42. #include "urldata.h"
  43. #include <curl/curl.h>
  44. #include "transfer.h"
  45. #include "sendf.h"
  46. #include "formdata.h"
  47. #include "progress.h"
  48. #include "curl_base64.h"
  49. #include "cookie.h"
  50. #include "strequal.h"
  51. #include "vtls/vtls.h"
  52. #include "http_digest.h"
  53. #include "curl_ntlm.h"
  54. #include "curl_ntlm_wb.h"
  55. #include "http_negotiate.h"
  56. #include "url.h"
  57. #include "share.h"
  58. #include "hostip.h"
  59. #include "http.h"
  60. #include "curl_memory.h"
  61. #include "select.h"
  62. #include "parsedate.h" /* for the week day and month names */
  63. #include "strtoofft.h"
  64. #include "multiif.h"
  65. #include "rawstr.h"
  66. #include "content_encoding.h"
  67. #include "http_proxy.h"
  68. #include "warnless.h"
  69. #include "non-ascii.h"
  70. #include "bundles.h"
  71. #include "pipeline.h"
  72. #include "http2.h"
  73. #include "connect.h"
  74. #define _MPRINTF_REPLACE /* use our functions only */
  75. #include <curl/mprintf.h>
  76. /* The last #include file should be: */
  77. #include "memdebug.h"
  78. /*
  79. * Forward declarations.
  80. */
  81. static int http_getsock_do(struct connectdata *conn,
  82. curl_socket_t *socks,
  83. int numsocks);
  84. static int http_should_fail(struct connectdata *conn);
  85. #ifdef USE_SSL
  86. static CURLcode https_connecting(struct connectdata *conn, bool *done);
  87. static int https_getsock(struct connectdata *conn,
  88. curl_socket_t *socks,
  89. int numsocks);
  90. #else
  91. #define https_connecting(x,y) CURLE_COULDNT_CONNECT
  92. #endif
  93. /*
  94. * HTTP handler interface.
  95. */
  96. const struct Curl_handler Curl_handler_http = {
  97. "HTTP", /* scheme */
  98. Curl_http_setup_conn, /* setup_connection */
  99. Curl_http, /* do_it */
  100. Curl_http_done, /* done */
  101. ZERO_NULL, /* do_more */
  102. Curl_http_connect, /* connect_it */
  103. ZERO_NULL, /* connecting */
  104. ZERO_NULL, /* doing */
  105. ZERO_NULL, /* proto_getsock */
  106. http_getsock_do, /* doing_getsock */
  107. ZERO_NULL, /* domore_getsock */
  108. ZERO_NULL, /* perform_getsock */
  109. ZERO_NULL, /* disconnect */
  110. ZERO_NULL, /* readwrite */
  111. PORT_HTTP, /* defport */
  112. CURLPROTO_HTTP, /* protocol */
  113. PROTOPT_CREDSPERREQUEST /* flags */
  114. };
  115. #ifdef USE_SSL
  116. /*
  117. * HTTPS handler interface.
  118. */
  119. const struct Curl_handler Curl_handler_https = {
  120. "HTTPS", /* scheme */
  121. Curl_http_setup_conn, /* setup_connection */
  122. Curl_http, /* do_it */
  123. Curl_http_done, /* done */
  124. ZERO_NULL, /* do_more */
  125. Curl_http_connect, /* connect_it */
  126. https_connecting, /* connecting */
  127. ZERO_NULL, /* doing */
  128. https_getsock, /* proto_getsock */
  129. http_getsock_do, /* doing_getsock */
  130. ZERO_NULL, /* domore_getsock */
  131. ZERO_NULL, /* perform_getsock */
  132. ZERO_NULL, /* disconnect */
  133. ZERO_NULL, /* readwrite */
  134. PORT_HTTPS, /* defport */
  135. CURLPROTO_HTTPS, /* protocol */
  136. PROTOPT_SSL | PROTOPT_CREDSPERREQUEST /* flags */
  137. };
  138. #endif
  139. CURLcode Curl_http_setup_conn(struct connectdata *conn)
  140. {
  141. /* allocate the HTTP-specific struct for the SessionHandle, only to survive
  142. during this request */
  143. DEBUGASSERT(conn->data->req.protop == NULL);
  144. conn->data->req.protop = calloc(1, sizeof(struct HTTP));
  145. if(!conn->data->req.protop)
  146. return CURLE_OUT_OF_MEMORY;
  147. return CURLE_OK;
  148. }
  149. /*
  150. * checkheaders() checks the linked list of custom HTTP headers for a
  151. * particular header (prefix).
  152. *
  153. * Returns a pointer to the first matching header or NULL if none matched.
  154. */
  155. char *Curl_checkheaders(const struct connectdata *conn,
  156. const char *thisheader)
  157. {
  158. struct curl_slist *head;
  159. size_t thislen = strlen(thisheader);
  160. struct SessionHandle *data = conn->data;
  161. for(head = data->set.headers;head; head=head->next) {
  162. if(Curl_raw_nequal(head->data, thisheader, thislen))
  163. return head->data;
  164. }
  165. return NULL;
  166. }
  167. /*
  168. * checkProxyHeaders() checks the linked list of custom proxy headers
  169. * if proxy headers are not available, then it will lookup into http header
  170. * link list
  171. *
  172. * It takes a connectdata struct as input instead of the SessionHandle simply
  173. * to know if this is a proxy request or not, as it then might check a
  174. * different header list.
  175. *
  176. */
  177. char *Curl_checkProxyheaders(const struct connectdata *conn,
  178. const char *thisheader)
  179. {
  180. struct curl_slist *head;
  181. size_t thislen = strlen(thisheader);
  182. struct SessionHandle *data = conn->data;
  183. for(head = (conn->bits.proxy && data->set.sep_headers)?
  184. data->set.proxyheaders:data->set.headers;
  185. head; head=head->next) {
  186. if(Curl_raw_nequal(head->data, thisheader, thislen))
  187. return head->data;
  188. }
  189. return NULL;
  190. }
  191. /*
  192. * Strip off leading and trailing whitespace from the value in the
  193. * given HTTP header line and return a strdupped copy. Returns NULL in
  194. * case of allocation failure. Returns an empty string if the header value
  195. * consists entirely of whitespace.
  196. */
  197. char *Curl_copy_header_value(const char *header)
  198. {
  199. const char *start;
  200. const char *end;
  201. char *value;
  202. size_t len;
  203. DEBUGASSERT(header);
  204. /* Find the end of the header name */
  205. while(*header && (*header != ':'))
  206. ++header;
  207. if(*header)
  208. /* Skip over colon */
  209. ++header;
  210. /* Find the first non-space letter */
  211. start = header;
  212. while(*start && ISSPACE(*start))
  213. start++;
  214. /* data is in the host encoding so
  215. use '\r' and '\n' instead of 0x0d and 0x0a */
  216. end = strchr(start, '\r');
  217. if(!end)
  218. end = strchr(start, '\n');
  219. if(!end)
  220. end = strchr(start, '\0');
  221. if(!end)
  222. return NULL;
  223. /* skip all trailing space letters */
  224. while((end > start) && ISSPACE(*end))
  225. end--;
  226. /* get length of the type */
  227. len = end - start + 1;
  228. value = malloc(len + 1);
  229. if(!value)
  230. return NULL;
  231. memcpy(value, start, len);
  232. value[len] = 0; /* zero terminate */
  233. return value;
  234. }
  235. /*
  236. * http_output_basic() sets up an Authorization: header (or the proxy version)
  237. * for HTTP Basic authentication.
  238. *
  239. * Returns CURLcode.
  240. */
  241. static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
  242. {
  243. size_t size = 0;
  244. char *authorization = NULL;
  245. struct SessionHandle *data = conn->data;
  246. char **userp;
  247. const char *user;
  248. const char *pwd;
  249. CURLcode error;
  250. if(proxy) {
  251. userp = &conn->allocptr.proxyuserpwd;
  252. user = conn->proxyuser;
  253. pwd = conn->proxypasswd;
  254. }
  255. else {
  256. userp = &conn->allocptr.userpwd;
  257. user = conn->user;
  258. pwd = conn->passwd;
  259. }
  260. snprintf(data->state.buffer, sizeof(data->state.buffer), "%s:%s", user, pwd);
  261. error = Curl_base64_encode(data,
  262. data->state.buffer, strlen(data->state.buffer),
  263. &authorization, &size);
  264. if(error)
  265. return error;
  266. if(!authorization)
  267. return CURLE_REMOTE_ACCESS_DENIED;
  268. Curl_safefree(*userp);
  269. *userp = aprintf("%sAuthorization: Basic %s\r\n",
  270. proxy?"Proxy-":"",
  271. authorization);
  272. free(authorization);
  273. if(!*userp)
  274. return CURLE_OUT_OF_MEMORY;
  275. return CURLE_OK;
  276. }
  277. /* pickoneauth() selects the most favourable authentication method from the
  278. * ones available and the ones we want.
  279. *
  280. * return TRUE if one was picked
  281. */
  282. static bool pickoneauth(struct auth *pick)
  283. {
  284. bool picked;
  285. /* only deal with authentication we want */
  286. unsigned long avail = pick->avail & pick->want;
  287. picked = TRUE;
  288. /* The order of these checks is highly relevant, as this will be the order
  289. of preference in case of the existence of multiple accepted types. */
  290. if(avail & CURLAUTH_NEGOTIATE)
  291. pick->picked = CURLAUTH_NEGOTIATE;
  292. else if(avail & CURLAUTH_DIGEST)
  293. pick->picked = CURLAUTH_DIGEST;
  294. else if(avail & CURLAUTH_NTLM)
  295. pick->picked = CURLAUTH_NTLM;
  296. else if(avail & CURLAUTH_NTLM_WB)
  297. pick->picked = CURLAUTH_NTLM_WB;
  298. else if(avail & CURLAUTH_BASIC)
  299. pick->picked = CURLAUTH_BASIC;
  300. else {
  301. pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
  302. picked = FALSE;
  303. }
  304. pick->avail = CURLAUTH_NONE; /* clear it here */
  305. return picked;
  306. }
  307. /*
  308. * Curl_http_perhapsrewind()
  309. *
  310. * If we are doing POST or PUT {
  311. * If we have more data to send {
  312. * If we are doing NTLM {
  313. * Keep sending since we must not disconnect
  314. * }
  315. * else {
  316. * If there is more than just a little data left to send, close
  317. * the current connection by force.
  318. * }
  319. * }
  320. * If we have sent any data {
  321. * If we don't have track of all the data {
  322. * call app to tell it to rewind
  323. * }
  324. * else {
  325. * rewind internally so that the operation can restart fine
  326. * }
  327. * }
  328. * }
  329. */
  330. static CURLcode http_perhapsrewind(struct connectdata *conn)
  331. {
  332. struct SessionHandle *data = conn->data;
  333. struct HTTP *http = data->req.protop;
  334. curl_off_t bytessent;
  335. curl_off_t expectsend = -1; /* default is unknown */
  336. if(!http)
  337. /* If this is still NULL, we have not reach very far and we can safely
  338. skip this rewinding stuff */
  339. return CURLE_OK;
  340. switch(data->set.httpreq) {
  341. case HTTPREQ_GET:
  342. case HTTPREQ_HEAD:
  343. return CURLE_OK;
  344. default:
  345. break;
  346. }
  347. bytessent = http->writebytecount;
  348. if(conn->bits.authneg)
  349. /* This is a state where we are known to be negotiating and we don't send
  350. any data then. */
  351. expectsend = 0;
  352. else {
  353. /* figure out how much data we are expected to send */
  354. switch(data->set.httpreq) {
  355. case HTTPREQ_POST:
  356. if(data->set.postfieldsize != -1)
  357. expectsend = data->set.postfieldsize;
  358. else if(data->set.postfields)
  359. expectsend = (curl_off_t)strlen(data->set.postfields);
  360. break;
  361. case HTTPREQ_PUT:
  362. if(data->state.infilesize != -1)
  363. expectsend = data->state.infilesize;
  364. break;
  365. case HTTPREQ_POST_FORM:
  366. expectsend = http->postsize;
  367. break;
  368. default:
  369. break;
  370. }
  371. }
  372. conn->bits.rewindaftersend = FALSE; /* default */
  373. if((expectsend == -1) || (expectsend > bytessent)) {
  374. /* There is still data left to send */
  375. if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
  376. (data->state.authhost.picked == CURLAUTH_NTLM) ||
  377. (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
  378. (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
  379. if(((expectsend - bytessent) < 2000) ||
  380. (conn->ntlm.state != NTLMSTATE_NONE) ||
  381. (conn->proxyntlm.state != NTLMSTATE_NONE)) {
  382. /* The NTLM-negotiation has started *OR* there is just a little (<2K)
  383. data left to send, keep on sending. */
  384. /* rewind data when completely done sending! */
  385. if(!conn->bits.authneg) {
  386. conn->bits.rewindaftersend = TRUE;
  387. infof(data, "Rewind stream after send\n");
  388. }
  389. return CURLE_OK;
  390. }
  391. if(conn->bits.close)
  392. /* this is already marked to get closed */
  393. return CURLE_OK;
  394. infof(data, "NTLM send, close instead of sending %"
  395. CURL_FORMAT_CURL_OFF_T " bytes\n",
  396. (curl_off_t)(expectsend - bytessent));
  397. }
  398. /* This is not NTLM or many bytes left to send: close
  399. */
  400. connclose(conn, "Mid-auth HTTP and much data left to send");
  401. data->req.size = 0; /* don't download any more than 0 bytes */
  402. /* There still is data left to send, but this connection is marked for
  403. closure so we can safely do the rewind right now */
  404. }
  405. if(bytessent)
  406. /* we rewind now at once since if we already sent something */
  407. return Curl_readrewind(conn);
  408. return CURLE_OK;
  409. }
  410. /*
  411. * Curl_http_auth_act() gets called when all HTTP headers have been received
  412. * and it checks what authentication methods that are available and decides
  413. * which one (if any) to use. It will set 'newurl' if an auth method was
  414. * picked.
  415. */
  416. CURLcode Curl_http_auth_act(struct connectdata *conn)
  417. {
  418. struct SessionHandle *data = conn->data;
  419. bool pickhost = FALSE;
  420. bool pickproxy = FALSE;
  421. CURLcode code = CURLE_OK;
  422. if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
  423. /* this is a transient response code, ignore */
  424. return CURLE_OK;
  425. if(data->state.authproblem)
  426. return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
  427. if(conn->bits.user_passwd &&
  428. ((data->req.httpcode == 401) ||
  429. (conn->bits.authneg && data->req.httpcode < 300))) {
  430. pickhost = pickoneauth(&data->state.authhost);
  431. if(!pickhost)
  432. data->state.authproblem = TRUE;
  433. }
  434. if(conn->bits.proxy_user_passwd &&
  435. ((data->req.httpcode == 407) ||
  436. (conn->bits.authneg && data->req.httpcode < 300))) {
  437. pickproxy = pickoneauth(&data->state.authproxy);
  438. if(!pickproxy)
  439. data->state.authproblem = TRUE;
  440. }
  441. if(pickhost || pickproxy) {
  442. /* In case this is GSS auth, the newurl field is already allocated so
  443. we must make sure to free it before allocating a new one. As figured
  444. out in bug #2284386 */
  445. Curl_safefree(data->req.newurl);
  446. data->req.newurl = strdup(data->change.url); /* clone URL */
  447. if(!data->req.newurl)
  448. return CURLE_OUT_OF_MEMORY;
  449. if((data->set.httpreq != HTTPREQ_GET) &&
  450. (data->set.httpreq != HTTPREQ_HEAD) &&
  451. !conn->bits.rewindaftersend) {
  452. code = http_perhapsrewind(conn);
  453. if(code)
  454. return code;
  455. }
  456. }
  457. else if((data->req.httpcode < 300) &&
  458. (!data->state.authhost.done) &&
  459. conn->bits.authneg) {
  460. /* no (known) authentication available,
  461. authentication is not "done" yet and
  462. no authentication seems to be required and
  463. we didn't try HEAD or GET */
  464. if((data->set.httpreq != HTTPREQ_GET) &&
  465. (data->set.httpreq != HTTPREQ_HEAD)) {
  466. data->req.newurl = strdup(data->change.url); /* clone URL */
  467. if(!data->req.newurl)
  468. return CURLE_OUT_OF_MEMORY;
  469. data->state.authhost.done = TRUE;
  470. }
  471. }
  472. if(http_should_fail(conn)) {
  473. failf (data, "The requested URL returned error: %d",
  474. data->req.httpcode);
  475. code = CURLE_HTTP_RETURNED_ERROR;
  476. }
  477. return code;
  478. }
  479. /*
  480. * Output the correct authentication header depending on the auth type
  481. * and whether or not it is to a proxy.
  482. */
  483. static CURLcode
  484. output_auth_headers(struct connectdata *conn,
  485. struct auth *authstatus,
  486. const char *request,
  487. const char *path,
  488. bool proxy)
  489. {
  490. struct SessionHandle *data = conn->data;
  491. const char *auth=NULL;
  492. CURLcode result = CURLE_OK;
  493. #ifdef USE_SPNEGO
  494. struct negotiatedata *negdata = proxy?
  495. &data->state.proxyneg:&data->state.negotiate;
  496. #endif
  497. #ifdef CURL_DISABLE_CRYPTO_AUTH
  498. (void)request;
  499. (void)path;
  500. #endif
  501. #ifdef USE_SPNEGO
  502. negdata->state = GSS_AUTHNONE;
  503. if((authstatus->picked == CURLAUTH_NEGOTIATE) &&
  504. negdata->context && !GSS_ERROR(negdata->status)) {
  505. auth="Negotiate";
  506. result = Curl_output_negotiate(conn, proxy);
  507. if(result)
  508. return result;
  509. authstatus->done = TRUE;
  510. negdata->state = GSS_AUTHSENT;
  511. }
  512. else
  513. #endif
  514. #ifdef USE_NTLM
  515. if(authstatus->picked == CURLAUTH_NTLM) {
  516. auth="NTLM";
  517. result = Curl_output_ntlm(conn, proxy);
  518. if(result)
  519. return result;
  520. }
  521. else
  522. #endif
  523. #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
  524. if(authstatus->picked == CURLAUTH_NTLM_WB) {
  525. auth="NTLM_WB";
  526. result = Curl_output_ntlm_wb(conn, proxy);
  527. if(result)
  528. return result;
  529. }
  530. else
  531. #endif
  532. #ifndef CURL_DISABLE_CRYPTO_AUTH
  533. if(authstatus->picked == CURLAUTH_DIGEST) {
  534. auth="Digest";
  535. result = Curl_output_digest(conn,
  536. proxy,
  537. (const unsigned char *)request,
  538. (const unsigned char *)path);
  539. if(result)
  540. return result;
  541. }
  542. else
  543. #endif
  544. if(authstatus->picked == CURLAUTH_BASIC) {
  545. /* Basic */
  546. if((proxy && conn->bits.proxy_user_passwd &&
  547. !Curl_checkProxyheaders(conn, "Proxy-authorization:")) ||
  548. (!proxy && conn->bits.user_passwd &&
  549. !Curl_checkheaders(conn, "Authorization:"))) {
  550. auth="Basic";
  551. result = http_output_basic(conn, proxy);
  552. if(result)
  553. return result;
  554. }
  555. /* NOTE: this function should set 'done' TRUE, as the other auth
  556. functions work that way */
  557. authstatus->done = TRUE;
  558. }
  559. if(auth) {
  560. infof(data, "%s auth using %s with user '%s'\n",
  561. proxy?"Proxy":"Server", auth,
  562. proxy?(conn->proxyuser?conn->proxyuser:""):
  563. (conn->user?conn->user:""));
  564. authstatus->multi = (!authstatus->done) ? TRUE : FALSE;
  565. }
  566. else
  567. authstatus->multi = FALSE;
  568. return CURLE_OK;
  569. }
  570. /**
  571. * Curl_http_output_auth() setups the authentication headers for the
  572. * host/proxy and the correct authentication
  573. * method. conn->data->state.authdone is set to TRUE when authentication is
  574. * done.
  575. *
  576. * @param conn all information about the current connection
  577. * @param request pointer to the request keyword
  578. * @param path pointer to the requested path
  579. * @param proxytunnel boolean if this is the request setting up a "proxy
  580. * tunnel"
  581. *
  582. * @returns CURLcode
  583. */
  584. CURLcode
  585. Curl_http_output_auth(struct connectdata *conn,
  586. const char *request,
  587. const char *path,
  588. bool proxytunnel) /* TRUE if this is the request setting
  589. up the proxy tunnel */
  590. {
  591. CURLcode result = CURLE_OK;
  592. struct SessionHandle *data = conn->data;
  593. struct auth *authhost;
  594. struct auth *authproxy;
  595. DEBUGASSERT(data);
  596. authhost = &data->state.authhost;
  597. authproxy = &data->state.authproxy;
  598. if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
  599. conn->bits.user_passwd)
  600. /* continue please */ ;
  601. else {
  602. authhost->done = TRUE;
  603. authproxy->done = TRUE;
  604. return CURLE_OK; /* no authentication with no user or password */
  605. }
  606. if(authhost->want && !authhost->picked)
  607. /* The app has selected one or more methods, but none has been picked
  608. so far by a server round-trip. Then we set the picked one to the
  609. want one, and if this is one single bit it'll be used instantly. */
  610. authhost->picked = authhost->want;
  611. if(authproxy->want && !authproxy->picked)
  612. /* The app has selected one or more methods, but none has been picked so
  613. far by a proxy round-trip. Then we set the picked one to the want one,
  614. and if this is one single bit it'll be used instantly. */
  615. authproxy->picked = authproxy->want;
  616. #ifndef CURL_DISABLE_PROXY
  617. /* Send proxy authentication header if needed */
  618. if(conn->bits.httpproxy &&
  619. (conn->bits.tunnel_proxy == proxytunnel)) {
  620. result = output_auth_headers(conn, authproxy, request, path, TRUE);
  621. if(result)
  622. return result;
  623. }
  624. else
  625. #else
  626. (void)proxytunnel;
  627. #endif /* CURL_DISABLE_PROXY */
  628. /* we have no proxy so let's pretend we're done authenticating
  629. with it */
  630. authproxy->done = TRUE;
  631. /* To prevent the user+password to get sent to other than the original
  632. host due to a location-follow, we do some weirdo checks here */
  633. if(!data->state.this_is_a_follow ||
  634. conn->bits.netrc ||
  635. !data->state.first_host ||
  636. data->set.http_disable_hostname_check_before_authentication ||
  637. Curl_raw_equal(data->state.first_host, conn->host.name)) {
  638. result = output_auth_headers(conn, authhost, request, path, FALSE);
  639. }
  640. else
  641. authhost->done = TRUE;
  642. return result;
  643. }
  644. /*
  645. * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
  646. * headers. They are dealt with both in the transfer.c main loop and in the
  647. * proxy CONNECT loop.
  648. */
  649. CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
  650. const char *auth) /* the first non-space */
  651. {
  652. /*
  653. * This resource requires authentication
  654. */
  655. struct SessionHandle *data = conn->data;
  656. #ifdef USE_SPNEGO
  657. struct negotiatedata *negdata = proxy?
  658. &data->state.proxyneg:&data->state.negotiate;
  659. #endif
  660. unsigned long *availp;
  661. struct auth *authp;
  662. if(proxy) {
  663. availp = &data->info.proxyauthavail;
  664. authp = &data->state.authproxy;
  665. }
  666. else {
  667. availp = &data->info.httpauthavail;
  668. authp = &data->state.authhost;
  669. }
  670. /*
  671. * Here we check if we want the specific single authentication (using ==) and
  672. * if we do, we initiate usage of it.
  673. *
  674. * If the provided authentication is wanted as one out of several accepted
  675. * types (using &), we OR this authentication type to the authavail
  676. * variable.
  677. *
  678. * Note:
  679. *
  680. * ->picked is first set to the 'want' value (one or more bits) before the
  681. * request is sent, and then it is again set _after_ all response 401/407
  682. * headers have been received but then only to a single preferred method
  683. * (bit).
  684. *
  685. */
  686. while(*auth) {
  687. #ifdef USE_SPNEGO
  688. if(checkprefix("Negotiate", auth)) {
  689. int neg;
  690. *availp |= CURLAUTH_NEGOTIATE;
  691. authp->avail |= CURLAUTH_NEGOTIATE;
  692. if(authp->picked == CURLAUTH_NEGOTIATE) {
  693. if(negdata->state == GSS_AUTHSENT || negdata->state == GSS_AUTHNONE) {
  694. neg = Curl_input_negotiate(conn, proxy, auth);
  695. if(neg == 0) {
  696. DEBUGASSERT(!data->req.newurl);
  697. data->req.newurl = strdup(data->change.url);
  698. if(!data->req.newurl)
  699. return CURLE_OUT_OF_MEMORY;
  700. data->state.authproblem = FALSE;
  701. /* we received a GSS auth token and we dealt with it fine */
  702. negdata->state = GSS_AUTHRECV;
  703. }
  704. else
  705. data->state.authproblem = TRUE;
  706. }
  707. }
  708. }
  709. else
  710. #endif
  711. #ifdef USE_NTLM
  712. /* NTLM support requires the SSL crypto libs */
  713. if(checkprefix("NTLM", auth)) {
  714. *availp |= CURLAUTH_NTLM;
  715. authp->avail |= CURLAUTH_NTLM;
  716. if(authp->picked == CURLAUTH_NTLM ||
  717. authp->picked == CURLAUTH_NTLM_WB) {
  718. /* NTLM authentication is picked and activated */
  719. CURLcode ntlm =
  720. Curl_input_ntlm(conn, proxy, auth);
  721. if(CURLE_OK == ntlm) {
  722. data->state.authproblem = FALSE;
  723. #ifdef NTLM_WB_ENABLED
  724. if(authp->picked == CURLAUTH_NTLM_WB) {
  725. *availp &= ~CURLAUTH_NTLM;
  726. authp->avail &= ~CURLAUTH_NTLM;
  727. *availp |= CURLAUTH_NTLM_WB;
  728. authp->avail |= CURLAUTH_NTLM_WB;
  729. /* Get the challenge-message which will be passed to
  730. * ntlm_auth for generating the type 3 message later */
  731. while(*auth && ISSPACE(*auth))
  732. auth++;
  733. if(checkprefix("NTLM", auth)) {
  734. auth += strlen("NTLM");
  735. while(*auth && ISSPACE(*auth))
  736. auth++;
  737. if(*auth)
  738. if((conn->challenge_header = strdup(auth)) == NULL)
  739. return CURLE_OUT_OF_MEMORY;
  740. }
  741. }
  742. #endif
  743. }
  744. else {
  745. infof(data, "Authentication problem. Ignoring this.\n");
  746. data->state.authproblem = TRUE;
  747. }
  748. }
  749. }
  750. else
  751. #endif
  752. #ifndef CURL_DISABLE_CRYPTO_AUTH
  753. if(checkprefix("Digest", auth)) {
  754. if((authp->avail & CURLAUTH_DIGEST) != 0) {
  755. infof(data, "Ignoring duplicate digest auth header.\n");
  756. }
  757. else {
  758. CURLdigest dig;
  759. *availp |= CURLAUTH_DIGEST;
  760. authp->avail |= CURLAUTH_DIGEST;
  761. /* We call this function on input Digest headers even if Digest
  762. * authentication isn't activated yet, as we need to store the
  763. * incoming data from this header in case we are gonna use
  764. * Digest. */
  765. dig = Curl_input_digest(conn, proxy, auth);
  766. if(CURLDIGEST_FINE != dig) {
  767. infof(data, "Authentication problem. Ignoring this.\n");
  768. data->state.authproblem = TRUE;
  769. }
  770. }
  771. }
  772. else
  773. #endif
  774. if(checkprefix("Basic", auth)) {
  775. *availp |= CURLAUTH_BASIC;
  776. authp->avail |= CURLAUTH_BASIC;
  777. if(authp->picked == CURLAUTH_BASIC) {
  778. /* We asked for Basic authentication but got a 40X back
  779. anyway, which basically means our name+password isn't
  780. valid. */
  781. authp->avail = CURLAUTH_NONE;
  782. infof(data, "Authentication problem. Ignoring this.\n");
  783. data->state.authproblem = TRUE;
  784. }
  785. }
  786. /* there may be multiple methods on one line, so keep reading */
  787. while(*auth && *auth != ',') /* read up to the next comma */
  788. auth++;
  789. if(*auth == ',') /* if we're on a comma, skip it */
  790. auth++;
  791. while(*auth && ISSPACE(*auth))
  792. auth++;
  793. }
  794. return CURLE_OK;
  795. }
  796. /**
  797. * http_should_fail() determines whether an HTTP response has gotten us
  798. * into an error state or not.
  799. *
  800. * @param conn all information about the current connection
  801. *
  802. * @retval 0 communications should continue
  803. *
  804. * @retval 1 communications should not continue
  805. */
  806. static int http_should_fail(struct connectdata *conn)
  807. {
  808. struct SessionHandle *data;
  809. int httpcode;
  810. DEBUGASSERT(conn);
  811. data = conn->data;
  812. DEBUGASSERT(data);
  813. httpcode = data->req.httpcode;
  814. /*
  815. ** If we haven't been asked to fail on error,
  816. ** don't fail.
  817. */
  818. if(!data->set.http_fail_on_error)
  819. return 0;
  820. /*
  821. ** Any code < 400 is never terminal.
  822. */
  823. if(httpcode < 400)
  824. return 0;
  825. /*
  826. ** Any code >= 400 that's not 401 or 407 is always
  827. ** a terminal error
  828. */
  829. if((httpcode != 401) &&
  830. (httpcode != 407))
  831. return 1;
  832. /*
  833. ** All we have left to deal with is 401 and 407
  834. */
  835. DEBUGASSERT((httpcode == 401) || (httpcode == 407));
  836. /*
  837. ** Examine the current authentication state to see if this
  838. ** is an error. The idea is for this function to get
  839. ** called after processing all the headers in a response
  840. ** message. So, if we've been to asked to authenticate a
  841. ** particular stage, and we've done it, we're OK. But, if
  842. ** we're already completely authenticated, it's not OK to
  843. ** get another 401 or 407.
  844. **
  845. ** It is possible for authentication to go stale such that
  846. ** the client needs to reauthenticate. Once that info is
  847. ** available, use it here.
  848. */
  849. /*
  850. ** Either we're not authenticating, or we're supposed to
  851. ** be authenticating something else. This is an error.
  852. */
  853. if((httpcode == 401) && !conn->bits.user_passwd)
  854. return TRUE;
  855. if((httpcode == 407) && !conn->bits.proxy_user_passwd)
  856. return TRUE;
  857. return data->state.authproblem;
  858. }
  859. /*
  860. * readmoredata() is a "fread() emulation" to provide POST and/or request
  861. * data. It is used when a huge POST is to be made and the entire chunk wasn't
  862. * sent in the first send(). This function will then be called from the
  863. * transfer.c loop when more data is to be sent to the peer.
  864. *
  865. * Returns the amount of bytes it filled the buffer with.
  866. */
  867. static size_t readmoredata(char *buffer,
  868. size_t size,
  869. size_t nitems,
  870. void *userp)
  871. {
  872. struct connectdata *conn = (struct connectdata *)userp;
  873. struct HTTP *http = conn->data->req.protop;
  874. size_t fullsize = size * nitems;
  875. if(0 == http->postsize)
  876. /* nothing to return */
  877. return 0;
  878. /* make sure that a HTTP request is never sent away chunked! */
  879. conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
  880. if(http->postsize <= (curl_off_t)fullsize) {
  881. memcpy(buffer, http->postdata, (size_t)http->postsize);
  882. fullsize = (size_t)http->postsize;
  883. if(http->backup.postsize) {
  884. /* move backup data into focus and continue on that */
  885. http->postdata = http->backup.postdata;
  886. http->postsize = http->backup.postsize;
  887. conn->fread_func = http->backup.fread_func;
  888. conn->fread_in = http->backup.fread_in;
  889. http->sending++; /* move one step up */
  890. http->backup.postsize=0;
  891. }
  892. else
  893. http->postsize = 0;
  894. return fullsize;
  895. }
  896. memcpy(buffer, http->postdata, fullsize);
  897. http->postdata += fullsize;
  898. http->postsize -= fullsize;
  899. return fullsize;
  900. }
  901. /* ------------------------------------------------------------------------- */
  902. /* add_buffer functions */
  903. /*
  904. * Curl_add_buffer_init() sets up and returns a fine buffer struct
  905. */
  906. Curl_send_buffer *Curl_add_buffer_init(void)
  907. {
  908. return calloc(1, sizeof(Curl_send_buffer));
  909. }
  910. /*
  911. * Curl_add_buffer_send() sends a header buffer and frees all associated
  912. * memory. Body data may be appended to the header data if desired.
  913. *
  914. * Returns CURLcode
  915. */
  916. CURLcode Curl_add_buffer_send(Curl_send_buffer *in,
  917. struct connectdata *conn,
  918. /* add the number of sent bytes to this
  919. counter */
  920. long *bytes_written,
  921. /* how much of the buffer contains body data */
  922. size_t included_body_bytes,
  923. int socketindex)
  924. {
  925. ssize_t amount;
  926. CURLcode res;
  927. char *ptr;
  928. size_t size;
  929. struct HTTP *http = conn->data->req.protop;
  930. size_t sendsize;
  931. curl_socket_t sockfd;
  932. size_t headersize;
  933. DEBUGASSERT(socketindex <= SECONDARYSOCKET);
  934. sockfd = conn->sock[socketindex];
  935. /* The looping below is required since we use non-blocking sockets, but due
  936. to the circumstances we will just loop and try again and again etc */
  937. ptr = in->buffer;
  938. size = in->size_used;
  939. headersize = size - included_body_bytes; /* the initial part that isn't body
  940. is header */
  941. DEBUGASSERT(size > included_body_bytes);
  942. res = Curl_convert_to_network(conn->data, ptr, headersize);
  943. /* Curl_convert_to_network calls failf if unsuccessful */
  944. if(res) {
  945. /* conversion failed, free memory and return to the caller */
  946. if(in->buffer)
  947. free(in->buffer);
  948. free(in);
  949. return res;
  950. }
  951. if(conn->handler->flags & PROTOPT_SSL) {
  952. /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
  953. when we speak HTTPS, as if only a fraction of it is sent now, this data
  954. needs to fit into the normal read-callback buffer later on and that
  955. buffer is using this size.
  956. */
  957. sendsize= (size > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:size;
  958. /* OpenSSL is very picky and we must send the SAME buffer pointer to the
  959. library when we attempt to re-send this buffer. Sending the same data
  960. is not enough, we must use the exact same address. For this reason, we
  961. must copy the data to the uploadbuffer first, since that is the buffer
  962. we will be using if this send is retried later.
  963. */
  964. memcpy(conn->data->state.uploadbuffer, ptr, sendsize);
  965. ptr = conn->data->state.uploadbuffer;
  966. }
  967. else
  968. sendsize = size;
  969. res = Curl_write(conn, sockfd, ptr, sendsize, &amount);
  970. if(CURLE_OK == res) {
  971. /*
  972. * Note that we may not send the entire chunk at once, and we have a set
  973. * number of data bytes at the end of the big buffer (out of which we may
  974. * only send away a part).
  975. */
  976. /* how much of the header that was sent */
  977. size_t headlen = (size_t)amount>headersize?headersize:(size_t)amount;
  978. size_t bodylen = amount - headlen;
  979. if(conn->data->set.verbose) {
  980. /* this data _may_ contain binary stuff */
  981. Curl_debug(conn->data, CURLINFO_HEADER_OUT, ptr, headlen, conn);
  982. if(bodylen) {
  983. /* there was body data sent beyond the initial header part, pass that
  984. on to the debug callback too */
  985. Curl_debug(conn->data, CURLINFO_DATA_OUT,
  986. ptr+headlen, bodylen, conn);
  987. }
  988. }
  989. if(bodylen)
  990. /* since we sent a piece of the body here, up the byte counter for it
  991. accordingly */
  992. http->writebytecount += bodylen;
  993. /* 'amount' can never be a very large value here so typecasting it so a
  994. signed 31 bit value should not cause problems even if ssize_t is
  995. 64bit */
  996. *bytes_written += (long)amount;
  997. if(http) {
  998. if((size_t)amount != size) {
  999. /* The whole request could not be sent in one system call. We must
  1000. queue it up and send it later when we get the chance. We must not
  1001. loop here and wait until it might work again. */
  1002. size -= amount;
  1003. ptr = in->buffer + amount;
  1004. /* backup the currently set pointers */
  1005. http->backup.fread_func = conn->fread_func;
  1006. http->backup.fread_in = conn->fread_in;
  1007. http->backup.postdata = http->postdata;
  1008. http->backup.postsize = http->postsize;
  1009. /* set the new pointers for the request-sending */
  1010. conn->fread_func = (curl_read_callback)readmoredata;
  1011. conn->fread_in = (void *)conn;
  1012. http->postdata = ptr;
  1013. http->postsize = (curl_off_t)size;
  1014. http->send_buffer = in;
  1015. http->sending = HTTPSEND_REQUEST;
  1016. return CURLE_OK;
  1017. }
  1018. http->sending = HTTPSEND_BODY;
  1019. /* the full buffer was sent, clean up and return */
  1020. }
  1021. else {
  1022. if((size_t)amount != size)
  1023. /* We have no continue-send mechanism now, fail. This can only happen
  1024. when this function is used from the CONNECT sending function. We
  1025. currently (stupidly) assume that the whole request is always sent
  1026. away in the first single chunk.
  1027. This needs FIXing.
  1028. */
  1029. return CURLE_SEND_ERROR;
  1030. else
  1031. conn->writechannel_inuse = FALSE;
  1032. }
  1033. }
  1034. if(in->buffer)
  1035. free(in->buffer);
  1036. free(in);
  1037. return res;
  1038. }
  1039. /*
  1040. * add_bufferf() add the formatted input to the buffer.
  1041. */
  1042. CURLcode Curl_add_bufferf(Curl_send_buffer *in, const char *fmt, ...)
  1043. {
  1044. char *s;
  1045. va_list ap;
  1046. va_start(ap, fmt);
  1047. s = vaprintf(fmt, ap); /* this allocs a new string to append */
  1048. va_end(ap);
  1049. if(s) {
  1050. CURLcode result = Curl_add_buffer(in, s, strlen(s));
  1051. free(s);
  1052. return result;
  1053. }
  1054. /* If we failed, we cleanup the whole buffer and return error */
  1055. if(in->buffer)
  1056. free(in->buffer);
  1057. free(in);
  1058. return CURLE_OUT_OF_MEMORY;
  1059. }
  1060. /*
  1061. * add_buffer() appends a memory chunk to the existing buffer
  1062. */
  1063. CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size)
  1064. {
  1065. char *new_rb;
  1066. size_t new_size;
  1067. if(~size < in->size_used) {
  1068. /* If resulting used size of send buffer would wrap size_t, cleanup
  1069. the whole buffer and return error. Otherwise the required buffer
  1070. size will fit into a single allocatable memory chunk */
  1071. Curl_safefree(in->buffer);
  1072. free(in);
  1073. return CURLE_OUT_OF_MEMORY;
  1074. }
  1075. if(!in->buffer ||
  1076. ((in->size_used + size) > (in->size_max - 1))) {
  1077. /* If current buffer size isn't enough to hold the result, use a
  1078. buffer size that doubles the required size. If this new size
  1079. would wrap size_t, then just use the largest possible one */
  1080. if((size > (size_t)-1/2) || (in->size_used > (size_t)-1/2) ||
  1081. (~(size*2) < (in->size_used*2)))
  1082. new_size = (size_t)-1;
  1083. else
  1084. new_size = (in->size_used+size)*2;
  1085. if(in->buffer)
  1086. /* we have a buffer, enlarge the existing one */
  1087. new_rb = realloc(in->buffer, new_size);
  1088. else
  1089. /* create a new buffer */
  1090. new_rb = malloc(new_size);
  1091. if(!new_rb) {
  1092. /* If we failed, we cleanup the whole buffer and return error */
  1093. Curl_safefree(in->buffer);
  1094. free(in);
  1095. return CURLE_OUT_OF_MEMORY;
  1096. }
  1097. in->buffer = new_rb;
  1098. in->size_max = new_size;
  1099. }
  1100. memcpy(&in->buffer[in->size_used], inptr, size);
  1101. in->size_used += size;
  1102. return CURLE_OK;
  1103. }
  1104. /* end of the add_buffer functions */
  1105. /* ------------------------------------------------------------------------- */
  1106. /*
  1107. * Curl_compareheader()
  1108. *
  1109. * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
  1110. * Pass headers WITH the colon.
  1111. */
  1112. bool
  1113. Curl_compareheader(const char *headerline, /* line to check */
  1114. const char *header, /* header keyword _with_ colon */
  1115. const char *content) /* content string to find */
  1116. {
  1117. /* RFC2616, section 4.2 says: "Each header field consists of a name followed
  1118. * by a colon (":") and the field value. Field names are case-insensitive.
  1119. * The field value MAY be preceded by any amount of LWS, though a single SP
  1120. * is preferred." */
  1121. size_t hlen = strlen(header);
  1122. size_t clen;
  1123. size_t len;
  1124. const char *start;
  1125. const char *end;
  1126. if(!Curl_raw_nequal(headerline, header, hlen))
  1127. return FALSE; /* doesn't start with header */
  1128. /* pass the header */
  1129. start = &headerline[hlen];
  1130. /* pass all white spaces */
  1131. while(*start && ISSPACE(*start))
  1132. start++;
  1133. /* find the end of the header line */
  1134. end = strchr(start, '\r'); /* lines end with CRLF */
  1135. if(!end) {
  1136. /* in case there's a non-standard compliant line here */
  1137. end = strchr(start, '\n');
  1138. if(!end)
  1139. /* hm, there's no line ending here, use the zero byte! */
  1140. end = strchr(start, '\0');
  1141. }
  1142. len = end-start; /* length of the content part of the input line */
  1143. clen = strlen(content); /* length of the word to find */
  1144. /* find the content string in the rest of the line */
  1145. for(;len>=clen;len--, start++) {
  1146. if(Curl_raw_nequal(start, content, clen))
  1147. return TRUE; /* match! */
  1148. }
  1149. return FALSE; /* no match */
  1150. }
  1151. /*
  1152. * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
  1153. * the generic Curl_connect().
  1154. */
  1155. CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
  1156. {
  1157. CURLcode result;
  1158. /* We default to persistent connections. We set this already in this connect
  1159. function to make the re-use checks properly be able to check this bit. */
  1160. connkeep(conn, "HTTP default");
  1161. /* the CONNECT procedure might not have been completed */
  1162. result = Curl_proxy_connect(conn);
  1163. if(result)
  1164. return result;
  1165. if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
  1166. /* nothing else to do except wait right now - we're not done here. */
  1167. return CURLE_OK;
  1168. if(conn->given->flags & PROTOPT_SSL) {
  1169. /* perform SSL initialization */
  1170. result = https_connecting(conn, done);
  1171. if(result)
  1172. return result;
  1173. }
  1174. else
  1175. *done = TRUE;
  1176. return CURLE_OK;
  1177. }
  1178. /* this returns the socket to wait for in the DO and DOING state for the multi
  1179. interface and then we're always _sending_ a request and thus we wait for
  1180. the single socket to become writable only */
  1181. static int http_getsock_do(struct connectdata *conn,
  1182. curl_socket_t *socks,
  1183. int numsocks)
  1184. {
  1185. /* write mode */
  1186. (void)numsocks; /* unused, we trust it to be at least 1 */
  1187. socks[0] = conn->sock[FIRSTSOCKET];
  1188. return GETSOCK_WRITESOCK(0);
  1189. }
  1190. #ifdef USE_SSL
  1191. static CURLcode https_connecting(struct connectdata *conn, bool *done)
  1192. {
  1193. CURLcode result;
  1194. DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
  1195. /* perform SSL initialization for this socket */
  1196. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
  1197. if(result)
  1198. connclose(conn, "Failed HTTPS connection");
  1199. return result;
  1200. }
  1201. #endif
  1202. #if defined(USE_SSLEAY) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
  1203. defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS)
  1204. /* This function is for OpenSSL, GnuTLS, darwinssl, schannel and polarssl only.
  1205. It should be made to query the generic SSL layer instead. */
  1206. static int https_getsock(struct connectdata *conn,
  1207. curl_socket_t *socks,
  1208. int numsocks)
  1209. {
  1210. if(conn->handler->flags & PROTOPT_SSL) {
  1211. struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
  1212. if(!numsocks)
  1213. return GETSOCK_BLANK;
  1214. if(connssl->connecting_state == ssl_connect_2_writing) {
  1215. /* write mode */
  1216. socks[0] = conn->sock[FIRSTSOCKET];
  1217. return GETSOCK_WRITESOCK(0);
  1218. }
  1219. else if(connssl->connecting_state == ssl_connect_2_reading) {
  1220. /* read mode */
  1221. socks[0] = conn->sock[FIRSTSOCKET];
  1222. return GETSOCK_READSOCK(0);
  1223. }
  1224. }
  1225. return CURLE_OK;
  1226. }
  1227. #else
  1228. #ifdef USE_SSL
  1229. static int https_getsock(struct connectdata *conn,
  1230. curl_socket_t *socks,
  1231. int numsocks)
  1232. {
  1233. (void)conn;
  1234. (void)socks;
  1235. (void)numsocks;
  1236. return GETSOCK_BLANK;
  1237. }
  1238. #endif /* USE_SSL */
  1239. #endif /* USE_SSLEAY || USE_GNUTLS || USE_SCHANNEL */
  1240. /*
  1241. * Curl_http_done() gets called from Curl_done() after a single HTTP request
  1242. * has been performed.
  1243. */
  1244. CURLcode Curl_http_done(struct connectdata *conn,
  1245. CURLcode status, bool premature)
  1246. {
  1247. struct SessionHandle *data = conn->data;
  1248. struct HTTP *http =data->req.protop;
  1249. Curl_unencode_cleanup(conn);
  1250. #ifdef USE_SPNEGO
  1251. if(data->state.proxyneg.state == GSS_AUTHSENT ||
  1252. data->state.negotiate.state == GSS_AUTHSENT)
  1253. Curl_cleanup_negotiate(data);
  1254. #endif
  1255. /* set the proper values (possibly modified on POST) */
  1256. conn->fread_func = data->set.fread_func; /* restore */
  1257. conn->fread_in = data->set.in; /* restore */
  1258. conn->seek_func = data->set.seek_func; /* restore */
  1259. conn->seek_client = data->set.seek_client; /* restore */
  1260. if(http == NULL)
  1261. return CURLE_OK;
  1262. if(http->send_buffer) {
  1263. Curl_send_buffer *buff = http->send_buffer;
  1264. free(buff->buffer);
  1265. free(buff);
  1266. http->send_buffer = NULL; /* clear the pointer */
  1267. }
  1268. if(HTTPREQ_POST_FORM == data->set.httpreq) {
  1269. data->req.bytecount = http->readbytecount + http->writebytecount;
  1270. Curl_formclean(&http->sendit); /* Now free that whole lot */
  1271. if(http->form.fp) {
  1272. /* a file being uploaded was left opened, close it! */
  1273. fclose(http->form.fp);
  1274. http->form.fp = NULL;
  1275. }
  1276. }
  1277. else if(HTTPREQ_PUT == data->set.httpreq)
  1278. data->req.bytecount = http->readbytecount + http->writebytecount;
  1279. if(status != CURLE_OK)
  1280. return (status);
  1281. if(!premature && /* this check is pointless when DONE is called before the
  1282. entire operation is complete */
  1283. !conn->bits.retry &&
  1284. !data->set.connect_only &&
  1285. ((http->readbytecount +
  1286. data->req.headerbytecount -
  1287. data->req.deductheadercount)) <= 0) {
  1288. /* If this connection isn't simply closed to be retried, AND nothing was
  1289. read from the HTTP server (that counts), this can't be right so we
  1290. return an error here */
  1291. failf(data, "Empty reply from server");
  1292. return CURLE_GOT_NOTHING;
  1293. }
  1294. return CURLE_OK;
  1295. }
  1296. /*
  1297. * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
  1298. * to avoid it include:
  1299. *
  1300. * - if the user specifically requested HTTP 1.0
  1301. * - if the server we are connected to only supports 1.0
  1302. * - if any server previously contacted to handle this request only supports
  1303. * 1.0.
  1304. */
  1305. static bool use_http_1_1plus(const struct SessionHandle *data,
  1306. const struct connectdata *conn)
  1307. {
  1308. return ((data->set.httpversion >= CURL_HTTP_VERSION_1_1) ||
  1309. ((data->set.httpversion != CURL_HTTP_VERSION_1_0) &&
  1310. ((conn->httpversion == 11) ||
  1311. ((conn->httpversion != 10) &&
  1312. (data->state.httpversion != 10))))) ? TRUE : FALSE;
  1313. }
  1314. /* check and possibly add an Expect: header */
  1315. static CURLcode expect100(struct SessionHandle *data,
  1316. struct connectdata *conn,
  1317. Curl_send_buffer *req_buffer)
  1318. {
  1319. CURLcode result = CURLE_OK;
  1320. const char *ptr;
  1321. data->state.expect100header = FALSE; /* default to false unless it is set
  1322. to TRUE below */
  1323. if(use_http_1_1plus(data, conn)) {
  1324. /* if not doing HTTP 1.0 or disabled explicitly, we add a Expect:
  1325. 100-continue to the headers which actually speeds up post operations
  1326. (as there is one packet coming back from the web server) */
  1327. ptr = Curl_checkheaders(conn, "Expect:");
  1328. if(ptr) {
  1329. data->state.expect100header =
  1330. Curl_compareheader(ptr, "Expect:", "100-continue");
  1331. }
  1332. else {
  1333. result = Curl_add_bufferf(req_buffer,
  1334. "Expect: 100-continue\r\n");
  1335. if(result == CURLE_OK)
  1336. data->state.expect100header = TRUE;
  1337. }
  1338. }
  1339. return result;
  1340. }
  1341. enum proxy_use {
  1342. HEADER_SERVER, /* direct to server */
  1343. HEADER_PROXY, /* regular request to proxy */
  1344. HEADER_CONNECT /* sending CONNECT to a proxy */
  1345. };
  1346. CURLcode Curl_add_custom_headers(struct connectdata *conn,
  1347. bool is_connect,
  1348. Curl_send_buffer *req_buffer)
  1349. {
  1350. char *ptr;
  1351. struct curl_slist *h[2];
  1352. struct curl_slist *headers;
  1353. int numlists=1; /* by default */
  1354. struct SessionHandle *data = conn->data;
  1355. int i;
  1356. enum proxy_use proxy;
  1357. if(is_connect)
  1358. proxy = HEADER_CONNECT;
  1359. else
  1360. proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
  1361. HEADER_PROXY:HEADER_SERVER;
  1362. switch(proxy) {
  1363. case HEADER_SERVER:
  1364. h[0] = data->set.headers;
  1365. break;
  1366. case HEADER_PROXY:
  1367. h[0] = data->set.headers;
  1368. if(data->set.sep_headers) {
  1369. h[1] = data->set.proxyheaders;
  1370. numlists++;
  1371. }
  1372. break;
  1373. case HEADER_CONNECT:
  1374. if(data->set.sep_headers)
  1375. h[0] = data->set.proxyheaders;
  1376. else
  1377. h[0] = data->set.headers;
  1378. break;
  1379. }
  1380. /* loop through one or two lists */
  1381. for(i=0; i < numlists; i++) {
  1382. headers = h[i];
  1383. while(headers) {
  1384. ptr = strchr(headers->data, ':');
  1385. if(ptr) {
  1386. /* we require a colon for this to be a true header */
  1387. ptr++; /* pass the colon */
  1388. while(*ptr && ISSPACE(*ptr))
  1389. ptr++;
  1390. if(*ptr) {
  1391. /* only send this if the contents was non-blank */
  1392. if(conn->allocptr.host &&
  1393. /* a Host: header was sent already, don't pass on any custom Host:
  1394. header as that will produce *two* in the same request! */
  1395. checkprefix("Host:", headers->data))
  1396. ;
  1397. else if(data->set.httpreq == HTTPREQ_POST_FORM &&
  1398. /* this header (extended by formdata.c) is sent later */
  1399. checkprefix("Content-Type:", headers->data))
  1400. ;
  1401. else if(conn->bits.authneg &&
  1402. /* while doing auth neg, don't allow the custom length since
  1403. we will force length zero then */
  1404. checkprefix("Content-Length", headers->data))
  1405. ;
  1406. else if(conn->allocptr.te &&
  1407. /* when asking for Transfer-Encoding, don't pass on a custom
  1408. Connection: */
  1409. checkprefix("Connection", headers->data))
  1410. ;
  1411. else {
  1412. CURLcode result = Curl_add_bufferf(req_buffer, "%s\r\n",
  1413. headers->data);
  1414. if(result)
  1415. return result;
  1416. }
  1417. }
  1418. }
  1419. else {
  1420. ptr = strchr(headers->data, ';');
  1421. if(ptr) {
  1422. ptr++; /* pass the semicolon */
  1423. while(*ptr && ISSPACE(*ptr))
  1424. ptr++;
  1425. if(*ptr) {
  1426. /* this may be used for something else in the future */
  1427. }
  1428. else {
  1429. if(*(--ptr) == ';') {
  1430. CURLcode result;
  1431. /* send no-value custom header if terminated by semicolon */
  1432. *ptr = ':';
  1433. result = Curl_add_bufferf(req_buffer, "%s\r\n",
  1434. headers->data);
  1435. if(result)
  1436. return result;
  1437. }
  1438. }
  1439. }
  1440. }
  1441. headers = headers->next;
  1442. }
  1443. }
  1444. return CURLE_OK;
  1445. }
  1446. CURLcode Curl_add_timecondition(struct SessionHandle *data,
  1447. Curl_send_buffer *req_buffer)
  1448. {
  1449. const struct tm *tm;
  1450. char *buf = data->state.buffer;
  1451. CURLcode result = CURLE_OK;
  1452. struct tm keeptime;
  1453. result = Curl_gmtime(data->set.timevalue, &keeptime);
  1454. if(result) {
  1455. failf(data, "Invalid TIMEVALUE");
  1456. return result;
  1457. }
  1458. tm = &keeptime;
  1459. /* The If-Modified-Since header family should have their times set in
  1460. * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
  1461. * represented in Greenwich Mean Time (GMT), without exception. For the
  1462. * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
  1463. * Time)." (see page 20 of RFC2616).
  1464. */
  1465. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  1466. snprintf(buf, BUFSIZE-1,
  1467. "%s, %02d %s %4d %02d:%02d:%02d GMT",
  1468. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  1469. tm->tm_mday,
  1470. Curl_month[tm->tm_mon],
  1471. tm->tm_year + 1900,
  1472. tm->tm_hour,
  1473. tm->tm_min,
  1474. tm->tm_sec);
  1475. switch(data->set.timecondition) {
  1476. case CURL_TIMECOND_IFMODSINCE:
  1477. default:
  1478. result = Curl_add_bufferf(req_buffer,
  1479. "If-Modified-Since: %s\r\n", buf);
  1480. break;
  1481. case CURL_TIMECOND_IFUNMODSINCE:
  1482. result = Curl_add_bufferf(req_buffer,
  1483. "If-Unmodified-Since: %s\r\n", buf);
  1484. break;
  1485. case CURL_TIMECOND_LASTMOD:
  1486. result = Curl_add_bufferf(req_buffer,
  1487. "Last-Modified: %s\r\n", buf);
  1488. break;
  1489. }
  1490. return result;
  1491. }
  1492. /*
  1493. * Curl_http() gets called from the generic Curl_do() function when a HTTP
  1494. * request is to be performed. This creates and sends a properly constructed
  1495. * HTTP request.
  1496. */
  1497. CURLcode Curl_http(struct connectdata *conn, bool *done)
  1498. {
  1499. struct SessionHandle *data=conn->data;
  1500. CURLcode result=CURLE_OK;
  1501. struct HTTP *http;
  1502. const char *ppath = data->state.path;
  1503. bool paste_ftp_userpwd = FALSE;
  1504. char ftp_typecode[sizeof("/;type=?")] = "";
  1505. const char *host = conn->host.name;
  1506. const char *te = ""; /* transfer-encoding */
  1507. const char *ptr;
  1508. const char *request;
  1509. Curl_HttpReq httpreq = data->set.httpreq;
  1510. char *addcookies = NULL;
  1511. curl_off_t included_body = 0;
  1512. const char *httpstring;
  1513. Curl_send_buffer *req_buffer;
  1514. curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
  1515. int seekerr = CURL_SEEKFUNC_OK;
  1516. /* Always consider the DO phase done after this function call, even if there
  1517. may be parts of the request that is not yet sent, since we can deal with
  1518. the rest of the request in the PERFORM phase. */
  1519. *done = TRUE;
  1520. if(conn->httpversion < 20) { /* unless the connection is re-used and already
  1521. http2 */
  1522. switch (conn->negnpn) {
  1523. case NPN_HTTP2:
  1524. result = Curl_http2_init(conn);
  1525. if(result)
  1526. return result;
  1527. result = Curl_http2_setup(conn);
  1528. if(result)
  1529. return result;
  1530. result = Curl_http2_switched(conn);
  1531. if(result)
  1532. return result;
  1533. break;
  1534. case NPN_HTTP1_1:
  1535. /* continue with HTTP/1.1 when explicitly requested */
  1536. break;
  1537. default:
  1538. /* and as fallback */
  1539. break;
  1540. }
  1541. }
  1542. else {
  1543. /* prepare for a http2 request */
  1544. result = Curl_http2_setup(conn);
  1545. if(result)
  1546. return result;
  1547. }
  1548. http = data->req.protop;
  1549. if(!data->state.this_is_a_follow) {
  1550. /* this is not a followed location, get the original host name */
  1551. if(data->state.first_host)
  1552. /* Free to avoid leaking memory on multiple requests*/
  1553. free(data->state.first_host);
  1554. data->state.first_host = strdup(conn->host.name);
  1555. if(!data->state.first_host)
  1556. return CURLE_OUT_OF_MEMORY;
  1557. }
  1558. http->writebytecount = http->readbytecount = 0;
  1559. if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
  1560. data->set.upload) {
  1561. httpreq = HTTPREQ_PUT;
  1562. }
  1563. /* Now set the 'request' pointer to the proper request string */
  1564. if(data->set.str[STRING_CUSTOMREQUEST])
  1565. request = data->set.str[STRING_CUSTOMREQUEST];
  1566. else {
  1567. if(data->set.opt_no_body)
  1568. request = "HEAD";
  1569. else {
  1570. DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
  1571. switch(httpreq) {
  1572. case HTTPREQ_POST:
  1573. case HTTPREQ_POST_FORM:
  1574. request = "POST";
  1575. break;
  1576. case HTTPREQ_PUT:
  1577. request = "PUT";
  1578. break;
  1579. default: /* this should never happen */
  1580. case HTTPREQ_GET:
  1581. request = "GET";
  1582. break;
  1583. case HTTPREQ_HEAD:
  1584. request = "HEAD";
  1585. break;
  1586. }
  1587. }
  1588. }
  1589. /* The User-Agent string might have been allocated in url.c already, because
  1590. it might have been used in the proxy connect, but if we have got a header
  1591. with the user-agent string specified, we erase the previously made string
  1592. here. */
  1593. if(Curl_checkheaders(conn, "User-Agent:") && conn->allocptr.uagent) {
  1594. free(conn->allocptr.uagent);
  1595. conn->allocptr.uagent=NULL;
  1596. }
  1597. /* setup the authentication headers */
  1598. result = Curl_http_output_auth(conn, request, ppath, FALSE);
  1599. if(result)
  1600. return result;
  1601. if((data->state.authhost.multi || data->state.authproxy.multi) &&
  1602. (httpreq != HTTPREQ_GET) &&
  1603. (httpreq != HTTPREQ_HEAD)) {
  1604. /* Auth is required and we are not authenticated yet. Make a PUT or POST
  1605. with content-length zero as a "probe". */
  1606. conn->bits.authneg = TRUE;
  1607. }
  1608. else
  1609. conn->bits.authneg = FALSE;
  1610. Curl_safefree(conn->allocptr.ref);
  1611. if(data->change.referer && !Curl_checkheaders(conn, "Referer:")) {
  1612. conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
  1613. if(!conn->allocptr.ref)
  1614. return CURLE_OUT_OF_MEMORY;
  1615. }
  1616. else
  1617. conn->allocptr.ref = NULL;
  1618. if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie:"))
  1619. addcookies = data->set.str[STRING_COOKIE];
  1620. if(!Curl_checkheaders(conn, "Accept-Encoding:") &&
  1621. data->set.str[STRING_ENCODING]) {
  1622. Curl_safefree(conn->allocptr.accept_encoding);
  1623. conn->allocptr.accept_encoding =
  1624. aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
  1625. if(!conn->allocptr.accept_encoding)
  1626. return CURLE_OUT_OF_MEMORY;
  1627. }
  1628. #ifdef HAVE_LIBZ
  1629. /* we only consider transfer-encoding magic if libz support is built-in */
  1630. if(!Curl_checkheaders(conn, "TE:") &&
  1631. data->set.http_transfer_encoding) {
  1632. /* When we are to insert a TE: header in the request, we must also insert
  1633. TE in a Connection: header, so we need to merge the custom provided
  1634. Connection: header and prevent the original to get sent. Note that if
  1635. the user has inserted his/hers own TE: header we don't do this magic
  1636. but then assume that the user will handle it all! */
  1637. char *cptr = Curl_checkheaders(conn, "Connection:");
  1638. #define TE_HEADER "TE: gzip\r\n"
  1639. Curl_safefree(conn->allocptr.te);
  1640. /* Create the (updated) Connection: header */
  1641. conn->allocptr.te = cptr? aprintf("%s, TE\r\n" TE_HEADER, cptr):
  1642. strdup("Connection: TE\r\n" TE_HEADER);
  1643. if(!conn->allocptr.te)
  1644. return CURLE_OUT_OF_MEMORY;
  1645. }
  1646. #endif
  1647. if(conn->httpversion == 20)
  1648. /* In HTTP2 forbids Transfer-Encoding: chunked */
  1649. ptr = NULL;
  1650. else {
  1651. ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
  1652. if(ptr) {
  1653. /* Some kind of TE is requested, check if 'chunked' is chosen */
  1654. data->req.upload_chunky =
  1655. Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
  1656. }
  1657. else {
  1658. if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1659. data->set.upload &&
  1660. (data->state.infilesize == -1)) {
  1661. if(conn->bits.authneg)
  1662. /* don't enable chunked during auth neg */
  1663. ;
  1664. else if(use_http_1_1plus(data, conn)) {
  1665. /* HTTP, upload, unknown file size and not HTTP 1.0 */
  1666. data->req.upload_chunky = TRUE;
  1667. }
  1668. else {
  1669. failf(data, "Chunky upload is not supported by HTTP 1.0");
  1670. return CURLE_UPLOAD_FAILED;
  1671. }
  1672. }
  1673. else {
  1674. /* else, no chunky upload */
  1675. data->req.upload_chunky = FALSE;
  1676. }
  1677. if(data->req.upload_chunky)
  1678. te = "Transfer-Encoding: chunked\r\n";
  1679. }
  1680. }
  1681. Curl_safefree(conn->allocptr.host);
  1682. ptr = Curl_checkheaders(conn, "Host:");
  1683. if(ptr && (!data->state.this_is_a_follow ||
  1684. Curl_raw_equal(data->state.first_host, conn->host.name))) {
  1685. #if !defined(CURL_DISABLE_COOKIES)
  1686. /* If we have a given custom Host: header, we extract the host name in
  1687. order to possibly use it for cookie reasons later on. We only allow the
  1688. custom Host: header if this is NOT a redirect, as setting Host: in the
  1689. redirected request is being out on thin ice. Except if the host name
  1690. is the same as the first one! */
  1691. char *cookiehost = Curl_copy_header_value(ptr);
  1692. if(!cookiehost)
  1693. return CURLE_OUT_OF_MEMORY;
  1694. if(!*cookiehost)
  1695. /* ignore empty data */
  1696. free(cookiehost);
  1697. else {
  1698. /* If the host begins with '[', we start searching for the port after
  1699. the bracket has been closed */
  1700. int startsearch = 0;
  1701. if(*cookiehost == '[') {
  1702. char *closingbracket;
  1703. /* since the 'cookiehost' is an allocated memory area that will be
  1704. freed later we cannot simply increment the pointer */
  1705. memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
  1706. closingbracket = strchr(cookiehost, ']');
  1707. if(closingbracket)
  1708. *closingbracket = 0;
  1709. }
  1710. else {
  1711. char *colon = strchr(cookiehost + startsearch, ':');
  1712. if(colon)
  1713. *colon = 0; /* The host must not include an embedded port number */
  1714. }
  1715. Curl_safefree(conn->allocptr.cookiehost);
  1716. conn->allocptr.cookiehost = cookiehost;
  1717. }
  1718. #endif
  1719. conn->allocptr.host = NULL;
  1720. }
  1721. else {
  1722. /* When building Host: headers, we must put the host name within
  1723. [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
  1724. if(((conn->given->protocol&CURLPROTO_HTTPS) &&
  1725. (conn->remote_port == PORT_HTTPS)) ||
  1726. ((conn->given->protocol&CURLPROTO_HTTP) &&
  1727. (conn->remote_port == PORT_HTTP)) )
  1728. /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
  1729. the port number in the host string */
  1730. conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
  1731. conn->bits.ipv6_ip?"[":"",
  1732. host,
  1733. conn->bits.ipv6_ip?"]":"");
  1734. else
  1735. conn->allocptr.host = aprintf("Host: %s%s%s:%hu\r\n",
  1736. conn->bits.ipv6_ip?"[":"",
  1737. host,
  1738. conn->bits.ipv6_ip?"]":"",
  1739. conn->remote_port);
  1740. if(!conn->allocptr.host)
  1741. /* without Host: we can't make a nice request */
  1742. return CURLE_OUT_OF_MEMORY;
  1743. }
  1744. #ifndef CURL_DISABLE_PROXY
  1745. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  1746. /* Using a proxy but does not tunnel through it */
  1747. /* The path sent to the proxy is in fact the entire URL. But if the remote
  1748. host is a IDN-name, we must make sure that the request we produce only
  1749. uses the encoded host name! */
  1750. if(conn->host.dispname != conn->host.name) {
  1751. char *url = data->change.url;
  1752. ptr = strstr(url, conn->host.dispname);
  1753. if(ptr) {
  1754. /* This is where the display name starts in the URL, now replace this
  1755. part with the encoded name. TODO: This method of replacing the host
  1756. name is rather crude as I believe there's a slight risk that the
  1757. user has entered a user name or password that contain the host name
  1758. string. */
  1759. size_t currlen = strlen(conn->host.dispname);
  1760. size_t newlen = strlen(conn->host.name);
  1761. size_t urllen = strlen(url);
  1762. char *newurl;
  1763. newurl = malloc(urllen + newlen - currlen + 1);
  1764. if(newurl) {
  1765. /* copy the part before the host name */
  1766. memcpy(newurl, url, ptr - url);
  1767. /* append the new host name instead of the old */
  1768. memcpy(newurl + (ptr - url), conn->host.name, newlen);
  1769. /* append the piece after the host name */
  1770. memcpy(newurl + newlen + (ptr - url),
  1771. ptr + currlen, /* copy the trailing zero byte too */
  1772. urllen - (ptr-url) - currlen + 1);
  1773. if(data->change.url_alloc) {
  1774. Curl_safefree(data->change.url);
  1775. data->change.url_alloc = FALSE;
  1776. }
  1777. data->change.url = newurl;
  1778. data->change.url_alloc = TRUE;
  1779. }
  1780. else
  1781. return CURLE_OUT_OF_MEMORY;
  1782. }
  1783. }
  1784. ppath = data->change.url;
  1785. if(checkprefix("ftp://", ppath)) {
  1786. if(data->set.proxy_transfer_mode) {
  1787. /* when doing ftp, append ;type=<a|i> if not present */
  1788. char *type = strstr(ppath, ";type=");
  1789. if(type && type[6] && type[7] == 0) {
  1790. switch (Curl_raw_toupper(type[6])) {
  1791. case 'A':
  1792. case 'D':
  1793. case 'I':
  1794. break;
  1795. default:
  1796. type = NULL;
  1797. }
  1798. }
  1799. if(!type) {
  1800. char *p = ftp_typecode;
  1801. /* avoid sending invalid URLs like ftp://example.com;type=i if the
  1802. * user specified ftp://example.com without the slash */
  1803. if(!*data->state.path && ppath[strlen(ppath) - 1] != '/') {
  1804. *p++ = '/';
  1805. }
  1806. snprintf(p, sizeof(ftp_typecode) - 1, ";type=%c",
  1807. data->set.prefer_ascii ? 'a' : 'i');
  1808. }
  1809. }
  1810. if(conn->bits.user_passwd && !conn->bits.userpwd_in_url)
  1811. paste_ftp_userpwd = TRUE;
  1812. }
  1813. }
  1814. #endif /* CURL_DISABLE_PROXY */
  1815. if(HTTPREQ_POST_FORM == httpreq) {
  1816. /* we must build the whole post sequence first, so that we have a size of
  1817. the whole transfer before we start to send it */
  1818. result = Curl_getformdata(data, &http->sendit, data->set.httppost,
  1819. Curl_checkheaders(conn, "Content-Type:"),
  1820. &http->postsize);
  1821. if(result)
  1822. return result;
  1823. }
  1824. http->p_accept = Curl_checkheaders(conn, "Accept:")?NULL:"Accept: */*\r\n";
  1825. if(( (HTTPREQ_POST == httpreq) ||
  1826. (HTTPREQ_POST_FORM == httpreq) ||
  1827. (HTTPREQ_PUT == httpreq) ) &&
  1828. data->state.resume_from) {
  1829. /**********************************************************************
  1830. * Resuming upload in HTTP means that we PUT or POST and that we have
  1831. * got a resume_from value set. The resume value has already created
  1832. * a Range: header that will be passed along. We need to "fast forward"
  1833. * the file the given number of bytes and decrease the assume upload
  1834. * file size before we continue this venture in the dark lands of HTTP.
  1835. *********************************************************************/
  1836. if(data->state.resume_from < 0 ) {
  1837. /*
  1838. * This is meant to get the size of the present remote-file by itself.
  1839. * We don't support this now. Bail out!
  1840. */
  1841. data->state.resume_from = 0;
  1842. }
  1843. if(data->state.resume_from && !data->state.this_is_a_follow) {
  1844. /* do we still game? */
  1845. /* Now, let's read off the proper amount of bytes from the
  1846. input. */
  1847. if(conn->seek_func) {
  1848. seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
  1849. SEEK_SET);
  1850. }
  1851. if(seekerr != CURL_SEEKFUNC_OK) {
  1852. if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
  1853. failf(data, "Could not seek stream");
  1854. return CURLE_READ_ERROR;
  1855. }
  1856. /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
  1857. else {
  1858. curl_off_t passed=0;
  1859. do {
  1860. size_t readthisamountnow =
  1861. (data->state.resume_from - passed > CURL_OFF_T_C(BUFSIZE)) ?
  1862. BUFSIZE : curlx_sotouz(data->state.resume_from - passed);
  1863. size_t actuallyread =
  1864. data->set.fread_func(data->state.buffer, 1, readthisamountnow,
  1865. data->set.in);
  1866. passed += actuallyread;
  1867. if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
  1868. /* this checks for greater-than only to make sure that the
  1869. CURL_READFUNC_ABORT return code still aborts */
  1870. failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T
  1871. " bytes from the input", passed);
  1872. return CURLE_READ_ERROR;
  1873. }
  1874. } while(passed < data->state.resume_from);
  1875. }
  1876. }
  1877. /* now, decrease the size of the read */
  1878. if(data->state.infilesize>0) {
  1879. data->state.infilesize -= data->state.resume_from;
  1880. if(data->state.infilesize <= 0) {
  1881. failf(data, "File already completely uploaded");
  1882. return CURLE_PARTIAL_FILE;
  1883. }
  1884. }
  1885. /* we've passed, proceed as normal */
  1886. }
  1887. }
  1888. if(data->state.use_range) {
  1889. /*
  1890. * A range is selected. We use different headers whether we're downloading
  1891. * or uploading and we always let customized headers override our internal
  1892. * ones if any such are specified.
  1893. */
  1894. if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
  1895. !Curl_checkheaders(conn, "Range:")) {
  1896. /* if a line like this was already allocated, free the previous one */
  1897. if(conn->allocptr.rangeline)
  1898. free(conn->allocptr.rangeline);
  1899. conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n",
  1900. data->state.range);
  1901. }
  1902. else if((httpreq != HTTPREQ_GET) &&
  1903. !Curl_checkheaders(conn, "Content-Range:")) {
  1904. /* if a line like this was already allocated, free the previous one */
  1905. if(conn->allocptr.rangeline)
  1906. free(conn->allocptr.rangeline);
  1907. if(data->set.set_resume_from < 0) {
  1908. /* Upload resume was asked for, but we don't know the size of the
  1909. remote part so we tell the server (and act accordingly) that we
  1910. upload the whole file (again) */
  1911. conn->allocptr.rangeline =
  1912. aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T
  1913. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  1914. data->state.infilesize - 1, data->state.infilesize);
  1915. }
  1916. else if(data->state.resume_from) {
  1917. /* This is because "resume" was selected */
  1918. curl_off_t total_expected_size=
  1919. data->state.resume_from + data->state.infilesize;
  1920. conn->allocptr.rangeline =
  1921. aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
  1922. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  1923. data->state.range, total_expected_size-1,
  1924. total_expected_size);
  1925. }
  1926. else {
  1927. /* Range was selected and then we just pass the incoming range and
  1928. append total size */
  1929. conn->allocptr.rangeline =
  1930. aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  1931. data->state.range, data->state.infilesize);
  1932. }
  1933. if(!conn->allocptr.rangeline)
  1934. return CURLE_OUT_OF_MEMORY;
  1935. }
  1936. }
  1937. /* Use 1.1 unless the user specifically asked for 1.0 or the server only
  1938. supports 1.0 */
  1939. httpstring= use_http_1_1plus(data, conn)?"1.1":"1.0";
  1940. /* initialize a dynamic send-buffer */
  1941. req_buffer = Curl_add_buffer_init();
  1942. if(!req_buffer)
  1943. return CURLE_OUT_OF_MEMORY;
  1944. /* add the main request stuff */
  1945. /* GET/HEAD/POST/PUT */
  1946. result = Curl_add_bufferf(req_buffer, "%s ", request);
  1947. if(result)
  1948. return result;
  1949. /* url */
  1950. if(paste_ftp_userpwd)
  1951. result = Curl_add_bufferf(req_buffer, "ftp://%s:%s@%s",
  1952. conn->user, conn->passwd,
  1953. ppath + sizeof("ftp://") - 1);
  1954. else
  1955. result = Curl_add_buffer(req_buffer, ppath, strlen(ppath));
  1956. if(result)
  1957. return result;
  1958. result =
  1959. Curl_add_bufferf(req_buffer,
  1960. "%s" /* ftp typecode (;type=x) */
  1961. " HTTP/%s\r\n" /* HTTP version */
  1962. "%s" /* proxyuserpwd */
  1963. "%s" /* userpwd */
  1964. "%s" /* range */
  1965. "%s" /* user agent */
  1966. "%s" /* host */
  1967. "%s" /* accept */
  1968. "%s" /* TE: */
  1969. "%s" /* accept-encoding */
  1970. "%s" /* referer */
  1971. "%s" /* Proxy-Connection */
  1972. "%s",/* transfer-encoding */
  1973. ftp_typecode,
  1974. httpstring,
  1975. conn->allocptr.proxyuserpwd?
  1976. conn->allocptr.proxyuserpwd:"",
  1977. conn->allocptr.userpwd?conn->allocptr.userpwd:"",
  1978. (data->state.use_range && conn->allocptr.rangeline)?
  1979. conn->allocptr.rangeline:"",
  1980. (data->set.str[STRING_USERAGENT] &&
  1981. *data->set.str[STRING_USERAGENT] &&
  1982. conn->allocptr.uagent)?
  1983. conn->allocptr.uagent:"",
  1984. (conn->allocptr.host?conn->allocptr.host:""),
  1985. http->p_accept?http->p_accept:"",
  1986. conn->allocptr.te?conn->allocptr.te:"",
  1987. (data->set.str[STRING_ENCODING] &&
  1988. *data->set.str[STRING_ENCODING] &&
  1989. conn->allocptr.accept_encoding)?
  1990. conn->allocptr.accept_encoding:"",
  1991. (data->change.referer && conn->allocptr.ref)?
  1992. conn->allocptr.ref:"" /* Referer: <data> */,
  1993. (conn->bits.httpproxy &&
  1994. !conn->bits.tunnel_proxy &&
  1995. !Curl_checkProxyheaders(conn, "Proxy-Connection:"))?
  1996. "Proxy-Connection: Keep-Alive\r\n":"",
  1997. te
  1998. );
  1999. /*
  2000. * Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM
  2001. * with basic and digest, it will be freed anyway by the next request
  2002. */
  2003. Curl_safefree (conn->allocptr.userpwd);
  2004. conn->allocptr.userpwd = NULL;
  2005. if(result)
  2006. return result;
  2007. if(!(conn->handler->flags&PROTOPT_SSL) &&
  2008. (data->set.httpversion == CURL_HTTP_VERSION_2_0)) {
  2009. /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done
  2010. over SSL */
  2011. result = Curl_http2_request_upgrade(req_buffer, conn);
  2012. if(result)
  2013. return result;
  2014. }
  2015. #if !defined(CURL_DISABLE_COOKIES)
  2016. if(data->cookies || addcookies) {
  2017. struct Cookie *co=NULL; /* no cookies from start */
  2018. int count=0;
  2019. if(data->cookies) {
  2020. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  2021. co = Curl_cookie_getlist(data->cookies,
  2022. conn->allocptr.cookiehost?
  2023. conn->allocptr.cookiehost:host,
  2024. data->state.path,
  2025. (conn->handler->protocol&CURLPROTO_HTTPS)?
  2026. TRUE:FALSE);
  2027. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  2028. }
  2029. if(co) {
  2030. struct Cookie *store=co;
  2031. /* now loop through all cookies that matched */
  2032. while(co) {
  2033. if(co->value) {
  2034. if(0 == count) {
  2035. result = Curl_add_bufferf(req_buffer, "Cookie: ");
  2036. if(result)
  2037. break;
  2038. }
  2039. result = Curl_add_bufferf(req_buffer,
  2040. "%s%s=%s", count?"; ":"",
  2041. co->name, co->value);
  2042. if(result)
  2043. break;
  2044. count++;
  2045. }
  2046. co = co->next; /* next cookie please */
  2047. }
  2048. Curl_cookie_freelist(store, FALSE); /* free the cookie list */
  2049. }
  2050. if(addcookies && (CURLE_OK == result)) {
  2051. if(!count)
  2052. result = Curl_add_bufferf(req_buffer, "Cookie: ");
  2053. if(CURLE_OK == result) {
  2054. result = Curl_add_bufferf(req_buffer, "%s%s",
  2055. count?"; ":"",
  2056. addcookies);
  2057. count++;
  2058. }
  2059. }
  2060. if(count && (CURLE_OK == result))
  2061. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2062. if(result)
  2063. return result;
  2064. }
  2065. #endif
  2066. if(data->set.timecondition) {
  2067. result = Curl_add_timecondition(data, req_buffer);
  2068. if(result)
  2069. return result;
  2070. }
  2071. result = Curl_add_custom_headers(conn, FALSE, req_buffer);
  2072. if(result)
  2073. return result;
  2074. http->postdata = NULL; /* nothing to post at this point */
  2075. Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */
  2076. /* If 'authdone' is FALSE, we must not set the write socket index to the
  2077. Curl_transfer() call below, as we're not ready to actually upload any
  2078. data yet. */
  2079. switch(httpreq) {
  2080. case HTTPREQ_POST_FORM:
  2081. if(!http->sendit || conn->bits.authneg) {
  2082. /* nothing to post! */
  2083. result = Curl_add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
  2084. if(result)
  2085. return result;
  2086. result = Curl_add_buffer_send(req_buffer, conn,
  2087. &data->info.request_size, 0, FIRSTSOCKET);
  2088. if(result)
  2089. failf(data, "Failed sending POST request");
  2090. else
  2091. /* setup variables for the upcoming transfer */
  2092. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
  2093. -1, NULL);
  2094. break;
  2095. }
  2096. if(Curl_FormInit(&http->form, http->sendit)) {
  2097. failf(data, "Internal HTTP POST error!");
  2098. return CURLE_HTTP_POST_ERROR;
  2099. }
  2100. /* Get the currently set callback function pointer and store that in the
  2101. form struct since we might want the actual user-provided callback later
  2102. on. The conn->fread_func pointer itself will be changed for the
  2103. multipart case to the function that returns a multipart formatted
  2104. stream. */
  2105. http->form.fread_func = conn->fread_func;
  2106. /* Set the read function to read from the generated form data */
  2107. conn->fread_func = (curl_read_callback)Curl_FormReader;
  2108. conn->fread_in = &http->form;
  2109. http->sending = HTTPSEND_BODY;
  2110. if(!data->req.upload_chunky &&
  2111. !Curl_checkheaders(conn, "Content-Length:")) {
  2112. /* only add Content-Length if not uploading chunked */
  2113. result = Curl_add_bufferf(req_buffer,
  2114. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2115. "\r\n", http->postsize);
  2116. if(result)
  2117. return result;
  2118. }
  2119. result = expect100(data, conn, req_buffer);
  2120. if(result)
  2121. return result;
  2122. {
  2123. /* Get Content-Type: line from Curl_formpostheader.
  2124. */
  2125. char *contentType;
  2126. size_t linelength=0;
  2127. contentType = Curl_formpostheader((void *)&http->form,
  2128. &linelength);
  2129. if(!contentType) {
  2130. failf(data, "Could not get Content-Type header line!");
  2131. return CURLE_HTTP_POST_ERROR;
  2132. }
  2133. result = Curl_add_buffer(req_buffer, contentType, linelength);
  2134. if(result)
  2135. return result;
  2136. }
  2137. /* make the request end in a true CRLF */
  2138. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2139. if(result)
  2140. return result;
  2141. /* set upload size to the progress meter */
  2142. Curl_pgrsSetUploadSize(data, http->postsize);
  2143. /* fire away the whole request to the server */
  2144. result = Curl_add_buffer_send(req_buffer, conn,
  2145. &data->info.request_size, 0, FIRSTSOCKET);
  2146. if(result)
  2147. failf(data, "Failed sending POST request");
  2148. else
  2149. /* setup variables for the upcoming transfer */
  2150. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2151. &http->readbytecount, FIRSTSOCKET,
  2152. &http->writebytecount);
  2153. if(result) {
  2154. Curl_formclean(&http->sendit); /* free that whole lot */
  2155. return result;
  2156. }
  2157. /* convert the form data */
  2158. result = Curl_convert_form(data, http->sendit);
  2159. if(result) {
  2160. Curl_formclean(&http->sendit); /* free that whole lot */
  2161. return result;
  2162. }
  2163. break;
  2164. case HTTPREQ_PUT: /* Let's PUT the data to the server! */
  2165. if(conn->bits.authneg)
  2166. postsize = 0;
  2167. else
  2168. postsize = data->state.infilesize;
  2169. if((postsize != -1) && !data->req.upload_chunky &&
  2170. !Curl_checkheaders(conn, "Content-Length:")) {
  2171. /* only add Content-Length if not uploading chunked */
  2172. result = Curl_add_bufferf(req_buffer,
  2173. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2174. "\r\n", postsize);
  2175. if(result)
  2176. return result;
  2177. }
  2178. if(postsize != 0) {
  2179. result = expect100(data, conn, req_buffer);
  2180. if(result)
  2181. return result;
  2182. }
  2183. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
  2184. if(result)
  2185. return result;
  2186. /* set the upload size to the progress meter */
  2187. Curl_pgrsSetUploadSize(data, postsize);
  2188. /* this sends the buffer and frees all the buffer resources */
  2189. result = Curl_add_buffer_send(req_buffer, conn,
  2190. &data->info.request_size, 0, FIRSTSOCKET);
  2191. if(result)
  2192. failf(data, "Failed sending PUT request");
  2193. else
  2194. /* prepare for transfer */
  2195. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2196. &http->readbytecount, postsize?FIRSTSOCKET:-1,
  2197. postsize?&http->writebytecount:NULL);
  2198. if(result)
  2199. return result;
  2200. break;
  2201. case HTTPREQ_POST:
  2202. /* this is the simple POST, using x-www-form-urlencoded style */
  2203. if(conn->bits.authneg)
  2204. postsize = 0;
  2205. else {
  2206. /* figure out the size of the postfields */
  2207. postsize = (data->set.postfieldsize != -1)?
  2208. data->set.postfieldsize:
  2209. (data->set.postfields? (curl_off_t)strlen(data->set.postfields):-1);
  2210. }
  2211. /* We only set Content-Length and allow a custom Content-Length if
  2212. we don't upload data chunked, as RFC2616 forbids us to set both
  2213. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2214. if((postsize != -1) && !data->req.upload_chunky &&
  2215. !Curl_checkheaders(conn, "Content-Length:")) {
  2216. /* we allow replacing this header if not during auth negotiation,
  2217. although it isn't very wise to actually set your own */
  2218. result = Curl_add_bufferf(req_buffer,
  2219. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2220. "\r\n", postsize);
  2221. if(result)
  2222. return result;
  2223. }
  2224. if(!Curl_checkheaders(conn, "Content-Type:")) {
  2225. result = Curl_add_bufferf(req_buffer,
  2226. "Content-Type: application/"
  2227. "x-www-form-urlencoded\r\n");
  2228. if(result)
  2229. return result;
  2230. }
  2231. /* For really small posts we don't use Expect: headers at all, and for
  2232. the somewhat bigger ones we allow the app to disable it. Just make
  2233. sure that the expect100header is always set to the preferred value
  2234. here. */
  2235. ptr = Curl_checkheaders(conn, "Expect:");
  2236. if(ptr) {
  2237. data->state.expect100header =
  2238. Curl_compareheader(ptr, "Expect:", "100-continue");
  2239. }
  2240. else if(postsize > TINY_INITIAL_POST_SIZE || postsize < 0) {
  2241. result = expect100(data, conn, req_buffer);
  2242. if(result)
  2243. return result;
  2244. }
  2245. else
  2246. data->state.expect100header = FALSE;
  2247. if(data->set.postfields) {
  2248. /* In HTTP2, we send request body in DATA frame regardless of
  2249. its size. */
  2250. if(conn->httpversion != 20 &&
  2251. !data->state.expect100header &&
  2252. (postsize < MAX_INITIAL_POST_SIZE)) {
  2253. /* if we don't use expect: 100 AND
  2254. postsize is less than MAX_INITIAL_POST_SIZE
  2255. then append the post data to the HTTP request header. This limit
  2256. is no magic limit but only set to prevent really huge POSTs to
  2257. get the data duplicated with malloc() and family. */
  2258. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2259. if(result)
  2260. return result;
  2261. if(!data->req.upload_chunky) {
  2262. /* We're not sending it 'chunked', append it to the request
  2263. already now to reduce the number if send() calls */
  2264. result = Curl_add_buffer(req_buffer, data->set.postfields,
  2265. (size_t)postsize);
  2266. included_body = postsize;
  2267. }
  2268. else {
  2269. if(postsize) {
  2270. /* Append the POST data chunky-style */
  2271. result = Curl_add_bufferf(req_buffer, "%x\r\n", (int)postsize);
  2272. if(CURLE_OK == result) {
  2273. result = Curl_add_buffer(req_buffer, data->set.postfields,
  2274. (size_t)postsize);
  2275. if(CURLE_OK == result)
  2276. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2277. included_body = postsize + 2;
  2278. }
  2279. }
  2280. if(CURLE_OK == result)
  2281. result = Curl_add_buffer(req_buffer,
  2282. "\x30\x0d\x0a\x0d\x0a", 5);
  2283. /* 0 CR LF CR LF */
  2284. included_body += 5;
  2285. }
  2286. if(result)
  2287. return result;
  2288. /* Make sure the progress information is accurate */
  2289. Curl_pgrsSetUploadSize(data, postsize);
  2290. }
  2291. else {
  2292. /* A huge POST coming up, do data separate from the request */
  2293. http->postsize = postsize;
  2294. http->postdata = data->set.postfields;
  2295. http->sending = HTTPSEND_BODY;
  2296. conn->fread_func = (curl_read_callback)readmoredata;
  2297. conn->fread_in = (void *)conn;
  2298. /* set the upload size to the progress meter */
  2299. Curl_pgrsSetUploadSize(data, http->postsize);
  2300. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2301. if(result)
  2302. return result;
  2303. }
  2304. }
  2305. else {
  2306. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2307. if(result)
  2308. return result;
  2309. if(data->req.upload_chunky && conn->bits.authneg) {
  2310. /* Chunky upload is selected and we're negotiating auth still, send
  2311. end-of-data only */
  2312. result = Curl_add_buffer(req_buffer,
  2313. "\x30\x0d\x0a\x0d\x0a", 5);
  2314. /* 0 CR LF CR LF */
  2315. if(result)
  2316. return result;
  2317. }
  2318. else if(data->set.postfieldsize) {
  2319. /* set the upload size to the progress meter */
  2320. Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
  2321. /* set the pointer to mark that we will send the post body using the
  2322. read callback, but only if we're not in authenticate
  2323. negotiation */
  2324. if(!conn->bits.authneg) {
  2325. http->postdata = (char *)&http->postdata;
  2326. http->postsize = postsize;
  2327. }
  2328. }
  2329. }
  2330. /* issue the request */
  2331. result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size,
  2332. (size_t)included_body, FIRSTSOCKET);
  2333. if(result)
  2334. failf(data, "Failed sending HTTP POST request");
  2335. else
  2336. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2337. &http->readbytecount, http->postdata?FIRSTSOCKET:-1,
  2338. http->postdata?&http->writebytecount:NULL);
  2339. break;
  2340. default:
  2341. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2342. if(result)
  2343. return result;
  2344. /* issue the request */
  2345. result = Curl_add_buffer_send(req_buffer, conn,
  2346. &data->info.request_size, 0, FIRSTSOCKET);
  2347. if(result)
  2348. failf(data, "Failed sending HTTP request");
  2349. else
  2350. /* HTTP GET/HEAD download: */
  2351. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
  2352. http->postdata?FIRSTSOCKET:-1,
  2353. http->postdata?&http->writebytecount:NULL);
  2354. }
  2355. if(result)
  2356. return result;
  2357. if(http->writebytecount) {
  2358. /* if a request-body has been sent off, we make sure this progress is noted
  2359. properly */
  2360. Curl_pgrsSetUploadCounter(data, http->writebytecount);
  2361. if(Curl_pgrsUpdate(conn))
  2362. result = CURLE_ABORTED_BY_CALLBACK;
  2363. if(http->writebytecount >= postsize) {
  2364. /* already sent the entire request body, mark the "upload" as
  2365. complete */
  2366. infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T
  2367. " out of %" CURL_FORMAT_CURL_OFF_T " bytes\n",
  2368. http->writebytecount, postsize);
  2369. data->req.upload_done = TRUE;
  2370. data->req.keepon &= ~KEEP_SEND; /* we're done writing */
  2371. data->req.exp100 = EXP100_SEND_DATA; /* already sent */
  2372. }
  2373. }
  2374. return result;
  2375. }
  2376. /*
  2377. * checkhttpprefix()
  2378. *
  2379. * Returns TRUE if member of the list matches prefix of string
  2380. */
  2381. static bool
  2382. checkhttpprefix(struct SessionHandle *data,
  2383. const char *s)
  2384. {
  2385. struct curl_slist *head = data->set.http200aliases;
  2386. bool rc = FALSE;
  2387. #ifdef CURL_DOES_CONVERSIONS
  2388. /* convert from the network encoding using a scratch area */
  2389. char *scratch = strdup(s);
  2390. if(NULL == scratch) {
  2391. failf (data, "Failed to allocate memory for conversion!");
  2392. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2393. }
  2394. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
  2395. /* Curl_convert_from_network calls failf if unsuccessful */
  2396. free(scratch);
  2397. return FALSE; /* can't return CURLE_foobar so return FALSE */
  2398. }
  2399. s = scratch;
  2400. #endif /* CURL_DOES_CONVERSIONS */
  2401. while(head) {
  2402. if(checkprefix(head->data, s)) {
  2403. rc = TRUE;
  2404. break;
  2405. }
  2406. head = head->next;
  2407. }
  2408. if(!rc && (checkprefix("HTTP/", s)))
  2409. rc = TRUE;
  2410. #ifdef CURL_DOES_CONVERSIONS
  2411. free(scratch);
  2412. #endif /* CURL_DOES_CONVERSIONS */
  2413. return rc;
  2414. }
  2415. #ifndef CURL_DISABLE_RTSP
  2416. static bool
  2417. checkrtspprefix(struct SessionHandle *data,
  2418. const char *s)
  2419. {
  2420. #ifdef CURL_DOES_CONVERSIONS
  2421. /* convert from the network encoding using a scratch area */
  2422. char *scratch = strdup(s);
  2423. if(NULL == scratch) {
  2424. failf (data, "Failed to allocate memory for conversion!");
  2425. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2426. }
  2427. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
  2428. /* Curl_convert_from_network calls failf if unsuccessful */
  2429. free(scratch);
  2430. return FALSE; /* can't return CURLE_foobar so return FALSE */
  2431. }
  2432. s = scratch;
  2433. #else
  2434. (void)data; /* unused */
  2435. #endif /* CURL_DOES_CONVERSIONS */
  2436. if(checkprefix("RTSP/", s))
  2437. return TRUE;
  2438. else
  2439. return FALSE;
  2440. }
  2441. #endif /* CURL_DISABLE_RTSP */
  2442. static bool
  2443. checkprotoprefix(struct SessionHandle *data, struct connectdata *conn,
  2444. const char *s)
  2445. {
  2446. #ifndef CURL_DISABLE_RTSP
  2447. if(conn->handler->protocol & CURLPROTO_RTSP)
  2448. return checkrtspprefix(data, s);
  2449. #else
  2450. (void)conn;
  2451. #endif /* CURL_DISABLE_RTSP */
  2452. return checkhttpprefix(data, s);
  2453. }
  2454. /*
  2455. * header_append() copies a chunk of data to the end of the already received
  2456. * header. We make sure that the full string fit in the allocated header
  2457. * buffer, or else we enlarge it.
  2458. */
  2459. static CURLcode header_append(struct SessionHandle *data,
  2460. struct SingleRequest *k,
  2461. size_t length)
  2462. {
  2463. if(k->hbuflen + length >= data->state.headersize) {
  2464. /* We enlarge the header buffer as it is too small */
  2465. char *newbuff;
  2466. size_t hbufp_index;
  2467. size_t newsize;
  2468. if(k->hbuflen + length > CURL_MAX_HTTP_HEADER) {
  2469. /* The reason to have a max limit for this is to avoid the risk of a bad
  2470. server feeding libcurl with a never-ending header that will cause
  2471. reallocs infinitely */
  2472. failf (data, "Avoided giant realloc for header (max is %d)!",
  2473. CURL_MAX_HTTP_HEADER);
  2474. return CURLE_OUT_OF_MEMORY;
  2475. }
  2476. newsize=CURLMAX((k->hbuflen+ length)*3/2, data->state.headersize*2);
  2477. hbufp_index = k->hbufp - data->state.headerbuff;
  2478. newbuff = realloc(data->state.headerbuff, newsize);
  2479. if(!newbuff) {
  2480. failf (data, "Failed to alloc memory for big header!");
  2481. return CURLE_OUT_OF_MEMORY;
  2482. }
  2483. data->state.headersize=newsize;
  2484. data->state.headerbuff = newbuff;
  2485. k->hbufp = data->state.headerbuff + hbufp_index;
  2486. }
  2487. memcpy(k->hbufp, k->str_start, length);
  2488. k->hbufp += length;
  2489. k->hbuflen += length;
  2490. *k->hbufp = 0;
  2491. return CURLE_OK;
  2492. }
  2493. static void print_http_error(struct SessionHandle *data)
  2494. {
  2495. struct SingleRequest *k = &data->req;
  2496. char *beg = k->p;
  2497. /* make sure that data->req.p points to the HTTP status line */
  2498. if(!strncmp(beg, "HTTP", 4)) {
  2499. /* skip to HTTP status code */
  2500. beg = strchr(beg, ' ');
  2501. if(beg && *++beg) {
  2502. /* find trailing CR */
  2503. char end_char = '\r';
  2504. char *end = strchr(beg, end_char);
  2505. if(!end) {
  2506. /* try to find LF (workaround for non-compliant HTTP servers) */
  2507. end_char = '\n';
  2508. end = strchr(beg, end_char);
  2509. }
  2510. if(end) {
  2511. /* temporarily replace CR or LF by NUL and print the error message */
  2512. *end = '\0';
  2513. failf(data, "The requested URL returned error: %s", beg);
  2514. /* restore the previously replaced CR or LF */
  2515. *end = end_char;
  2516. return;
  2517. }
  2518. }
  2519. }
  2520. /* fall-back to printing the HTTP status code only */
  2521. failf(data, "The requested URL returned error: %d", k->httpcode);
  2522. }
  2523. /*
  2524. * Read any HTTP header lines from the server and pass them to the client app.
  2525. */
  2526. CURLcode Curl_http_readwrite_headers(struct SessionHandle *data,
  2527. struct connectdata *conn,
  2528. ssize_t *nread,
  2529. bool *stop_reading)
  2530. {
  2531. CURLcode result;
  2532. struct SingleRequest *k = &data->req;
  2533. /* header line within buffer loop */
  2534. do {
  2535. size_t rest_length;
  2536. size_t full_length;
  2537. int writetype;
  2538. /* str_start is start of line within buf */
  2539. k->str_start = k->str;
  2540. /* data is in network encoding so use 0x0a instead of '\n' */
  2541. k->end_ptr = memchr(k->str_start, 0x0a, *nread);
  2542. if(!k->end_ptr) {
  2543. /* Not a complete header line within buffer, append the data to
  2544. the end of the headerbuff. */
  2545. result = header_append(data, k, *nread);
  2546. if(result)
  2547. return result;
  2548. if(!k->headerline && (k->hbuflen>5)) {
  2549. /* make a first check that this looks like a protocol header */
  2550. if(!checkprotoprefix(data, conn, data->state.headerbuff)) {
  2551. /* this is not the beginning of a protocol first header line */
  2552. k->header = FALSE;
  2553. k->badheader = HEADER_ALLBAD;
  2554. break;
  2555. }
  2556. }
  2557. break; /* read more and try again */
  2558. }
  2559. /* decrease the size of the remaining (supposed) header line */
  2560. rest_length = (k->end_ptr - k->str)+1;
  2561. *nread -= (ssize_t)rest_length;
  2562. k->str = k->end_ptr + 1; /* move past new line */
  2563. full_length = k->str - k->str_start;
  2564. result = header_append(data, k, full_length);
  2565. if(result)
  2566. return result;
  2567. k->end_ptr = k->hbufp;
  2568. k->p = data->state.headerbuff;
  2569. /****
  2570. * We now have a FULL header line that p points to
  2571. *****/
  2572. if(!k->headerline) {
  2573. /* the first read header */
  2574. if((k->hbuflen>5) &&
  2575. !checkprotoprefix(data, conn, data->state.headerbuff)) {
  2576. /* this is not the beginning of a protocol first header line */
  2577. k->header = FALSE;
  2578. if(*nread)
  2579. /* since there's more, this is a partial bad header */
  2580. k->badheader = HEADER_PARTHEADER;
  2581. else {
  2582. /* this was all we read so it's all a bad header */
  2583. k->badheader = HEADER_ALLBAD;
  2584. *nread = (ssize_t)rest_length;
  2585. }
  2586. break;
  2587. }
  2588. }
  2589. /* headers are in network encoding so
  2590. use 0x0a and 0x0d instead of '\n' and '\r' */
  2591. if((0x0a == *k->p) || (0x0d == *k->p)) {
  2592. size_t headerlen;
  2593. /* Zero-length header line means end of headers! */
  2594. #ifdef CURL_DOES_CONVERSIONS
  2595. if(0x0d == *k->p) {
  2596. *k->p = '\r'; /* replace with CR in host encoding */
  2597. k->p++; /* pass the CR byte */
  2598. }
  2599. if(0x0a == *k->p) {
  2600. *k->p = '\n'; /* replace with LF in host encoding */
  2601. k->p++; /* pass the LF byte */
  2602. }
  2603. #else
  2604. if('\r' == *k->p)
  2605. k->p++; /* pass the \r byte */
  2606. if('\n' == *k->p)
  2607. k->p++; /* pass the \n byte */
  2608. #endif /* CURL_DOES_CONVERSIONS */
  2609. if(100 <= k->httpcode && 199 >= k->httpcode) {
  2610. /*
  2611. * We have made a HTTP PUT or POST and this is 1.1-lingo
  2612. * that tells us that the server is OK with this and ready
  2613. * to receive the data.
  2614. * However, we'll get more headers now so we must get
  2615. * back into the header-parsing state!
  2616. */
  2617. k->header = TRUE;
  2618. k->headerline = 0; /* restart the header line counter */
  2619. /* "A user agent MAY ignore unexpected 1xx status responses." */
  2620. switch(k->httpcode) {
  2621. case 100:
  2622. /* if we did wait for this do enable write now! */
  2623. if(k->exp100) {
  2624. k->exp100 = EXP100_SEND_DATA;
  2625. k->keepon |= KEEP_SEND;
  2626. }
  2627. break;
  2628. case 101:
  2629. /* Switching Protocols */
  2630. if(k->upgr101 == UPGR101_REQUESTED) {
  2631. infof(data, "Received 101\n");
  2632. k->upgr101 = UPGR101_RECEIVED;
  2633. /* switch to http2 now */
  2634. result = Curl_http2_switched(conn);
  2635. if(result)
  2636. return result;
  2637. }
  2638. break;
  2639. default:
  2640. break;
  2641. }
  2642. }
  2643. else {
  2644. k->header = FALSE; /* no more header to parse! */
  2645. if((k->size == -1) && !k->chunk && !conn->bits.close &&
  2646. (conn->httpversion == 11) &&
  2647. !(conn->handler->protocol & CURLPROTO_RTSP) &&
  2648. data->set.httpreq != HTTPREQ_HEAD) {
  2649. /* On HTTP 1.1, when connection is not to get closed, but no
  2650. Content-Length nor Content-Encoding chunked have been
  2651. received, according to RFC2616 section 4.4 point 5, we
  2652. assume that the server will close the connection to
  2653. signal the end of the document. */
  2654. infof(data, "no chunk, no close, no size. Assume close to "
  2655. "signal end\n");
  2656. connclose(conn, "HTTP: No end-of-message indicator");
  2657. }
  2658. }
  2659. /*
  2660. * When all the headers have been parsed, see if we should give
  2661. * up and return an error.
  2662. */
  2663. if(http_should_fail(conn)) {
  2664. failf (data, "The requested URL returned error: %d",
  2665. k->httpcode);
  2666. return CURLE_HTTP_RETURNED_ERROR;
  2667. }
  2668. /* now, only output this if the header AND body are requested:
  2669. */
  2670. writetype = CLIENTWRITE_HEADER;
  2671. if(data->set.include_header)
  2672. writetype |= CLIENTWRITE_BODY;
  2673. headerlen = k->p - data->state.headerbuff;
  2674. result = Curl_client_write(conn, writetype,
  2675. data->state.headerbuff,
  2676. headerlen);
  2677. if(result)
  2678. return result;
  2679. data->info.header_size += (long)headerlen;
  2680. data->req.headerbytecount += (long)headerlen;
  2681. data->req.deductheadercount =
  2682. (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
  2683. if(!*stop_reading) {
  2684. /* Curl_http_auth_act() checks what authentication methods
  2685. * that are available and decides which one (if any) to
  2686. * use. It will set 'newurl' if an auth method was picked. */
  2687. result = Curl_http_auth_act(conn);
  2688. if(result)
  2689. return result;
  2690. if(k->httpcode >= 300) {
  2691. if((!conn->bits.authneg) && !conn->bits.close &&
  2692. !conn->bits.rewindaftersend) {
  2693. /*
  2694. * General treatment of errors when about to send data. Including :
  2695. * "417 Expectation Failed", while waiting for 100-continue.
  2696. *
  2697. * The check for close above is done simply because of something
  2698. * else has already deemed the connection to get closed then
  2699. * something else should've considered the big picture and we
  2700. * avoid this check.
  2701. *
  2702. * rewindaftersend indicates that something has told libcurl to
  2703. * continue sending even if it gets discarded
  2704. */
  2705. switch(data->set.httpreq) {
  2706. case HTTPREQ_PUT:
  2707. case HTTPREQ_POST:
  2708. case HTTPREQ_POST_FORM:
  2709. /* We got an error response. If this happened before the whole
  2710. * request body has been sent we stop sending and mark the
  2711. * connection for closure after we've read the entire response.
  2712. */
  2713. if(!k->upload_done) {
  2714. infof(data, "HTTP error before end of send, stop sending\n");
  2715. connclose(conn, "Stop sending data before everything sent");
  2716. k->upload_done = TRUE;
  2717. k->keepon &= ~KEEP_SEND; /* don't send */
  2718. if(data->state.expect100header)
  2719. k->exp100 = EXP100_FAILED;
  2720. }
  2721. break;
  2722. default: /* default label present to avoid compiler warnings */
  2723. break;
  2724. }
  2725. }
  2726. }
  2727. if(conn->bits.rewindaftersend) {
  2728. /* We rewind after a complete send, so thus we continue
  2729. sending now */
  2730. infof(data, "Keep sending data to get tossed away!\n");
  2731. k->keepon |= KEEP_SEND;
  2732. }
  2733. }
  2734. if(!k->header) {
  2735. /*
  2736. * really end-of-headers.
  2737. *
  2738. * If we requested a "no body", this is a good time to get
  2739. * out and return home.
  2740. */
  2741. if(data->set.opt_no_body)
  2742. *stop_reading = TRUE;
  2743. else {
  2744. /* If we know the expected size of this document, we set the
  2745. maximum download size to the size of the expected
  2746. document or else, we won't know when to stop reading!
  2747. Note that we set the download maximum even if we read a
  2748. "Connection: close" header, to make sure that
  2749. "Content-Length: 0" still prevents us from attempting to
  2750. read the (missing) response-body.
  2751. */
  2752. /* According to RFC2616 section 4.4, we MUST ignore
  2753. Content-Length: headers if we are now receiving data
  2754. using chunked Transfer-Encoding.
  2755. */
  2756. if(k->chunk)
  2757. k->maxdownload = k->size = -1;
  2758. }
  2759. if(-1 != k->size) {
  2760. /* We do this operation even if no_body is true, since this
  2761. data might be retrieved later with curl_easy_getinfo()
  2762. and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
  2763. Curl_pgrsSetDownloadSize(data, k->size);
  2764. k->maxdownload = k->size;
  2765. }
  2766. /* If max download size is *zero* (nothing) we already
  2767. have nothing and can safely return ok now! */
  2768. if(0 == k->maxdownload)
  2769. *stop_reading = TRUE;
  2770. if(*stop_reading) {
  2771. /* we make sure that this socket isn't read more now */
  2772. k->keepon &= ~KEEP_RECV;
  2773. }
  2774. if(data->set.verbose)
  2775. Curl_debug(data, CURLINFO_HEADER_IN,
  2776. k->str_start, headerlen, conn);
  2777. break; /* exit header line loop */
  2778. }
  2779. /* We continue reading headers, so reset the line-based
  2780. header parsing variables hbufp && hbuflen */
  2781. k->hbufp = data->state.headerbuff;
  2782. k->hbuflen = 0;
  2783. continue;
  2784. }
  2785. /*
  2786. * Checks for special headers coming up.
  2787. */
  2788. if(!k->headerline++) {
  2789. /* This is the first header, it MUST be the error code line
  2790. or else we consider this to be the body right away! */
  2791. int httpversion_major;
  2792. int rtspversion_major;
  2793. int nc = 0;
  2794. #ifdef CURL_DOES_CONVERSIONS
  2795. #define HEADER1 scratch
  2796. #define SCRATCHSIZE 21
  2797. CURLcode res;
  2798. char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
  2799. /* We can't really convert this yet because we
  2800. don't know if it's the 1st header line or the body.
  2801. So we do a partial conversion into a scratch area,
  2802. leaving the data at k->p as-is.
  2803. */
  2804. strncpy(&scratch[0], k->p, SCRATCHSIZE);
  2805. scratch[SCRATCHSIZE] = 0; /* null terminate */
  2806. res = Curl_convert_from_network(data,
  2807. &scratch[0],
  2808. SCRATCHSIZE);
  2809. if(res)
  2810. /* Curl_convert_from_network calls failf if unsuccessful */
  2811. return res;
  2812. #else
  2813. #define HEADER1 k->p /* no conversion needed, just use k->p */
  2814. #endif /* CURL_DOES_CONVERSIONS */
  2815. if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
  2816. nc = sscanf(HEADER1,
  2817. " HTTP/%d.%d %3d",
  2818. &httpversion_major,
  2819. &conn->httpversion,
  2820. &k->httpcode);
  2821. if(nc==3) {
  2822. conn->httpversion += 10 * httpversion_major;
  2823. }
  2824. else {
  2825. /* this is the real world, not a Nirvana
  2826. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  2827. */
  2828. nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
  2829. conn->httpversion = 10;
  2830. /* If user has set option HTTP200ALIASES,
  2831. compare header line against list of aliases
  2832. */
  2833. if(!nc) {
  2834. if(checkhttpprefix(data, k->p)) {
  2835. nc = 1;
  2836. k->httpcode = 200;
  2837. conn->httpversion = 10;
  2838. }
  2839. }
  2840. }
  2841. }
  2842. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  2843. nc = sscanf(HEADER1,
  2844. " RTSP/%d.%d %3d",
  2845. &rtspversion_major,
  2846. &conn->rtspversion,
  2847. &k->httpcode);
  2848. if(nc==3) {
  2849. conn->rtspversion += 10 * rtspversion_major;
  2850. conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
  2851. }
  2852. else {
  2853. /* TODO: do we care about the other cases here? */
  2854. nc = 0;
  2855. }
  2856. }
  2857. if(nc) {
  2858. data->info.httpcode = k->httpcode;
  2859. data->info.httpversion = conn->httpversion;
  2860. if(!data->state.httpversion ||
  2861. data->state.httpversion > conn->httpversion)
  2862. /* store the lowest server version we encounter */
  2863. data->state.httpversion = conn->httpversion;
  2864. /*
  2865. * This code executes as part of processing the header. As a
  2866. * result, it's not totally clear how to interpret the
  2867. * response code yet as that depends on what other headers may
  2868. * be present. 401 and 407 may be errors, but may be OK
  2869. * depending on how authentication is working. Other codes
  2870. * are definitely errors, so give up here.
  2871. */
  2872. if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
  2873. ((k->httpcode != 401) || !conn->bits.user_passwd) &&
  2874. ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
  2875. if(data->state.resume_from &&
  2876. (data->set.httpreq==HTTPREQ_GET) &&
  2877. (k->httpcode == 416)) {
  2878. /* "Requested Range Not Satisfiable", just proceed and
  2879. pretend this is no error */
  2880. }
  2881. else {
  2882. /* serious error, go home! */
  2883. print_http_error(data);
  2884. return CURLE_HTTP_RETURNED_ERROR;
  2885. }
  2886. }
  2887. if(conn->httpversion == 10) {
  2888. /* Default action for HTTP/1.0 must be to close, unless
  2889. we get one of those fancy headers that tell us the
  2890. server keeps it open for us! */
  2891. infof(data, "HTTP 1.0, assume close after body\n");
  2892. connclose(conn, "HTTP/1.0 close after body");
  2893. }
  2894. else if(conn->httpversion >= 11 &&
  2895. !conn->bits.close) {
  2896. struct connectbundle *cb_ptr;
  2897. /* If HTTP version is >= 1.1 and connection is persistent
  2898. server supports pipelining. */
  2899. DEBUGF(infof(data,
  2900. "HTTP 1.1 or later with persistent connection, "
  2901. "pipelining supported\n"));
  2902. /* Activate pipelining if needed */
  2903. cb_ptr = conn->bundle;
  2904. if(cb_ptr) {
  2905. if(!Curl_pipeline_site_blacklisted(data, conn))
  2906. cb_ptr->server_supports_pipelining = TRUE;
  2907. }
  2908. }
  2909. switch(k->httpcode) {
  2910. case 204:
  2911. /* (quote from RFC2616, section 10.2.5): The server has
  2912. * fulfilled the request but does not need to return an
  2913. * entity-body ... The 204 response MUST NOT include a
  2914. * message-body, and thus is always terminated by the first
  2915. * empty line after the header fields. */
  2916. /* FALLTHROUGH */
  2917. case 304:
  2918. /* (quote from RFC2616, section 10.3.5): The 304 response
  2919. * MUST NOT contain a message-body, and thus is always
  2920. * terminated by the first empty line after the header
  2921. * fields. */
  2922. if(data->set.timecondition)
  2923. data->info.timecond = TRUE;
  2924. k->size=0;
  2925. k->maxdownload=0;
  2926. k->ignorecl = TRUE; /* ignore Content-Length headers */
  2927. break;
  2928. default:
  2929. /* nothing */
  2930. break;
  2931. }
  2932. }
  2933. else {
  2934. k->header = FALSE; /* this is not a header line */
  2935. break;
  2936. }
  2937. }
  2938. result = Curl_convert_from_network(data, k->p, strlen(k->p));
  2939. /* Curl_convert_from_network calls failf if unsuccessful */
  2940. if(result)
  2941. return result;
  2942. /* Check for Content-Length: header lines to get size */
  2943. if(!k->ignorecl && !data->set.ignorecl &&
  2944. checkprefix("Content-Length:", k->p)) {
  2945. curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
  2946. if(data->set.max_filesize &&
  2947. contentlength > data->set.max_filesize) {
  2948. failf(data, "Maximum file size exceeded");
  2949. return CURLE_FILESIZE_EXCEEDED;
  2950. }
  2951. if(contentlength >= 0) {
  2952. k->size = contentlength;
  2953. k->maxdownload = k->size;
  2954. /* we set the progress download size already at this point
  2955. just to make it easier for apps/callbacks to extract this
  2956. info as soon as possible */
  2957. Curl_pgrsSetDownloadSize(data, k->size);
  2958. }
  2959. else {
  2960. /* Negative Content-Length is really odd, and we know it
  2961. happens for example when older Apache servers send large
  2962. files */
  2963. connclose(conn, "negative content-length");
  2964. infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
  2965. ", closing after transfer\n", contentlength);
  2966. }
  2967. }
  2968. /* check for Content-Type: header lines to get the MIME-type */
  2969. else if(checkprefix("Content-Type:", k->p)) {
  2970. char *contenttype = Curl_copy_header_value(k->p);
  2971. if(!contenttype)
  2972. return CURLE_OUT_OF_MEMORY;
  2973. if(!*contenttype)
  2974. /* ignore empty data */
  2975. free(contenttype);
  2976. else {
  2977. Curl_safefree(data->info.contenttype);
  2978. data->info.contenttype = contenttype;
  2979. }
  2980. }
  2981. else if(checkprefix("Server:", k->p)) {
  2982. char *server_name = Curl_copy_header_value(k->p);
  2983. /* Turn off pipelining if the server version is blacklisted */
  2984. if(conn->bundle && conn->bundle->server_supports_pipelining) {
  2985. if(Curl_pipeline_server_blacklisted(data, server_name))
  2986. conn->bundle->server_supports_pipelining = FALSE;
  2987. }
  2988. Curl_safefree(server_name);
  2989. }
  2990. else if((conn->httpversion == 10) &&
  2991. conn->bits.httpproxy &&
  2992. Curl_compareheader(k->p,
  2993. "Proxy-Connection:", "keep-alive")) {
  2994. /*
  2995. * When a HTTP/1.0 reply comes when using a proxy, the
  2996. * 'Proxy-Connection: keep-alive' line tells us the
  2997. * connection will be kept alive for our pleasure.
  2998. * Default action for 1.0 is to close.
  2999. */
  3000. connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
  3001. infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
  3002. }
  3003. else if((conn->httpversion == 11) &&
  3004. conn->bits.httpproxy &&
  3005. Curl_compareheader(k->p,
  3006. "Proxy-Connection:", "close")) {
  3007. /*
  3008. * We get a HTTP/1.1 response from a proxy and it says it'll
  3009. * close down after this transfer.
  3010. */
  3011. connclose(conn, "Proxy-Connection: asked to close after done");
  3012. infof(data, "HTTP/1.1 proxy connection set close!\n");
  3013. }
  3014. else if((conn->httpversion == 10) &&
  3015. Curl_compareheader(k->p, "Connection:", "keep-alive")) {
  3016. /*
  3017. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  3018. * tells us the connection will be kept alive for our
  3019. * pleasure. Default action for 1.0 is to close.
  3020. *
  3021. * [RFC2068, section 19.7.1] */
  3022. connkeep(conn, "Connection keep-alive");
  3023. infof(data, "HTTP/1.0 connection set to keep alive!\n");
  3024. }
  3025. else if(Curl_compareheader(k->p, "Connection:", "close")) {
  3026. /*
  3027. * [RFC 2616, section 8.1.2.1]
  3028. * "Connection: close" is HTTP/1.1 language and means that
  3029. * the connection will close when this request has been
  3030. * served.
  3031. */
  3032. connclose(conn, "Connection: close used");
  3033. }
  3034. else if(checkprefix("Transfer-Encoding:", k->p)) {
  3035. /* One or more encodings. We check for chunked and/or a compression
  3036. algorithm. */
  3037. /*
  3038. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  3039. * means that the server will send a series of "chunks". Each
  3040. * chunk starts with line with info (including size of the
  3041. * coming block) (terminated with CRLF), then a block of data
  3042. * with the previously mentioned size. There can be any amount
  3043. * of chunks, and a chunk-data set to zero signals the
  3044. * end-of-chunks. */
  3045. char *start;
  3046. /* Find the first non-space letter */
  3047. start = k->p + 18;
  3048. for(;;) {
  3049. /* skip whitespaces and commas */
  3050. while(*start && (ISSPACE(*start) || (*start == ',')))
  3051. start++;
  3052. if(checkprefix("chunked", start)) {
  3053. k->chunk = TRUE; /* chunks coming our way */
  3054. /* init our chunky engine */
  3055. Curl_httpchunk_init(conn);
  3056. start += 7;
  3057. }
  3058. if(k->auto_decoding)
  3059. /* TODO: we only support the first mentioned compression for now */
  3060. break;
  3061. if(checkprefix("identity", start)) {
  3062. k->auto_decoding = IDENTITY;
  3063. start += 8;
  3064. }
  3065. else if(checkprefix("deflate", start)) {
  3066. k->auto_decoding = DEFLATE;
  3067. start += 7;
  3068. }
  3069. else if(checkprefix("gzip", start)) {
  3070. k->auto_decoding = GZIP;
  3071. start += 4;
  3072. }
  3073. else if(checkprefix("x-gzip", start)) {
  3074. k->auto_decoding = GZIP;
  3075. start += 6;
  3076. }
  3077. else if(checkprefix("compress", start)) {
  3078. k->auto_decoding = COMPRESS;
  3079. start += 8;
  3080. }
  3081. else if(checkprefix("x-compress", start)) {
  3082. k->auto_decoding = COMPRESS;
  3083. start += 10;
  3084. }
  3085. else
  3086. /* unknown! */
  3087. break;
  3088. }
  3089. }
  3090. else if(checkprefix("Content-Encoding:", k->p) &&
  3091. (data->set.str[STRING_ENCODING] ||
  3092. conn->httpversion == 20)) {
  3093. /*
  3094. * Process Content-Encoding. Look for the values: identity,
  3095. * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
  3096. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  3097. * 2616). zlib cannot handle compress. However, errors are
  3098. * handled further down when the response body is processed
  3099. */
  3100. char *start;
  3101. /* Find the first non-space letter */
  3102. start = k->p + 17;
  3103. while(*start && ISSPACE(*start))
  3104. start++;
  3105. /* Record the content-encoding for later use */
  3106. if(checkprefix("identity", start))
  3107. k->auto_decoding = IDENTITY;
  3108. else if(checkprefix("deflate", start))
  3109. k->auto_decoding = DEFLATE;
  3110. else if(checkprefix("gzip", start)
  3111. || checkprefix("x-gzip", start))
  3112. k->auto_decoding = GZIP;
  3113. else if(checkprefix("compress", start)
  3114. || checkprefix("x-compress", start))
  3115. k->auto_decoding = COMPRESS;
  3116. }
  3117. else if(checkprefix("Content-Range:", k->p)) {
  3118. /* Content-Range: bytes [num]-
  3119. Content-Range: bytes: [num]-
  3120. Content-Range: [num]-
  3121. Content-Range: [asterisk]/[total]
  3122. The second format was added since Sun's webserver
  3123. JavaWebServer/1.1.1 obviously sends the header this way!
  3124. The third added since some servers use that!
  3125. The forth means the requested range was unsatisfied.
  3126. */
  3127. char *ptr = k->p + 14;
  3128. /* Move forward until first digit or asterisk */
  3129. while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
  3130. ptr++;
  3131. /* if it truly stopped on a digit */
  3132. if(ISDIGIT(*ptr)) {
  3133. k->offset = curlx_strtoofft(ptr, NULL, 10);
  3134. if(data->state.resume_from == k->offset)
  3135. /* we asked for a resume and we got it */
  3136. k->content_range = TRUE;
  3137. }
  3138. else
  3139. data->state.resume_from = 0; /* get everything */
  3140. }
  3141. #if !defined(CURL_DISABLE_COOKIES)
  3142. else if(data->cookies &&
  3143. checkprefix("Set-Cookie:", k->p)) {
  3144. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
  3145. CURL_LOCK_ACCESS_SINGLE);
  3146. Curl_cookie_add(data,
  3147. data->cookies, TRUE, k->p+11,
  3148. /* If there is a custom-set Host: name, use it
  3149. here, or else use real peer host name. */
  3150. conn->allocptr.cookiehost?
  3151. conn->allocptr.cookiehost:conn->host.name,
  3152. data->state.path);
  3153. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  3154. }
  3155. #endif
  3156. else if(checkprefix("Last-Modified:", k->p) &&
  3157. (data->set.timecondition || data->set.get_filetime) ) {
  3158. time_t secs=time(NULL);
  3159. k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
  3160. &secs);
  3161. if(data->set.get_filetime)
  3162. data->info.filetime = (long)k->timeofdoc;
  3163. }
  3164. else if((checkprefix("WWW-Authenticate:", k->p) &&
  3165. (401 == k->httpcode)) ||
  3166. (checkprefix("Proxy-authenticate:", k->p) &&
  3167. (407 == k->httpcode))) {
  3168. bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
  3169. char *auth = Curl_copy_header_value(k->p);
  3170. if(!auth)
  3171. return CURLE_OUT_OF_MEMORY;
  3172. result = Curl_http_input_auth(conn, proxy, auth);
  3173. Curl_safefree(auth);
  3174. if(result)
  3175. return result;
  3176. }
  3177. else if((k->httpcode >= 300 && k->httpcode < 400) &&
  3178. checkprefix("Location:", k->p) &&
  3179. !data->req.location) {
  3180. /* this is the URL that the server advises us to use instead */
  3181. char *location = Curl_copy_header_value(k->p);
  3182. if(!location)
  3183. return CURLE_OUT_OF_MEMORY;
  3184. if(!*location)
  3185. /* ignore empty data */
  3186. free(location);
  3187. else {
  3188. data->req.location = location;
  3189. if(data->set.http_follow_location) {
  3190. DEBUGASSERT(!data->req.newurl);
  3191. data->req.newurl = strdup(data->req.location); /* clone */
  3192. if(!data->req.newurl)
  3193. return CURLE_OUT_OF_MEMORY;
  3194. /* some cases of POST and PUT etc needs to rewind the data
  3195. stream at this point */
  3196. result = http_perhapsrewind(conn);
  3197. if(result)
  3198. return result;
  3199. }
  3200. }
  3201. }
  3202. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  3203. result = Curl_rtsp_parseheader(conn, k->p);
  3204. if(result)
  3205. return result;
  3206. }
  3207. /*
  3208. * End of header-checks. Write them to the client.
  3209. */
  3210. writetype = CLIENTWRITE_HEADER;
  3211. if(data->set.include_header)
  3212. writetype |= CLIENTWRITE_BODY;
  3213. if(data->set.verbose)
  3214. Curl_debug(data, CURLINFO_HEADER_IN,
  3215. k->p, (size_t)k->hbuflen, conn);
  3216. result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
  3217. if(result)
  3218. return result;
  3219. data->info.header_size += (long)k->hbuflen;
  3220. data->req.headerbytecount += (long)k->hbuflen;
  3221. /* reset hbufp pointer && hbuflen */
  3222. k->hbufp = data->state.headerbuff;
  3223. k->hbuflen = 0;
  3224. }
  3225. while(!*stop_reading && *k->str); /* header line within buffer */
  3226. /* We might have reached the end of the header part here, but
  3227. there might be a non-header part left in the end of the read
  3228. buffer. */
  3229. return CURLE_OK;
  3230. }
  3231. #endif /* CURL_DISABLE_HTTP */