http.c 120 KB

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