http.c 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  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. #ifdef USE_HYPER
  43. #include <hyper.h>
  44. #endif
  45. #include "urldata.h"
  46. #include <curl/curl.h>
  47. #include "transfer.h"
  48. #include "sendf.h"
  49. #include "formdata.h"
  50. #include "mime.h"
  51. #include "progress.h"
  52. #include "curl_base64.h"
  53. #include "cookie.h"
  54. #include "vauth/vauth.h"
  55. #include "vtls/vtls.h"
  56. #include "http_digest.h"
  57. #include "http_ntlm.h"
  58. #include "curl_ntlm_wb.h"
  59. #include "http_negotiate.h"
  60. #include "http_aws_sigv4.h"
  61. #include "url.h"
  62. #include "share.h"
  63. #include "hostip.h"
  64. #include "http.h"
  65. #include "select.h"
  66. #include "parsedate.h" /* for the week day and month names */
  67. #include "strtoofft.h"
  68. #include "multiif.h"
  69. #include "strcase.h"
  70. #include "content_encoding.h"
  71. #include "http_proxy.h"
  72. #include "warnless.h"
  73. #include "non-ascii.h"
  74. #include "http2.h"
  75. #include "connect.h"
  76. #include "strdup.h"
  77. #include "altsvc.h"
  78. #include "hsts.h"
  79. #include "c-hyper.h"
  80. /* The last 3 #include files should be in this order */
  81. #include "curl_printf.h"
  82. #include "curl_memory.h"
  83. #include "memdebug.h"
  84. /*
  85. * Forward declarations.
  86. */
  87. static int http_getsock_do(struct Curl_easy *data,
  88. struct connectdata *conn,
  89. curl_socket_t *socks);
  90. static bool http_should_fail(struct Curl_easy *data);
  91. #ifndef CURL_DISABLE_PROXY
  92. static CURLcode add_haproxy_protocol_header(struct Curl_easy *data);
  93. #endif
  94. #ifdef USE_SSL
  95. static CURLcode https_connecting(struct Curl_easy *data, bool *done);
  96. static int https_getsock(struct Curl_easy *data,
  97. struct connectdata *conn,
  98. curl_socket_t *socks);
  99. #else
  100. #define https_connecting(x,y) CURLE_COULDNT_CONNECT
  101. #endif
  102. static CURLcode http_setup_conn(struct Curl_easy *data,
  103. struct connectdata *conn);
  104. /*
  105. * HTTP handler interface.
  106. */
  107. const struct Curl_handler Curl_handler_http = {
  108. "HTTP", /* scheme */
  109. http_setup_conn, /* setup_connection */
  110. Curl_http, /* do_it */
  111. Curl_http_done, /* done */
  112. ZERO_NULL, /* do_more */
  113. Curl_http_connect, /* connect_it */
  114. ZERO_NULL, /* connecting */
  115. ZERO_NULL, /* doing */
  116. ZERO_NULL, /* proto_getsock */
  117. http_getsock_do, /* doing_getsock */
  118. ZERO_NULL, /* domore_getsock */
  119. ZERO_NULL, /* perform_getsock */
  120. ZERO_NULL, /* disconnect */
  121. ZERO_NULL, /* readwrite */
  122. ZERO_NULL, /* connection_check */
  123. ZERO_NULL, /* attach connection */
  124. PORT_HTTP, /* defport */
  125. CURLPROTO_HTTP, /* protocol */
  126. CURLPROTO_HTTP, /* family */
  127. PROTOPT_CREDSPERREQUEST | /* flags */
  128. PROTOPT_USERPWDCTRL
  129. };
  130. #ifdef USE_SSL
  131. /*
  132. * HTTPS handler interface.
  133. */
  134. const struct Curl_handler Curl_handler_https = {
  135. "HTTPS", /* scheme */
  136. http_setup_conn, /* setup_connection */
  137. Curl_http, /* do_it */
  138. Curl_http_done, /* done */
  139. ZERO_NULL, /* do_more */
  140. Curl_http_connect, /* connect_it */
  141. https_connecting, /* connecting */
  142. ZERO_NULL, /* doing */
  143. https_getsock, /* proto_getsock */
  144. http_getsock_do, /* doing_getsock */
  145. ZERO_NULL, /* domore_getsock */
  146. ZERO_NULL, /* perform_getsock */
  147. ZERO_NULL, /* disconnect */
  148. ZERO_NULL, /* readwrite */
  149. ZERO_NULL, /* connection_check */
  150. ZERO_NULL, /* attach connection */
  151. PORT_HTTPS, /* defport */
  152. CURLPROTO_HTTPS, /* protocol */
  153. CURLPROTO_HTTP, /* family */
  154. PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN | /* flags */
  155. PROTOPT_USERPWDCTRL
  156. };
  157. #endif
  158. static CURLcode http_setup_conn(struct Curl_easy *data,
  159. struct connectdata *conn)
  160. {
  161. /* allocate the HTTP-specific struct for the Curl_easy, only to survive
  162. during this request */
  163. struct HTTP *http;
  164. DEBUGASSERT(data->req.p.http == NULL);
  165. http = calloc(1, sizeof(struct HTTP));
  166. if(!http)
  167. return CURLE_OUT_OF_MEMORY;
  168. Curl_mime_initpart(&http->form, data);
  169. data->req.p.http = http;
  170. if(data->state.httpwant == CURL_HTTP_VERSION_3) {
  171. if(conn->handler->flags & PROTOPT_SSL)
  172. /* Only go HTTP/3 directly on HTTPS URLs. It needs a UDP socket and does
  173. the QUIC dance. */
  174. conn->transport = TRNSPRT_QUIC;
  175. else {
  176. failf(data, "HTTP/3 requested for non-HTTPS URL");
  177. return CURLE_URL_MALFORMAT;
  178. }
  179. }
  180. else {
  181. if(!CONN_INUSE(conn))
  182. /* if not already multi-using, setup connection details */
  183. Curl_http2_setup_conn(conn);
  184. Curl_http2_setup_req(data);
  185. }
  186. return CURLE_OK;
  187. }
  188. #ifndef CURL_DISABLE_PROXY
  189. /*
  190. * checkProxyHeaders() checks the linked list of custom proxy headers
  191. * if proxy headers are not available, then it will lookup into http header
  192. * link list
  193. *
  194. * It takes a connectdata struct as input to see if this is a proxy request or
  195. * not, as it then might check a different header list. Provide the header
  196. * prefix without colon!
  197. */
  198. char *Curl_checkProxyheaders(struct Curl_easy *data,
  199. const struct connectdata *conn,
  200. const char *thisheader)
  201. {
  202. struct curl_slist *head;
  203. size_t thislen = strlen(thisheader);
  204. for(head = (conn->bits.proxy && data->set.sep_headers) ?
  205. data->set.proxyheaders : data->set.headers;
  206. head; head = head->next) {
  207. if(strncasecompare(head->data, thisheader, thislen) &&
  208. Curl_headersep(head->data[thislen]))
  209. return head->data;
  210. }
  211. return NULL;
  212. }
  213. #else
  214. /* disabled */
  215. #define Curl_checkProxyheaders(x,y,z) NULL
  216. #endif
  217. /*
  218. * Strip off leading and trailing whitespace from the value in the
  219. * given HTTP header line and return a strdupped copy. Returns NULL in
  220. * case of allocation failure. Returns an empty string if the header value
  221. * consists entirely of whitespace.
  222. */
  223. char *Curl_copy_header_value(const char *header)
  224. {
  225. const char *start;
  226. const char *end;
  227. char *value;
  228. size_t len;
  229. /* Find the end of the header name */
  230. while(*header && (*header != ':'))
  231. ++header;
  232. if(*header)
  233. /* Skip over colon */
  234. ++header;
  235. /* Find the first non-space letter */
  236. start = header;
  237. while(*start && ISSPACE(*start))
  238. start++;
  239. /* data is in the host encoding so
  240. use '\r' and '\n' instead of 0x0d and 0x0a */
  241. end = strchr(start, '\r');
  242. if(!end)
  243. end = strchr(start, '\n');
  244. if(!end)
  245. end = strchr(start, '\0');
  246. if(!end)
  247. return NULL;
  248. /* skip all trailing space letters */
  249. while((end > start) && ISSPACE(*end))
  250. end--;
  251. /* get length of the type */
  252. len = end - start + 1;
  253. value = malloc(len + 1);
  254. if(!value)
  255. return NULL;
  256. memcpy(value, start, len);
  257. value[len] = 0; /* null-terminate */
  258. return value;
  259. }
  260. #ifndef CURL_DISABLE_HTTP_AUTH
  261. /*
  262. * http_output_basic() sets up an Authorization: header (or the proxy version)
  263. * for HTTP Basic authentication.
  264. *
  265. * Returns CURLcode.
  266. */
  267. static CURLcode http_output_basic(struct Curl_easy *data, bool proxy)
  268. {
  269. size_t size = 0;
  270. char *authorization = NULL;
  271. char **userp;
  272. const char *user;
  273. const char *pwd;
  274. CURLcode result;
  275. char *out;
  276. /* credentials are unique per transfer for HTTP, do not use the ones for the
  277. connection */
  278. if(proxy) {
  279. #ifndef CURL_DISABLE_PROXY
  280. userp = &data->state.aptr.proxyuserpwd;
  281. user = data->state.aptr.proxyuser;
  282. pwd = data->state.aptr.proxypasswd;
  283. #else
  284. return CURLE_NOT_BUILT_IN;
  285. #endif
  286. }
  287. else {
  288. userp = &data->state.aptr.userpwd;
  289. user = data->state.aptr.user;
  290. pwd = data->state.aptr.passwd;
  291. }
  292. out = aprintf("%s:%s", user, pwd ? pwd : "");
  293. if(!out)
  294. return CURLE_OUT_OF_MEMORY;
  295. result = Curl_base64_encode(data, out, strlen(out), &authorization, &size);
  296. if(result)
  297. goto fail;
  298. if(!authorization) {
  299. result = CURLE_REMOTE_ACCESS_DENIED;
  300. goto fail;
  301. }
  302. free(*userp);
  303. *userp = aprintf("%sAuthorization: Basic %s\r\n",
  304. proxy ? "Proxy-" : "",
  305. authorization);
  306. free(authorization);
  307. if(!*userp) {
  308. result = CURLE_OUT_OF_MEMORY;
  309. goto fail;
  310. }
  311. fail:
  312. free(out);
  313. return result;
  314. }
  315. /*
  316. * http_output_bearer() sets up an Authorization: header
  317. * for HTTP Bearer authentication.
  318. *
  319. * Returns CURLcode.
  320. */
  321. static CURLcode http_output_bearer(struct Curl_easy *data)
  322. {
  323. char **userp;
  324. CURLcode result = CURLE_OK;
  325. userp = &data->state.aptr.userpwd;
  326. free(*userp);
  327. *userp = aprintf("Authorization: Bearer %s\r\n",
  328. data->set.str[STRING_BEARER]);
  329. if(!*userp) {
  330. result = CURLE_OUT_OF_MEMORY;
  331. goto fail;
  332. }
  333. fail:
  334. return result;
  335. }
  336. #endif
  337. /* pickoneauth() selects the most favourable authentication method from the
  338. * ones available and the ones we want.
  339. *
  340. * return TRUE if one was picked
  341. */
  342. static bool pickoneauth(struct auth *pick, unsigned long mask)
  343. {
  344. bool picked;
  345. /* only deal with authentication we want */
  346. unsigned long avail = pick->avail & pick->want & mask;
  347. picked = TRUE;
  348. /* The order of these checks is highly relevant, as this will be the order
  349. of preference in case of the existence of multiple accepted types. */
  350. if(avail & CURLAUTH_NEGOTIATE)
  351. pick->picked = CURLAUTH_NEGOTIATE;
  352. else if(avail & CURLAUTH_BEARER)
  353. pick->picked = CURLAUTH_BEARER;
  354. else if(avail & CURLAUTH_DIGEST)
  355. pick->picked = CURLAUTH_DIGEST;
  356. else if(avail & CURLAUTH_NTLM)
  357. pick->picked = CURLAUTH_NTLM;
  358. else if(avail & CURLAUTH_NTLM_WB)
  359. pick->picked = CURLAUTH_NTLM_WB;
  360. else if(avail & CURLAUTH_BASIC)
  361. pick->picked = CURLAUTH_BASIC;
  362. else if(avail & CURLAUTH_AWS_SIGV4)
  363. pick->picked = CURLAUTH_AWS_SIGV4;
  364. else {
  365. pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
  366. picked = FALSE;
  367. }
  368. pick->avail = CURLAUTH_NONE; /* clear it here */
  369. return picked;
  370. }
  371. /*
  372. * http_perhapsrewind()
  373. *
  374. * If we are doing POST or PUT {
  375. * If we have more data to send {
  376. * If we are doing NTLM {
  377. * Keep sending since we must not disconnect
  378. * }
  379. * else {
  380. * If there is more than just a little data left to send, close
  381. * the current connection by force.
  382. * }
  383. * }
  384. * If we have sent any data {
  385. * If we don't have track of all the data {
  386. * call app to tell it to rewind
  387. * }
  388. * else {
  389. * rewind internally so that the operation can restart fine
  390. * }
  391. * }
  392. * }
  393. */
  394. static CURLcode http_perhapsrewind(struct Curl_easy *data,
  395. struct connectdata *conn)
  396. {
  397. struct HTTP *http = data->req.p.http;
  398. curl_off_t bytessent;
  399. curl_off_t expectsend = -1; /* default is unknown */
  400. if(!http)
  401. /* If this is still NULL, we have not reach very far and we can safely
  402. skip this rewinding stuff */
  403. return CURLE_OK;
  404. switch(data->state.httpreq) {
  405. case HTTPREQ_GET:
  406. case HTTPREQ_HEAD:
  407. return CURLE_OK;
  408. default:
  409. break;
  410. }
  411. bytessent = data->req.writebytecount;
  412. if(conn->bits.authneg) {
  413. /* This is a state where we are known to be negotiating and we don't send
  414. any data then. */
  415. expectsend = 0;
  416. }
  417. else if(!conn->bits.protoconnstart) {
  418. /* HTTP CONNECT in progress: there is no body */
  419. expectsend = 0;
  420. }
  421. else {
  422. /* figure out how much data we are expected to send */
  423. switch(data->state.httpreq) {
  424. case HTTPREQ_POST:
  425. case HTTPREQ_PUT:
  426. if(data->state.infilesize != -1)
  427. expectsend = data->state.infilesize;
  428. break;
  429. case HTTPREQ_POST_FORM:
  430. case HTTPREQ_POST_MIME:
  431. expectsend = http->postsize;
  432. break;
  433. default:
  434. break;
  435. }
  436. }
  437. conn->bits.rewindaftersend = FALSE; /* default */
  438. if((expectsend == -1) || (expectsend > bytessent)) {
  439. #if defined(USE_NTLM)
  440. /* There is still data left to send */
  441. if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
  442. (data->state.authhost.picked == CURLAUTH_NTLM) ||
  443. (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
  444. (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
  445. if(((expectsend - bytessent) < 2000) ||
  446. (conn->http_ntlm_state != NTLMSTATE_NONE) ||
  447. (conn->proxy_ntlm_state != NTLMSTATE_NONE)) {
  448. /* The NTLM-negotiation has started *OR* there is just a little (<2K)
  449. data left to send, keep on sending. */
  450. /* rewind data when completely done sending! */
  451. if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) {
  452. conn->bits.rewindaftersend = TRUE;
  453. infof(data, "Rewind stream after send");
  454. }
  455. return CURLE_OK;
  456. }
  457. if(conn->bits.close)
  458. /* this is already marked to get closed */
  459. return CURLE_OK;
  460. infof(data, "NTLM send, close instead of sending %"
  461. CURL_FORMAT_CURL_OFF_T " bytes",
  462. (curl_off_t)(expectsend - bytessent));
  463. }
  464. #endif
  465. #if defined(USE_SPNEGO)
  466. /* There is still data left to send */
  467. if((data->state.authproxy.picked == CURLAUTH_NEGOTIATE) ||
  468. (data->state.authhost.picked == CURLAUTH_NEGOTIATE)) {
  469. if(((expectsend - bytessent) < 2000) ||
  470. (conn->http_negotiate_state != GSS_AUTHNONE) ||
  471. (conn->proxy_negotiate_state != GSS_AUTHNONE)) {
  472. /* The NEGOTIATE-negotiation has started *OR*
  473. there is just a little (<2K) data left to send, keep on sending. */
  474. /* rewind data when completely done sending! */
  475. if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) {
  476. conn->bits.rewindaftersend = TRUE;
  477. infof(data, "Rewind stream after send");
  478. }
  479. return CURLE_OK;
  480. }
  481. if(conn->bits.close)
  482. /* this is already marked to get closed */
  483. return CURLE_OK;
  484. infof(data, "NEGOTIATE send, close instead of sending %"
  485. CURL_FORMAT_CURL_OFF_T " bytes",
  486. (curl_off_t)(expectsend - bytessent));
  487. }
  488. #endif
  489. /* This is not NEGOTIATE/NTLM or many bytes left to send: close */
  490. streamclose(conn, "Mid-auth HTTP and much data left to send");
  491. data->req.size = 0; /* don't download any more than 0 bytes */
  492. /* There still is data left to send, but this connection is marked for
  493. closure so we can safely do the rewind right now */
  494. }
  495. if(bytessent)
  496. /* we rewind now at once since if we already sent something */
  497. return Curl_readrewind(data);
  498. return CURLE_OK;
  499. }
  500. /*
  501. * Curl_http_auth_act() gets called when all HTTP headers have been received
  502. * and it checks what authentication methods that are available and decides
  503. * which one (if any) to use. It will set 'newurl' if an auth method was
  504. * picked.
  505. */
  506. CURLcode Curl_http_auth_act(struct Curl_easy *data)
  507. {
  508. struct connectdata *conn = data->conn;
  509. bool pickhost = FALSE;
  510. bool pickproxy = FALSE;
  511. CURLcode result = CURLE_OK;
  512. unsigned long authmask = ~0ul;
  513. if(!data->set.str[STRING_BEARER])
  514. authmask &= (unsigned long)~CURLAUTH_BEARER;
  515. if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
  516. /* this is a transient response code, ignore */
  517. return CURLE_OK;
  518. if(data->state.authproblem)
  519. return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
  520. if((conn->bits.user_passwd || data->set.str[STRING_BEARER]) &&
  521. ((data->req.httpcode == 401) ||
  522. (conn->bits.authneg && data->req.httpcode < 300))) {
  523. pickhost = pickoneauth(&data->state.authhost, authmask);
  524. if(!pickhost)
  525. data->state.authproblem = TRUE;
  526. if(data->state.authhost.picked == CURLAUTH_NTLM &&
  527. conn->httpversion > 11) {
  528. infof(data, "Forcing HTTP/1.1 for NTLM");
  529. connclose(conn, "Force HTTP/1.1 connection");
  530. data->state.httpwant = CURL_HTTP_VERSION_1_1;
  531. }
  532. }
  533. #ifndef CURL_DISABLE_PROXY
  534. if(conn->bits.proxy_user_passwd &&
  535. ((data->req.httpcode == 407) ||
  536. (conn->bits.authneg && data->req.httpcode < 300))) {
  537. pickproxy = pickoneauth(&data->state.authproxy,
  538. authmask & ~CURLAUTH_BEARER);
  539. if(!pickproxy)
  540. data->state.authproblem = TRUE;
  541. }
  542. #endif
  543. if(pickhost || pickproxy) {
  544. if((data->state.httpreq != HTTPREQ_GET) &&
  545. (data->state.httpreq != HTTPREQ_HEAD) &&
  546. !conn->bits.rewindaftersend) {
  547. result = http_perhapsrewind(data, conn);
  548. if(result)
  549. return result;
  550. }
  551. /* In case this is GSS auth, the newurl field is already allocated so
  552. we must make sure to free it before allocating a new one. As figured
  553. out in bug #2284386 */
  554. Curl_safefree(data->req.newurl);
  555. data->req.newurl = strdup(data->state.url); /* clone URL */
  556. if(!data->req.newurl)
  557. return CURLE_OUT_OF_MEMORY;
  558. }
  559. else if((data->req.httpcode < 300) &&
  560. (!data->state.authhost.done) &&
  561. conn->bits.authneg) {
  562. /* no (known) authentication available,
  563. authentication is not "done" yet and
  564. no authentication seems to be required and
  565. we didn't try HEAD or GET */
  566. if((data->state.httpreq != HTTPREQ_GET) &&
  567. (data->state.httpreq != HTTPREQ_HEAD)) {
  568. data->req.newurl = strdup(data->state.url); /* clone URL */
  569. if(!data->req.newurl)
  570. return CURLE_OUT_OF_MEMORY;
  571. data->state.authhost.done = TRUE;
  572. }
  573. }
  574. if(http_should_fail(data)) {
  575. failf(data, "The requested URL returned error: %d",
  576. data->req.httpcode);
  577. result = CURLE_HTTP_RETURNED_ERROR;
  578. }
  579. return result;
  580. }
  581. #ifndef CURL_DISABLE_HTTP_AUTH
  582. /*
  583. * Output the correct authentication header depending on the auth type
  584. * and whether or not it is to a proxy.
  585. */
  586. static CURLcode
  587. output_auth_headers(struct Curl_easy *data,
  588. struct connectdata *conn,
  589. struct auth *authstatus,
  590. const char *request,
  591. const char *path,
  592. bool proxy)
  593. {
  594. const char *auth = NULL;
  595. CURLcode result = CURLE_OK;
  596. #ifdef CURL_DISABLE_CRYPTO_AUTH
  597. (void)request;
  598. (void)path;
  599. #endif
  600. #ifndef CURL_DISABLE_CRYPTO_AUTH
  601. if(authstatus->picked == CURLAUTH_AWS_SIGV4) {
  602. auth = "AWS_SIGV4";
  603. result = Curl_output_aws_sigv4(data, proxy);
  604. if(result)
  605. return result;
  606. }
  607. else
  608. #endif
  609. #ifdef USE_SPNEGO
  610. if(authstatus->picked == CURLAUTH_NEGOTIATE) {
  611. auth = "Negotiate";
  612. result = Curl_output_negotiate(data, conn, proxy);
  613. if(result)
  614. return result;
  615. }
  616. else
  617. #endif
  618. #ifdef USE_NTLM
  619. if(authstatus->picked == CURLAUTH_NTLM) {
  620. auth = "NTLM";
  621. result = Curl_output_ntlm(data, proxy);
  622. if(result)
  623. return result;
  624. }
  625. else
  626. #endif
  627. #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
  628. if(authstatus->picked == CURLAUTH_NTLM_WB) {
  629. auth = "NTLM_WB";
  630. result = Curl_output_ntlm_wb(data, conn, proxy);
  631. if(result)
  632. return result;
  633. }
  634. else
  635. #endif
  636. #ifndef CURL_DISABLE_CRYPTO_AUTH
  637. if(authstatus->picked == CURLAUTH_DIGEST) {
  638. auth = "Digest";
  639. result = Curl_output_digest(data,
  640. proxy,
  641. (const unsigned char *)request,
  642. (const unsigned char *)path);
  643. if(result)
  644. return result;
  645. }
  646. else
  647. #endif
  648. if(authstatus->picked == CURLAUTH_BASIC) {
  649. /* Basic */
  650. if(
  651. #ifndef CURL_DISABLE_PROXY
  652. (proxy && conn->bits.proxy_user_passwd &&
  653. !Curl_checkProxyheaders(data, conn, "Proxy-authorization")) ||
  654. #endif
  655. (!proxy && conn->bits.user_passwd &&
  656. !Curl_checkheaders(data, "Authorization"))) {
  657. auth = "Basic";
  658. result = http_output_basic(data, proxy);
  659. if(result)
  660. return result;
  661. }
  662. /* NOTE: this function should set 'done' TRUE, as the other auth
  663. functions work that way */
  664. authstatus->done = TRUE;
  665. }
  666. if(authstatus->picked == CURLAUTH_BEARER) {
  667. /* Bearer */
  668. if((!proxy && data->set.str[STRING_BEARER] &&
  669. !Curl_checkheaders(data, "Authorization"))) {
  670. auth = "Bearer";
  671. result = http_output_bearer(data);
  672. if(result)
  673. return result;
  674. }
  675. /* NOTE: this function should set 'done' TRUE, as the other auth
  676. functions work that way */
  677. authstatus->done = TRUE;
  678. }
  679. if(auth) {
  680. #ifndef CURL_DISABLE_PROXY
  681. infof(data, "%s auth using %s with user '%s'",
  682. proxy ? "Proxy" : "Server", auth,
  683. proxy ? (data->state.aptr.proxyuser ?
  684. data->state.aptr.proxyuser : "") :
  685. (data->state.aptr.user ?
  686. data->state.aptr.user : ""));
  687. #else
  688. infof(data, "Server auth using %s with user '%s'",
  689. auth, data->state.aptr.user ?
  690. data->state.aptr.user : "");
  691. #endif
  692. authstatus->multipass = (!authstatus->done) ? TRUE : FALSE;
  693. }
  694. else
  695. authstatus->multipass = FALSE;
  696. return CURLE_OK;
  697. }
  698. /**
  699. * Curl_http_output_auth() setups the authentication headers for the
  700. * host/proxy and the correct authentication
  701. * method. data->state.authdone is set to TRUE when authentication is
  702. * done.
  703. *
  704. * @param conn all information about the current connection
  705. * @param request pointer to the request keyword
  706. * @param path pointer to the requested path; should include query part
  707. * @param proxytunnel boolean if this is the request setting up a "proxy
  708. * tunnel"
  709. *
  710. * @returns CURLcode
  711. */
  712. CURLcode
  713. Curl_http_output_auth(struct Curl_easy *data,
  714. struct connectdata *conn,
  715. const char *request,
  716. Curl_HttpReq httpreq,
  717. const char *path,
  718. bool proxytunnel) /* TRUE if this is the request setting
  719. up the proxy tunnel */
  720. {
  721. CURLcode result = CURLE_OK;
  722. struct auth *authhost;
  723. struct auth *authproxy;
  724. DEBUGASSERT(data);
  725. authhost = &data->state.authhost;
  726. authproxy = &data->state.authproxy;
  727. if(
  728. #ifndef CURL_DISABLE_PROXY
  729. (conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
  730. #endif
  731. conn->bits.user_passwd || data->set.str[STRING_BEARER])
  732. /* continue please */;
  733. else {
  734. authhost->done = TRUE;
  735. authproxy->done = TRUE;
  736. return CURLE_OK; /* no authentication with no user or password */
  737. }
  738. if(authhost->want && !authhost->picked)
  739. /* The app has selected one or more methods, but none has been picked
  740. so far by a server round-trip. Then we set the picked one to the
  741. want one, and if this is one single bit it'll be used instantly. */
  742. authhost->picked = authhost->want;
  743. if(authproxy->want && !authproxy->picked)
  744. /* The app has selected one or more methods, but none has been picked so
  745. far by a proxy round-trip. Then we set the picked one to the want one,
  746. and if this is one single bit it'll be used instantly. */
  747. authproxy->picked = authproxy->want;
  748. #ifndef CURL_DISABLE_PROXY
  749. /* Send proxy authentication header if needed */
  750. if(conn->bits.httpproxy &&
  751. (conn->bits.tunnel_proxy == (bit)proxytunnel)) {
  752. result = output_auth_headers(data, conn, authproxy, request, path, TRUE);
  753. if(result)
  754. return result;
  755. }
  756. else
  757. #else
  758. (void)proxytunnel;
  759. #endif /* CURL_DISABLE_PROXY */
  760. /* we have no proxy so let's pretend we're done authenticating
  761. with it */
  762. authproxy->done = TRUE;
  763. /* To prevent the user+password to get sent to other than the original
  764. host due to a location-follow, we do some weirdo checks here */
  765. if(!data->state.this_is_a_follow ||
  766. #ifndef CURL_DISABLE_NETRC
  767. conn->bits.netrc ||
  768. #endif
  769. !data->state.first_host ||
  770. data->set.allow_auth_to_other_hosts ||
  771. strcasecompare(data->state.first_host, conn->host.name)) {
  772. result = output_auth_headers(data, conn, authhost, request, path, FALSE);
  773. }
  774. else
  775. authhost->done = TRUE;
  776. if(((authhost->multipass && !authhost->done) ||
  777. (authproxy->multipass && !authproxy->done)) &&
  778. (httpreq != HTTPREQ_GET) &&
  779. (httpreq != HTTPREQ_HEAD)) {
  780. /* Auth is required and we are not authenticated yet. Make a PUT or POST
  781. with content-length zero as a "probe". */
  782. conn->bits.authneg = TRUE;
  783. }
  784. else
  785. conn->bits.authneg = FALSE;
  786. return result;
  787. }
  788. #else
  789. /* when disabled */
  790. CURLcode
  791. Curl_http_output_auth(struct Curl_easy *data,
  792. struct connectdata *conn,
  793. const char *request,
  794. Curl_HttpReq httpreq,
  795. const char *path,
  796. bool proxytunnel)
  797. {
  798. (void)data;
  799. (void)conn;
  800. (void)request;
  801. (void)httpreq;
  802. (void)path;
  803. (void)proxytunnel;
  804. return CURLE_OK;
  805. }
  806. #endif
  807. /*
  808. * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
  809. * headers. They are dealt with both in the transfer.c main loop and in the
  810. * proxy CONNECT loop.
  811. */
  812. static int is_valid_auth_separator(char ch)
  813. {
  814. return ch == '\0' || ch == ',' || ISSPACE(ch);
  815. }
  816. CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy,
  817. const char *auth) /* the first non-space */
  818. {
  819. /*
  820. * This resource requires authentication
  821. */
  822. struct connectdata *conn = data->conn;
  823. #ifdef USE_SPNEGO
  824. curlnegotiate *negstate = proxy ? &conn->proxy_negotiate_state :
  825. &conn->http_negotiate_state;
  826. #endif
  827. unsigned long *availp;
  828. struct auth *authp;
  829. (void) conn; /* In case conditionals make it unused. */
  830. if(proxy) {
  831. availp = &data->info.proxyauthavail;
  832. authp = &data->state.authproxy;
  833. }
  834. else {
  835. availp = &data->info.httpauthavail;
  836. authp = &data->state.authhost;
  837. }
  838. /*
  839. * Here we check if we want the specific single authentication (using ==) and
  840. * if we do, we initiate usage of it.
  841. *
  842. * If the provided authentication is wanted as one out of several accepted
  843. * types (using &), we OR this authentication type to the authavail
  844. * variable.
  845. *
  846. * Note:
  847. *
  848. * ->picked is first set to the 'want' value (one or more bits) before the
  849. * request is sent, and then it is again set _after_ all response 401/407
  850. * headers have been received but then only to a single preferred method
  851. * (bit).
  852. */
  853. while(*auth) {
  854. #ifdef USE_SPNEGO
  855. if(checkprefix("Negotiate", auth) && is_valid_auth_separator(auth[9])) {
  856. if((authp->avail & CURLAUTH_NEGOTIATE) ||
  857. Curl_auth_is_spnego_supported()) {
  858. *availp |= CURLAUTH_NEGOTIATE;
  859. authp->avail |= CURLAUTH_NEGOTIATE;
  860. if(authp->picked == CURLAUTH_NEGOTIATE) {
  861. CURLcode result = Curl_input_negotiate(data, conn, proxy, auth);
  862. if(!result) {
  863. DEBUGASSERT(!data->req.newurl);
  864. data->req.newurl = strdup(data->state.url);
  865. if(!data->req.newurl)
  866. return CURLE_OUT_OF_MEMORY;
  867. data->state.authproblem = FALSE;
  868. /* we received a GSS auth token and we dealt with it fine */
  869. *negstate = GSS_AUTHRECV;
  870. }
  871. else
  872. data->state.authproblem = TRUE;
  873. }
  874. }
  875. }
  876. else
  877. #endif
  878. #ifdef USE_NTLM
  879. /* NTLM support requires the SSL crypto libs */
  880. if(checkprefix("NTLM", auth) && is_valid_auth_separator(auth[4])) {
  881. if((authp->avail & CURLAUTH_NTLM) ||
  882. (authp->avail & CURLAUTH_NTLM_WB) ||
  883. Curl_auth_is_ntlm_supported()) {
  884. *availp |= CURLAUTH_NTLM;
  885. authp->avail |= CURLAUTH_NTLM;
  886. if(authp->picked == CURLAUTH_NTLM ||
  887. authp->picked == CURLAUTH_NTLM_WB) {
  888. /* NTLM authentication is picked and activated */
  889. CURLcode result = Curl_input_ntlm(data, proxy, auth);
  890. if(!result) {
  891. data->state.authproblem = FALSE;
  892. #ifdef NTLM_WB_ENABLED
  893. if(authp->picked == CURLAUTH_NTLM_WB) {
  894. *availp &= ~CURLAUTH_NTLM;
  895. authp->avail &= ~CURLAUTH_NTLM;
  896. *availp |= CURLAUTH_NTLM_WB;
  897. authp->avail |= CURLAUTH_NTLM_WB;
  898. result = Curl_input_ntlm_wb(data, conn, proxy, auth);
  899. if(result) {
  900. infof(data, "Authentication problem. Ignoring this.");
  901. data->state.authproblem = TRUE;
  902. }
  903. }
  904. #endif
  905. }
  906. else {
  907. infof(data, "Authentication problem. Ignoring this.");
  908. data->state.authproblem = TRUE;
  909. }
  910. }
  911. }
  912. }
  913. else
  914. #endif
  915. #ifndef CURL_DISABLE_CRYPTO_AUTH
  916. if(checkprefix("Digest", auth) && is_valid_auth_separator(auth[6])) {
  917. if((authp->avail & CURLAUTH_DIGEST) != 0)
  918. infof(data, "Ignoring duplicate digest auth header.");
  919. else if(Curl_auth_is_digest_supported()) {
  920. CURLcode result;
  921. *availp |= CURLAUTH_DIGEST;
  922. authp->avail |= CURLAUTH_DIGEST;
  923. /* We call this function on input Digest headers even if Digest
  924. * authentication isn't activated yet, as we need to store the
  925. * incoming data from this header in case we are going to use
  926. * Digest */
  927. result = Curl_input_digest(data, proxy, auth);
  928. if(result) {
  929. infof(data, "Authentication problem. Ignoring this.");
  930. data->state.authproblem = TRUE;
  931. }
  932. }
  933. }
  934. else
  935. #endif
  936. if(checkprefix("Basic", auth) &&
  937. is_valid_auth_separator(auth[5])) {
  938. *availp |= CURLAUTH_BASIC;
  939. authp->avail |= CURLAUTH_BASIC;
  940. if(authp->picked == CURLAUTH_BASIC) {
  941. /* We asked for Basic authentication but got a 40X back
  942. anyway, which basically means our name+password isn't
  943. valid. */
  944. authp->avail = CURLAUTH_NONE;
  945. infof(data, "Authentication problem. Ignoring this.");
  946. data->state.authproblem = TRUE;
  947. }
  948. }
  949. else
  950. if(checkprefix("Bearer", auth) &&
  951. is_valid_auth_separator(auth[6])) {
  952. *availp |= CURLAUTH_BEARER;
  953. authp->avail |= CURLAUTH_BEARER;
  954. if(authp->picked == CURLAUTH_BEARER) {
  955. /* We asked for Bearer authentication but got a 40X back
  956. anyway, which basically means our token isn't valid. */
  957. authp->avail = CURLAUTH_NONE;
  958. infof(data, "Authentication problem. Ignoring this.");
  959. data->state.authproblem = TRUE;
  960. }
  961. }
  962. /* there may be multiple methods on one line, so keep reading */
  963. while(*auth && *auth != ',') /* read up to the next comma */
  964. auth++;
  965. if(*auth == ',') /* if we're on a comma, skip it */
  966. auth++;
  967. while(*auth && ISSPACE(*auth))
  968. auth++;
  969. }
  970. return CURLE_OK;
  971. }
  972. /**
  973. * http_should_fail() determines whether an HTTP response has gotten us
  974. * into an error state or not.
  975. *
  976. * @param conn all information about the current connection
  977. *
  978. * @retval FALSE communications should continue
  979. *
  980. * @retval TRUE communications should not continue
  981. */
  982. static bool http_should_fail(struct Curl_easy *data)
  983. {
  984. int httpcode;
  985. DEBUGASSERT(data);
  986. DEBUGASSERT(data->conn);
  987. httpcode = data->req.httpcode;
  988. /*
  989. ** If we haven't been asked to fail on error,
  990. ** don't fail.
  991. */
  992. if(!data->set.http_fail_on_error)
  993. return FALSE;
  994. /*
  995. ** Any code < 400 is never terminal.
  996. */
  997. if(httpcode < 400)
  998. return FALSE;
  999. /*
  1000. ** A 416 response to a resume request is presumably because the file is
  1001. ** already completely downloaded and thus not actually a fail.
  1002. */
  1003. if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET &&
  1004. httpcode == 416)
  1005. return FALSE;
  1006. /*
  1007. ** Any code >= 400 that's not 401 or 407 is always
  1008. ** a terminal error
  1009. */
  1010. if((httpcode != 401) && (httpcode != 407))
  1011. return TRUE;
  1012. /*
  1013. ** All we have left to deal with is 401 and 407
  1014. */
  1015. DEBUGASSERT((httpcode == 401) || (httpcode == 407));
  1016. /*
  1017. ** Examine the current authentication state to see if this
  1018. ** is an error. The idea is for this function to get
  1019. ** called after processing all the headers in a response
  1020. ** message. So, if we've been to asked to authenticate a
  1021. ** particular stage, and we've done it, we're OK. But, if
  1022. ** we're already completely authenticated, it's not OK to
  1023. ** get another 401 or 407.
  1024. **
  1025. ** It is possible for authentication to go stale such that
  1026. ** the client needs to reauthenticate. Once that info is
  1027. ** available, use it here.
  1028. */
  1029. /*
  1030. ** Either we're not authenticating, or we're supposed to
  1031. ** be authenticating something else. This is an error.
  1032. */
  1033. if((httpcode == 401) && !data->conn->bits.user_passwd)
  1034. return TRUE;
  1035. #ifndef CURL_DISABLE_PROXY
  1036. if((httpcode == 407) && !data->conn->bits.proxy_user_passwd)
  1037. return TRUE;
  1038. #endif
  1039. return data->state.authproblem;
  1040. }
  1041. #ifndef USE_HYPER
  1042. /*
  1043. * readmoredata() is a "fread() emulation" to provide POST and/or request
  1044. * data. It is used when a huge POST is to be made and the entire chunk wasn't
  1045. * sent in the first send(). This function will then be called from the
  1046. * transfer.c loop when more data is to be sent to the peer.
  1047. *
  1048. * Returns the amount of bytes it filled the buffer with.
  1049. */
  1050. static size_t readmoredata(char *buffer,
  1051. size_t size,
  1052. size_t nitems,
  1053. void *userp)
  1054. {
  1055. struct Curl_easy *data = (struct Curl_easy *)userp;
  1056. struct HTTP *http = data->req.p.http;
  1057. size_t fullsize = size * nitems;
  1058. if(!http->postsize)
  1059. /* nothing to return */
  1060. return 0;
  1061. /* make sure that a HTTP request is never sent away chunked! */
  1062. data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
  1063. if(data->set.max_send_speed &&
  1064. (data->set.max_send_speed < (curl_off_t)fullsize) &&
  1065. (data->set.max_send_speed < http->postsize))
  1066. /* speed limit */
  1067. fullsize = (size_t)data->set.max_send_speed;
  1068. else if(http->postsize <= (curl_off_t)fullsize) {
  1069. memcpy(buffer, http->postdata, (size_t)http->postsize);
  1070. fullsize = (size_t)http->postsize;
  1071. if(http->backup.postsize) {
  1072. /* move backup data into focus and continue on that */
  1073. http->postdata = http->backup.postdata;
  1074. http->postsize = http->backup.postsize;
  1075. data->state.fread_func = http->backup.fread_func;
  1076. data->state.in = http->backup.fread_in;
  1077. http->sending++; /* move one step up */
  1078. http->backup.postsize = 0;
  1079. }
  1080. else
  1081. http->postsize = 0;
  1082. return fullsize;
  1083. }
  1084. memcpy(buffer, http->postdata, fullsize);
  1085. http->postdata += fullsize;
  1086. http->postsize -= fullsize;
  1087. return fullsize;
  1088. }
  1089. /*
  1090. * Curl_buffer_send() sends a header buffer and frees all associated
  1091. * memory. Body data may be appended to the header data if desired.
  1092. *
  1093. * Returns CURLcode
  1094. */
  1095. CURLcode Curl_buffer_send(struct dynbuf *in,
  1096. struct Curl_easy *data,
  1097. /* add the number of sent bytes to this
  1098. counter */
  1099. curl_off_t *bytes_written,
  1100. /* how much of the buffer contains body data */
  1101. curl_off_t included_body_bytes,
  1102. int socketindex)
  1103. {
  1104. ssize_t amount;
  1105. CURLcode result;
  1106. char *ptr;
  1107. size_t size;
  1108. struct connectdata *conn = data->conn;
  1109. struct HTTP *http = data->req.p.http;
  1110. size_t sendsize;
  1111. curl_socket_t sockfd;
  1112. size_t headersize;
  1113. DEBUGASSERT(socketindex <= SECONDARYSOCKET);
  1114. sockfd = conn->sock[socketindex];
  1115. /* The looping below is required since we use non-blocking sockets, but due
  1116. to the circumstances we will just loop and try again and again etc */
  1117. ptr = Curl_dyn_ptr(in);
  1118. size = Curl_dyn_len(in);
  1119. headersize = size - (size_t)included_body_bytes; /* the initial part that
  1120. isn't body is header */
  1121. DEBUGASSERT(size > (size_t)included_body_bytes);
  1122. result = Curl_convert_to_network(data, ptr, headersize);
  1123. /* Curl_convert_to_network calls failf if unsuccessful */
  1124. if(result) {
  1125. /* conversion failed, free memory and return to the caller */
  1126. Curl_dyn_free(in);
  1127. return result;
  1128. }
  1129. if((conn->handler->flags & PROTOPT_SSL
  1130. #ifndef CURL_DISABLE_PROXY
  1131. || conn->http_proxy.proxytype == CURLPROXY_HTTPS
  1132. #endif
  1133. )
  1134. && conn->httpversion != 20) {
  1135. /* Make sure this doesn't send more body bytes than what the max send
  1136. speed says. The request bytes do not count to the max speed.
  1137. */
  1138. if(data->set.max_send_speed &&
  1139. (included_body_bytes > data->set.max_send_speed)) {
  1140. curl_off_t overflow = included_body_bytes - data->set.max_send_speed;
  1141. DEBUGASSERT((size_t)overflow < size);
  1142. sendsize = size - (size_t)overflow;
  1143. }
  1144. else
  1145. sendsize = size;
  1146. /* OpenSSL is very picky and we must send the SAME buffer pointer to the
  1147. library when we attempt to re-send this buffer. Sending the same data
  1148. is not enough, we must use the exact same address. For this reason, we
  1149. must copy the data to the uploadbuffer first, since that is the buffer
  1150. we will be using if this send is retried later.
  1151. */
  1152. result = Curl_get_upload_buffer(data);
  1153. if(result) {
  1154. /* malloc failed, free memory and return to the caller */
  1155. Curl_dyn_free(in);
  1156. return result;
  1157. }
  1158. /* We never send more than upload_buffer_size bytes in one single chunk
  1159. when we speak HTTPS, as if only a fraction of it is sent now, this data
  1160. needs to fit into the normal read-callback buffer later on and that
  1161. buffer is using this size.
  1162. */
  1163. if(sendsize > (size_t)data->set.upload_buffer_size)
  1164. sendsize = (size_t)data->set.upload_buffer_size;
  1165. memcpy(data->state.ulbuf, ptr, sendsize);
  1166. ptr = data->state.ulbuf;
  1167. }
  1168. else {
  1169. #ifdef CURLDEBUG
  1170. /* Allow debug builds to override this logic to force short initial
  1171. sends
  1172. */
  1173. char *p = getenv("CURL_SMALLREQSEND");
  1174. if(p) {
  1175. size_t altsize = (size_t)strtoul(p, NULL, 10);
  1176. if(altsize)
  1177. sendsize = CURLMIN(size, altsize);
  1178. else
  1179. sendsize = size;
  1180. }
  1181. else
  1182. #endif
  1183. {
  1184. /* Make sure this doesn't send more body bytes than what the max send
  1185. speed says. The request bytes do not count to the max speed.
  1186. */
  1187. if(data->set.max_send_speed &&
  1188. (included_body_bytes > data->set.max_send_speed)) {
  1189. curl_off_t overflow = included_body_bytes - data->set.max_send_speed;
  1190. DEBUGASSERT((size_t)overflow < size);
  1191. sendsize = size - (size_t)overflow;
  1192. }
  1193. else
  1194. sendsize = size;
  1195. }
  1196. }
  1197. result = Curl_write(data, sockfd, ptr, sendsize, &amount);
  1198. if(!result) {
  1199. /*
  1200. * Note that we may not send the entire chunk at once, and we have a set
  1201. * number of data bytes at the end of the big buffer (out of which we may
  1202. * only send away a part).
  1203. */
  1204. /* how much of the header that was sent */
  1205. size_t headlen = (size_t)amount>headersize ? headersize : (size_t)amount;
  1206. size_t bodylen = amount - headlen;
  1207. /* this data _may_ contain binary stuff */
  1208. Curl_debug(data, CURLINFO_HEADER_OUT, ptr, headlen);
  1209. if(bodylen)
  1210. /* there was body data sent beyond the initial header part, pass that on
  1211. to the debug callback too */
  1212. Curl_debug(data, CURLINFO_DATA_OUT, ptr + headlen, bodylen);
  1213. /* 'amount' can never be a very large value here so typecasting it so a
  1214. signed 31 bit value should not cause problems even if ssize_t is
  1215. 64bit */
  1216. *bytes_written += (long)amount;
  1217. if(http) {
  1218. /* if we sent a piece of the body here, up the byte counter for it
  1219. accordingly */
  1220. data->req.writebytecount += bodylen;
  1221. Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
  1222. if((size_t)amount != size) {
  1223. /* The whole request could not be sent in one system call. We must
  1224. queue it up and send it later when we get the chance. We must not
  1225. loop here and wait until it might work again. */
  1226. size -= amount;
  1227. ptr = Curl_dyn_ptr(in) + amount;
  1228. /* backup the currently set pointers */
  1229. http->backup.fread_func = data->state.fread_func;
  1230. http->backup.fread_in = data->state.in;
  1231. http->backup.postdata = http->postdata;
  1232. http->backup.postsize = http->postsize;
  1233. /* set the new pointers for the request-sending */
  1234. data->state.fread_func = (curl_read_callback)readmoredata;
  1235. data->state.in = (void *)data;
  1236. http->postdata = ptr;
  1237. http->postsize = (curl_off_t)size;
  1238. /* this much data is remaining header: */
  1239. data->req.pendingheader = headersize - headlen;
  1240. http->send_buffer = *in; /* copy the whole struct */
  1241. http->sending = HTTPSEND_REQUEST;
  1242. return CURLE_OK;
  1243. }
  1244. http->sending = HTTPSEND_BODY;
  1245. /* the full buffer was sent, clean up and return */
  1246. }
  1247. else {
  1248. if((size_t)amount != size)
  1249. /* We have no continue-send mechanism now, fail. This can only happen
  1250. when this function is used from the CONNECT sending function. We
  1251. currently (stupidly) assume that the whole request is always sent
  1252. away in the first single chunk.
  1253. This needs FIXing.
  1254. */
  1255. return CURLE_SEND_ERROR;
  1256. }
  1257. }
  1258. Curl_dyn_free(in);
  1259. /* no remaining header data */
  1260. data->req.pendingheader = 0;
  1261. return result;
  1262. }
  1263. #endif
  1264. /* end of the add_buffer functions */
  1265. /* ------------------------------------------------------------------------- */
  1266. /*
  1267. * Curl_compareheader()
  1268. *
  1269. * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
  1270. * Pass headers WITH the colon.
  1271. */
  1272. bool
  1273. Curl_compareheader(const char *headerline, /* line to check */
  1274. const char *header, /* header keyword _with_ colon */
  1275. const char *content) /* content string to find */
  1276. {
  1277. /* RFC2616, section 4.2 says: "Each header field consists of a name followed
  1278. * by a colon (":") and the field value. Field names are case-insensitive.
  1279. * The field value MAY be preceded by any amount of LWS, though a single SP
  1280. * is preferred." */
  1281. size_t hlen = strlen(header);
  1282. size_t clen;
  1283. size_t len;
  1284. const char *start;
  1285. const char *end;
  1286. if(!strncasecompare(headerline, header, hlen))
  1287. return FALSE; /* doesn't start with header */
  1288. /* pass the header */
  1289. start = &headerline[hlen];
  1290. /* pass all whitespace */
  1291. while(*start && ISSPACE(*start))
  1292. start++;
  1293. /* find the end of the header line */
  1294. end = strchr(start, '\r'); /* lines end with CRLF */
  1295. if(!end) {
  1296. /* in case there's a non-standard compliant line here */
  1297. end = strchr(start, '\n');
  1298. if(!end)
  1299. /* hm, there's no line ending here, use the zero byte! */
  1300. end = strchr(start, '\0');
  1301. }
  1302. len = end-start; /* length of the content part of the input line */
  1303. clen = strlen(content); /* length of the word to find */
  1304. /* find the content string in the rest of the line */
  1305. for(; len >= clen; len--, start++) {
  1306. if(strncasecompare(start, content, clen))
  1307. return TRUE; /* match! */
  1308. }
  1309. return FALSE; /* no match */
  1310. }
  1311. /*
  1312. * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
  1313. * the generic Curl_connect().
  1314. */
  1315. CURLcode Curl_http_connect(struct Curl_easy *data, bool *done)
  1316. {
  1317. CURLcode result;
  1318. struct connectdata *conn = data->conn;
  1319. /* We default to persistent connections. We set this already in this connect
  1320. function to make the re-use checks properly be able to check this bit. */
  1321. connkeep(conn, "HTTP default");
  1322. #ifndef CURL_DISABLE_PROXY
  1323. /* the CONNECT procedure might not have been completed */
  1324. result = Curl_proxy_connect(data, FIRSTSOCKET);
  1325. if(result)
  1326. return result;
  1327. if(conn->bits.proxy_connect_closed)
  1328. /* this is not an error, just part of the connection negotiation */
  1329. return CURLE_OK;
  1330. if(CONNECT_FIRSTSOCKET_PROXY_SSL())
  1331. return CURLE_OK; /* wait for HTTPS proxy SSL initialization to complete */
  1332. if(Curl_connect_ongoing(conn))
  1333. /* nothing else to do except wait right now - we're not done here. */
  1334. return CURLE_OK;
  1335. if(data->set.haproxyprotocol) {
  1336. /* add HAProxy PROXY protocol header */
  1337. result = add_haproxy_protocol_header(data);
  1338. if(result)
  1339. return result;
  1340. }
  1341. #endif
  1342. if(conn->given->protocol & CURLPROTO_HTTPS) {
  1343. /* perform SSL initialization */
  1344. result = https_connecting(data, done);
  1345. if(result)
  1346. return result;
  1347. }
  1348. else
  1349. *done = TRUE;
  1350. return CURLE_OK;
  1351. }
  1352. /* this returns the socket to wait for in the DO and DOING state for the multi
  1353. interface and then we're always _sending_ a request and thus we wait for
  1354. the single socket to become writable only */
  1355. static int http_getsock_do(struct Curl_easy *data,
  1356. struct connectdata *conn,
  1357. curl_socket_t *socks)
  1358. {
  1359. /* write mode */
  1360. (void)data;
  1361. socks[0] = conn->sock[FIRSTSOCKET];
  1362. return GETSOCK_WRITESOCK(0);
  1363. }
  1364. #ifndef CURL_DISABLE_PROXY
  1365. static CURLcode add_haproxy_protocol_header(struct Curl_easy *data)
  1366. {
  1367. struct dynbuf req;
  1368. CURLcode result;
  1369. const char *tcp_version;
  1370. DEBUGASSERT(data->conn);
  1371. Curl_dyn_init(&req, DYN_HAXPROXY);
  1372. #ifdef USE_UNIX_SOCKETS
  1373. if(data->conn->unix_domain_socket)
  1374. /* the buffer is large enough to hold this! */
  1375. result = Curl_dyn_add(&req, "PROXY UNKNOWN\r\n");
  1376. else {
  1377. #endif
  1378. /* Emit the correct prefix for IPv6 */
  1379. tcp_version = data->conn->bits.ipv6 ? "TCP6" : "TCP4";
  1380. result = Curl_dyn_addf(&req, "PROXY %s %s %s %i %i\r\n",
  1381. tcp_version,
  1382. data->info.conn_local_ip,
  1383. data->info.conn_primary_ip,
  1384. data->info.conn_local_port,
  1385. data->info.conn_primary_port);
  1386. #ifdef USE_UNIX_SOCKETS
  1387. }
  1388. #endif
  1389. if(!result)
  1390. result = Curl_buffer_send(&req, data, &data->info.request_size,
  1391. 0, FIRSTSOCKET);
  1392. return result;
  1393. }
  1394. #endif
  1395. #ifdef USE_SSL
  1396. static CURLcode https_connecting(struct Curl_easy *data, bool *done)
  1397. {
  1398. CURLcode result;
  1399. struct connectdata *conn = data->conn;
  1400. DEBUGASSERT((data) && (data->conn->handler->flags & PROTOPT_SSL));
  1401. #ifdef ENABLE_QUIC
  1402. if(conn->transport == TRNSPRT_QUIC) {
  1403. *done = TRUE;
  1404. return CURLE_OK;
  1405. }
  1406. #endif
  1407. /* perform SSL initialization for this socket */
  1408. result = Curl_ssl_connect_nonblocking(data, conn, FALSE, FIRSTSOCKET, done);
  1409. if(result)
  1410. connclose(conn, "Failed HTTPS connection");
  1411. return result;
  1412. }
  1413. static int https_getsock(struct Curl_easy *data,
  1414. struct connectdata *conn,
  1415. curl_socket_t *socks)
  1416. {
  1417. (void)data;
  1418. if(conn->handler->flags & PROTOPT_SSL)
  1419. return Curl_ssl->getsock(conn, socks);
  1420. return GETSOCK_BLANK;
  1421. }
  1422. #endif /* USE_SSL */
  1423. /*
  1424. * Curl_http_done() gets called after a single HTTP request has been
  1425. * performed.
  1426. */
  1427. CURLcode Curl_http_done(struct Curl_easy *data,
  1428. CURLcode status, bool premature)
  1429. {
  1430. struct connectdata *conn = data->conn;
  1431. struct HTTP *http = data->req.p.http;
  1432. /* Clear multipass flag. If authentication isn't done yet, then it will get
  1433. * a chance to be set back to true when we output the next auth header */
  1434. data->state.authhost.multipass = FALSE;
  1435. data->state.authproxy.multipass = FALSE;
  1436. Curl_unencode_cleanup(data);
  1437. /* set the proper values (possibly modified on POST) */
  1438. conn->seek_func = data->set.seek_func; /* restore */
  1439. conn->seek_client = data->set.seek_client; /* restore */
  1440. if(!http)
  1441. return CURLE_OK;
  1442. Curl_dyn_free(&http->send_buffer);
  1443. Curl_http2_done(data, premature);
  1444. Curl_quic_done(data, premature);
  1445. Curl_mime_cleanpart(&http->form);
  1446. Curl_dyn_reset(&data->state.headerb);
  1447. Curl_hyper_done(data);
  1448. if(status)
  1449. return status;
  1450. if(!premature && /* this check is pointless when DONE is called before the
  1451. entire operation is complete */
  1452. !conn->bits.retry &&
  1453. !data->set.connect_only &&
  1454. (data->req.bytecount +
  1455. data->req.headerbytecount -
  1456. data->req.deductheadercount) <= 0) {
  1457. /* If this connection isn't simply closed to be retried, AND nothing was
  1458. read from the HTTP server (that counts), this can't be right so we
  1459. return an error here */
  1460. failf(data, "Empty reply from server");
  1461. /* Mark it as closed to avoid the "left intact" message */
  1462. streamclose(conn, "Empty reply from server");
  1463. return CURLE_GOT_NOTHING;
  1464. }
  1465. return CURLE_OK;
  1466. }
  1467. /*
  1468. * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
  1469. * to avoid it include:
  1470. *
  1471. * - if the user specifically requested HTTP 1.0
  1472. * - if the server we are connected to only supports 1.0
  1473. * - if any server previously contacted to handle this request only supports
  1474. * 1.0.
  1475. */
  1476. bool Curl_use_http_1_1plus(const struct Curl_easy *data,
  1477. const struct connectdata *conn)
  1478. {
  1479. if((data->state.httpversion == 10) || (conn->httpversion == 10))
  1480. return FALSE;
  1481. if((data->state.httpwant == CURL_HTTP_VERSION_1_0) &&
  1482. (conn->httpversion <= 10))
  1483. return FALSE;
  1484. return ((data->state.httpwant == CURL_HTTP_VERSION_NONE) ||
  1485. (data->state.httpwant >= CURL_HTTP_VERSION_1_1));
  1486. }
  1487. #ifndef USE_HYPER
  1488. static const char *get_http_string(const struct Curl_easy *data,
  1489. const struct connectdata *conn)
  1490. {
  1491. #ifdef ENABLE_QUIC
  1492. if((data->state.httpwant == CURL_HTTP_VERSION_3) ||
  1493. (conn->httpversion == 30))
  1494. return "3";
  1495. #endif
  1496. #ifdef USE_NGHTTP2
  1497. if(conn->proto.httpc.h2)
  1498. return "2";
  1499. #endif
  1500. if(Curl_use_http_1_1plus(data, conn))
  1501. return "1.1";
  1502. return "1.0";
  1503. }
  1504. #endif
  1505. /* check and possibly add an Expect: header */
  1506. static CURLcode expect100(struct Curl_easy *data,
  1507. struct connectdata *conn,
  1508. struct dynbuf *req)
  1509. {
  1510. CURLcode result = CURLE_OK;
  1511. data->state.expect100header = FALSE; /* default to false unless it is set
  1512. to TRUE below */
  1513. if(!data->state.disableexpect && Curl_use_http_1_1plus(data, conn) &&
  1514. (conn->httpversion < 20)) {
  1515. /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an
  1516. Expect: 100-continue to the headers which actually speeds up post
  1517. operations (as there is one packet coming back from the web server) */
  1518. const char *ptr = Curl_checkheaders(data, "Expect");
  1519. if(ptr) {
  1520. data->state.expect100header =
  1521. Curl_compareheader(ptr, "Expect:", "100-continue");
  1522. }
  1523. else {
  1524. result = Curl_dyn_add(req, "Expect: 100-continue\r\n");
  1525. if(!result)
  1526. data->state.expect100header = TRUE;
  1527. }
  1528. }
  1529. return result;
  1530. }
  1531. enum proxy_use {
  1532. HEADER_SERVER, /* direct to server */
  1533. HEADER_PROXY, /* regular request to proxy */
  1534. HEADER_CONNECT /* sending CONNECT to a proxy */
  1535. };
  1536. /* used to compile the provided trailers into one buffer
  1537. will return an error code if one of the headers is
  1538. not formatted correctly */
  1539. CURLcode Curl_http_compile_trailers(struct curl_slist *trailers,
  1540. struct dynbuf *b,
  1541. struct Curl_easy *handle)
  1542. {
  1543. char *ptr = NULL;
  1544. CURLcode result = CURLE_OK;
  1545. const char *endofline_native = NULL;
  1546. const char *endofline_network = NULL;
  1547. if(
  1548. #ifdef CURL_DO_LINEEND_CONV
  1549. (handle->state.prefer_ascii) ||
  1550. #endif
  1551. (handle->set.crlf)) {
  1552. /* \n will become \r\n later on */
  1553. endofline_native = "\n";
  1554. endofline_network = "\x0a";
  1555. }
  1556. else {
  1557. endofline_native = "\r\n";
  1558. endofline_network = "\x0d\x0a";
  1559. }
  1560. while(trailers) {
  1561. /* only add correctly formatted trailers */
  1562. ptr = strchr(trailers->data, ':');
  1563. if(ptr && *(ptr + 1) == ' ') {
  1564. result = Curl_dyn_add(b, trailers->data);
  1565. if(result)
  1566. return result;
  1567. result = Curl_dyn_add(b, endofline_native);
  1568. if(result)
  1569. return result;
  1570. }
  1571. else
  1572. infof(handle, "Malformatted trailing header ! Skipping trailer.");
  1573. trailers = trailers->next;
  1574. }
  1575. result = Curl_dyn_add(b, endofline_network);
  1576. return result;
  1577. }
  1578. CURLcode Curl_add_custom_headers(struct Curl_easy *data,
  1579. bool is_connect,
  1580. #ifndef USE_HYPER
  1581. struct dynbuf *req
  1582. #else
  1583. void *req
  1584. #endif
  1585. )
  1586. {
  1587. struct connectdata *conn = data->conn;
  1588. char *ptr;
  1589. struct curl_slist *h[2];
  1590. struct curl_slist *headers;
  1591. int numlists = 1; /* by default */
  1592. int i;
  1593. #ifndef CURL_DISABLE_PROXY
  1594. enum proxy_use proxy;
  1595. if(is_connect)
  1596. proxy = HEADER_CONNECT;
  1597. else
  1598. proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
  1599. HEADER_PROXY:HEADER_SERVER;
  1600. switch(proxy) {
  1601. case HEADER_SERVER:
  1602. h[0] = data->set.headers;
  1603. break;
  1604. case HEADER_PROXY:
  1605. h[0] = data->set.headers;
  1606. if(data->set.sep_headers) {
  1607. h[1] = data->set.proxyheaders;
  1608. numlists++;
  1609. }
  1610. break;
  1611. case HEADER_CONNECT:
  1612. if(data->set.sep_headers)
  1613. h[0] = data->set.proxyheaders;
  1614. else
  1615. h[0] = data->set.headers;
  1616. break;
  1617. }
  1618. #else
  1619. (void)is_connect;
  1620. h[0] = data->set.headers;
  1621. #endif
  1622. /* loop through one or two lists */
  1623. for(i = 0; i < numlists; i++) {
  1624. headers = h[i];
  1625. while(headers) {
  1626. char *semicolonp = NULL;
  1627. ptr = strchr(headers->data, ':');
  1628. if(!ptr) {
  1629. char *optr;
  1630. /* no colon, semicolon? */
  1631. ptr = strchr(headers->data, ';');
  1632. if(ptr) {
  1633. optr = ptr;
  1634. ptr++; /* pass the semicolon */
  1635. while(*ptr && ISSPACE(*ptr))
  1636. ptr++;
  1637. if(*ptr) {
  1638. /* this may be used for something else in the future */
  1639. optr = NULL;
  1640. }
  1641. else {
  1642. if(*(--ptr) == ';') {
  1643. /* copy the source */
  1644. semicolonp = strdup(headers->data);
  1645. if(!semicolonp) {
  1646. #ifndef USE_HYPER
  1647. Curl_dyn_free(req);
  1648. #endif
  1649. return CURLE_OUT_OF_MEMORY;
  1650. }
  1651. /* put a colon where the semicolon is */
  1652. semicolonp[ptr - headers->data] = ':';
  1653. /* point at the colon */
  1654. optr = &semicolonp [ptr - headers->data];
  1655. }
  1656. }
  1657. ptr = optr;
  1658. }
  1659. }
  1660. if(ptr) {
  1661. /* we require a colon for this to be a true header */
  1662. ptr++; /* pass the colon */
  1663. while(*ptr && ISSPACE(*ptr))
  1664. ptr++;
  1665. if(*ptr || semicolonp) {
  1666. /* only send this if the contents was non-blank or done special */
  1667. CURLcode result = CURLE_OK;
  1668. char *compare = semicolonp ? semicolonp : headers->data;
  1669. if(data->state.aptr.host &&
  1670. /* a Host: header was sent already, don't pass on any custom Host:
  1671. header as that will produce *two* in the same request! */
  1672. checkprefix("Host:", compare))
  1673. ;
  1674. else if(data->state.httpreq == HTTPREQ_POST_FORM &&
  1675. /* this header (extended by formdata.c) is sent later */
  1676. checkprefix("Content-Type:", compare))
  1677. ;
  1678. else if(data->state.httpreq == HTTPREQ_POST_MIME &&
  1679. /* this header is sent later */
  1680. checkprefix("Content-Type:", compare))
  1681. ;
  1682. else if(conn->bits.authneg &&
  1683. /* while doing auth neg, don't allow the custom length since
  1684. we will force length zero then */
  1685. checkprefix("Content-Length:", compare))
  1686. ;
  1687. else if(data->state.aptr.te &&
  1688. /* when asking for Transfer-Encoding, don't pass on a custom
  1689. Connection: */
  1690. checkprefix("Connection:", compare))
  1691. ;
  1692. else if((conn->httpversion >= 20) &&
  1693. checkprefix("Transfer-Encoding:", compare))
  1694. /* HTTP/2 doesn't support chunked requests */
  1695. ;
  1696. else if((checkprefix("Authorization:", compare) ||
  1697. checkprefix("Cookie:", compare)) &&
  1698. /* be careful of sending this potentially sensitive header to
  1699. other hosts */
  1700. (data->state.this_is_a_follow &&
  1701. data->state.first_host &&
  1702. !data->set.allow_auth_to_other_hosts &&
  1703. !strcasecompare(data->state.first_host, conn->host.name)))
  1704. ;
  1705. else {
  1706. #ifdef USE_HYPER
  1707. result = Curl_hyper_header(data, req, compare);
  1708. #else
  1709. result = Curl_dyn_addf(req, "%s\r\n", compare);
  1710. #endif
  1711. }
  1712. if(semicolonp)
  1713. free(semicolonp);
  1714. if(result)
  1715. return result;
  1716. }
  1717. }
  1718. headers = headers->next;
  1719. }
  1720. }
  1721. return CURLE_OK;
  1722. }
  1723. #ifndef CURL_DISABLE_PARSEDATE
  1724. CURLcode Curl_add_timecondition(struct Curl_easy *data,
  1725. #ifndef USE_HYPER
  1726. struct dynbuf *req
  1727. #else
  1728. void *req
  1729. #endif
  1730. )
  1731. {
  1732. const struct tm *tm;
  1733. struct tm keeptime;
  1734. CURLcode result;
  1735. char datestr[80];
  1736. const char *condp;
  1737. if(data->set.timecondition == CURL_TIMECOND_NONE)
  1738. /* no condition was asked for */
  1739. return CURLE_OK;
  1740. result = Curl_gmtime(data->set.timevalue, &keeptime);
  1741. if(result) {
  1742. failf(data, "Invalid TIMEVALUE");
  1743. return result;
  1744. }
  1745. tm = &keeptime;
  1746. switch(data->set.timecondition) {
  1747. default:
  1748. return CURLE_BAD_FUNCTION_ARGUMENT;
  1749. case CURL_TIMECOND_IFMODSINCE:
  1750. condp = "If-Modified-Since";
  1751. break;
  1752. case CURL_TIMECOND_IFUNMODSINCE:
  1753. condp = "If-Unmodified-Since";
  1754. break;
  1755. case CURL_TIMECOND_LASTMOD:
  1756. condp = "Last-Modified";
  1757. break;
  1758. }
  1759. if(Curl_checkheaders(data, condp)) {
  1760. /* A custom header was specified; it will be sent instead. */
  1761. return CURLE_OK;
  1762. }
  1763. /* The If-Modified-Since header family should have their times set in
  1764. * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
  1765. * represented in Greenwich Mean Time (GMT), without exception. For the
  1766. * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
  1767. * Time)." (see page 20 of RFC2616).
  1768. */
  1769. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  1770. msnprintf(datestr, sizeof(datestr),
  1771. "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  1772. condp,
  1773. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  1774. tm->tm_mday,
  1775. Curl_month[tm->tm_mon],
  1776. tm->tm_year + 1900,
  1777. tm->tm_hour,
  1778. tm->tm_min,
  1779. tm->tm_sec);
  1780. #ifndef USE_HYPER
  1781. result = Curl_dyn_add(req, datestr);
  1782. #else
  1783. result = Curl_hyper_header(data, req, datestr);
  1784. #endif
  1785. return result;
  1786. }
  1787. #else
  1788. /* disabled */
  1789. CURLcode Curl_add_timecondition(struct Curl_easy *data,
  1790. struct dynbuf *req)
  1791. {
  1792. (void)data;
  1793. (void)req;
  1794. return CURLE_OK;
  1795. }
  1796. #endif
  1797. void Curl_http_method(struct Curl_easy *data, struct connectdata *conn,
  1798. const char **method, Curl_HttpReq *reqp)
  1799. {
  1800. Curl_HttpReq httpreq = data->state.httpreq;
  1801. const char *request;
  1802. if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
  1803. data->set.upload)
  1804. httpreq = HTTPREQ_PUT;
  1805. /* Now set the 'request' pointer to the proper request string */
  1806. if(data->set.str[STRING_CUSTOMREQUEST])
  1807. request = data->set.str[STRING_CUSTOMREQUEST];
  1808. else {
  1809. if(data->set.opt_no_body)
  1810. request = "HEAD";
  1811. else {
  1812. DEBUGASSERT((httpreq >= HTTPREQ_GET) && (httpreq <= HTTPREQ_HEAD));
  1813. switch(httpreq) {
  1814. case HTTPREQ_POST:
  1815. case HTTPREQ_POST_FORM:
  1816. case HTTPREQ_POST_MIME:
  1817. request = "POST";
  1818. break;
  1819. case HTTPREQ_PUT:
  1820. request = "PUT";
  1821. break;
  1822. default: /* this should never happen */
  1823. case HTTPREQ_GET:
  1824. request = "GET";
  1825. break;
  1826. case HTTPREQ_HEAD:
  1827. request = "HEAD";
  1828. break;
  1829. }
  1830. }
  1831. }
  1832. *method = request;
  1833. *reqp = httpreq;
  1834. }
  1835. CURLcode Curl_http_useragent(struct Curl_easy *data)
  1836. {
  1837. /* The User-Agent string might have been allocated in url.c already, because
  1838. it might have been used in the proxy connect, but if we have got a header
  1839. with the user-agent string specified, we erase the previously made string
  1840. here. */
  1841. if(Curl_checkheaders(data, "User-Agent")) {
  1842. free(data->state.aptr.uagent);
  1843. data->state.aptr.uagent = NULL;
  1844. }
  1845. return CURLE_OK;
  1846. }
  1847. CURLcode Curl_http_host(struct Curl_easy *data, struct connectdata *conn)
  1848. {
  1849. const char *ptr;
  1850. if(!data->state.this_is_a_follow) {
  1851. /* Free to avoid leaking memory on multiple requests*/
  1852. free(data->state.first_host);
  1853. data->state.first_host = strdup(conn->host.name);
  1854. if(!data->state.first_host)
  1855. return CURLE_OUT_OF_MEMORY;
  1856. data->state.first_remote_port = conn->remote_port;
  1857. }
  1858. Curl_safefree(data->state.aptr.host);
  1859. ptr = Curl_checkheaders(data, "Host");
  1860. if(ptr && (!data->state.this_is_a_follow ||
  1861. strcasecompare(data->state.first_host, conn->host.name))) {
  1862. #if !defined(CURL_DISABLE_COOKIES)
  1863. /* If we have a given custom Host: header, we extract the host name in
  1864. order to possibly use it for cookie reasons later on. We only allow the
  1865. custom Host: header if this is NOT a redirect, as setting Host: in the
  1866. redirected request is being out on thin ice. Except if the host name
  1867. is the same as the first one! */
  1868. char *cookiehost = Curl_copy_header_value(ptr);
  1869. if(!cookiehost)
  1870. return CURLE_OUT_OF_MEMORY;
  1871. if(!*cookiehost)
  1872. /* ignore empty data */
  1873. free(cookiehost);
  1874. else {
  1875. /* If the host begins with '[', we start searching for the port after
  1876. the bracket has been closed */
  1877. if(*cookiehost == '[') {
  1878. char *closingbracket;
  1879. /* since the 'cookiehost' is an allocated memory area that will be
  1880. freed later we cannot simply increment the pointer */
  1881. memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
  1882. closingbracket = strchr(cookiehost, ']');
  1883. if(closingbracket)
  1884. *closingbracket = 0;
  1885. }
  1886. else {
  1887. int startsearch = 0;
  1888. char *colon = strchr(cookiehost + startsearch, ':');
  1889. if(colon)
  1890. *colon = 0; /* The host must not include an embedded port number */
  1891. }
  1892. Curl_safefree(data->state.aptr.cookiehost);
  1893. data->state.aptr.cookiehost = cookiehost;
  1894. }
  1895. #endif
  1896. if(strcmp("Host:", ptr)) {
  1897. data->state.aptr.host = aprintf("Host:%s\r\n", &ptr[5]);
  1898. if(!data->state.aptr.host)
  1899. return CURLE_OUT_OF_MEMORY;
  1900. }
  1901. else
  1902. /* when clearing the header */
  1903. data->state.aptr.host = NULL;
  1904. }
  1905. else {
  1906. /* When building Host: headers, we must put the host name within
  1907. [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
  1908. const char *host = conn->host.name;
  1909. if(((conn->given->protocol&CURLPROTO_HTTPS) &&
  1910. (conn->remote_port == PORT_HTTPS)) ||
  1911. ((conn->given->protocol&CURLPROTO_HTTP) &&
  1912. (conn->remote_port == PORT_HTTP)) )
  1913. /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
  1914. the port number in the host string */
  1915. data->state.aptr.host = aprintf("Host: %s%s%s\r\n",
  1916. conn->bits.ipv6_ip?"[":"",
  1917. host,
  1918. conn->bits.ipv6_ip?"]":"");
  1919. else
  1920. data->state.aptr.host = aprintf("Host: %s%s%s:%d\r\n",
  1921. conn->bits.ipv6_ip?"[":"",
  1922. host,
  1923. conn->bits.ipv6_ip?"]":"",
  1924. conn->remote_port);
  1925. if(!data->state.aptr.host)
  1926. /* without Host: we can't make a nice request */
  1927. return CURLE_OUT_OF_MEMORY;
  1928. }
  1929. return CURLE_OK;
  1930. }
  1931. /*
  1932. * Append the request-target to the HTTP request
  1933. */
  1934. CURLcode Curl_http_target(struct Curl_easy *data,
  1935. struct connectdata *conn,
  1936. struct dynbuf *r)
  1937. {
  1938. CURLcode result = CURLE_OK;
  1939. const char *path = data->state.up.path;
  1940. const char *query = data->state.up.query;
  1941. if(data->set.str[STRING_TARGET]) {
  1942. path = data->set.str[STRING_TARGET];
  1943. query = NULL;
  1944. }
  1945. #ifndef CURL_DISABLE_PROXY
  1946. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  1947. /* Using a proxy but does not tunnel through it */
  1948. /* The path sent to the proxy is in fact the entire URL. But if the remote
  1949. host is a IDN-name, we must make sure that the request we produce only
  1950. uses the encoded host name! */
  1951. /* and no fragment part */
  1952. CURLUcode uc;
  1953. char *url;
  1954. CURLU *h = curl_url_dup(data->state.uh);
  1955. if(!h)
  1956. return CURLE_OUT_OF_MEMORY;
  1957. if(conn->host.dispname != conn->host.name) {
  1958. uc = curl_url_set(h, CURLUPART_HOST, conn->host.name, 0);
  1959. if(uc) {
  1960. curl_url_cleanup(h);
  1961. return CURLE_OUT_OF_MEMORY;
  1962. }
  1963. }
  1964. uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0);
  1965. if(uc) {
  1966. curl_url_cleanup(h);
  1967. return CURLE_OUT_OF_MEMORY;
  1968. }
  1969. if(strcasecompare("http", data->state.up.scheme)) {
  1970. /* when getting HTTP, we don't want the userinfo the URL */
  1971. uc = curl_url_set(h, CURLUPART_USER, NULL, 0);
  1972. if(uc) {
  1973. curl_url_cleanup(h);
  1974. return CURLE_OUT_OF_MEMORY;
  1975. }
  1976. uc = curl_url_set(h, CURLUPART_PASSWORD, NULL, 0);
  1977. if(uc) {
  1978. curl_url_cleanup(h);
  1979. return CURLE_OUT_OF_MEMORY;
  1980. }
  1981. }
  1982. /* Extract the URL to use in the request. Store in STRING_TEMP_URL for
  1983. clean-up reasons if the function returns before the free() further
  1984. down. */
  1985. uc = curl_url_get(h, CURLUPART_URL, &url, CURLU_NO_DEFAULT_PORT);
  1986. if(uc) {
  1987. curl_url_cleanup(h);
  1988. return CURLE_OUT_OF_MEMORY;
  1989. }
  1990. curl_url_cleanup(h);
  1991. /* target or url */
  1992. result = Curl_dyn_add(r, data->set.str[STRING_TARGET]?
  1993. data->set.str[STRING_TARGET]:url);
  1994. free(url);
  1995. if(result)
  1996. return (result);
  1997. if(strcasecompare("ftp", data->state.up.scheme)) {
  1998. if(data->set.proxy_transfer_mode) {
  1999. /* when doing ftp, append ;type=<a|i> if not present */
  2000. char *type = strstr(path, ";type=");
  2001. if(type && type[6] && type[7] == 0) {
  2002. switch(Curl_raw_toupper(type[6])) {
  2003. case 'A':
  2004. case 'D':
  2005. case 'I':
  2006. break;
  2007. default:
  2008. type = NULL;
  2009. }
  2010. }
  2011. if(!type) {
  2012. result = Curl_dyn_addf(r, ";type=%c",
  2013. data->state.prefer_ascii ? 'a' : 'i');
  2014. if(result)
  2015. return result;
  2016. }
  2017. }
  2018. }
  2019. }
  2020. else
  2021. #else
  2022. (void)conn; /* not used in disabled-proxy builds */
  2023. #endif
  2024. {
  2025. result = Curl_dyn_add(r, path);
  2026. if(result)
  2027. return result;
  2028. if(query)
  2029. result = Curl_dyn_addf(r, "?%s", query);
  2030. }
  2031. return result;
  2032. }
  2033. CURLcode Curl_http_body(struct Curl_easy *data, struct connectdata *conn,
  2034. Curl_HttpReq httpreq, const char **tep)
  2035. {
  2036. CURLcode result = CURLE_OK;
  2037. const char *ptr;
  2038. struct HTTP *http = data->req.p.http;
  2039. http->postsize = 0;
  2040. switch(httpreq) {
  2041. case HTTPREQ_POST_MIME:
  2042. http->sendit = &data->set.mimepost;
  2043. break;
  2044. case HTTPREQ_POST_FORM:
  2045. /* Convert the form structure into a mime structure. */
  2046. Curl_mime_cleanpart(&http->form);
  2047. result = Curl_getformdata(data, &http->form, data->set.httppost,
  2048. data->state.fread_func);
  2049. if(result)
  2050. return result;
  2051. http->sendit = &http->form;
  2052. break;
  2053. default:
  2054. http->sendit = NULL;
  2055. }
  2056. #ifndef CURL_DISABLE_MIME
  2057. if(http->sendit) {
  2058. const char *cthdr = Curl_checkheaders(data, "Content-Type");
  2059. /* Read and seek body only. */
  2060. http->sendit->flags |= MIME_BODY_ONLY;
  2061. /* Prepare the mime structure headers & set content type. */
  2062. if(cthdr)
  2063. for(cthdr += 13; *cthdr == ' '; cthdr++)
  2064. ;
  2065. else if(http->sendit->kind == MIMEKIND_MULTIPART)
  2066. cthdr = "multipart/form-data";
  2067. curl_mime_headers(http->sendit, data->set.headers, 0);
  2068. result = Curl_mime_prepare_headers(http->sendit, cthdr,
  2069. NULL, MIMESTRATEGY_FORM);
  2070. curl_mime_headers(http->sendit, NULL, 0);
  2071. if(!result)
  2072. result = Curl_mime_rewind(http->sendit);
  2073. if(result)
  2074. return result;
  2075. http->postsize = Curl_mime_size(http->sendit);
  2076. }
  2077. #endif
  2078. ptr = Curl_checkheaders(data, "Transfer-Encoding");
  2079. if(ptr) {
  2080. /* Some kind of TE is requested, check if 'chunked' is chosen */
  2081. data->req.upload_chunky =
  2082. Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
  2083. }
  2084. else {
  2085. if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  2086. (((httpreq == HTTPREQ_POST_MIME || httpreq == HTTPREQ_POST_FORM) &&
  2087. http->postsize < 0) ||
  2088. ((data->set.upload || httpreq == HTTPREQ_POST) &&
  2089. data->state.infilesize == -1))) {
  2090. if(conn->bits.authneg)
  2091. /* don't enable chunked during auth neg */
  2092. ;
  2093. else if(Curl_use_http_1_1plus(data, conn)) {
  2094. if(conn->httpversion < 20)
  2095. /* HTTP, upload, unknown file size and not HTTP 1.0 */
  2096. data->req.upload_chunky = TRUE;
  2097. }
  2098. else {
  2099. failf(data, "Chunky upload is not supported by HTTP 1.0");
  2100. return CURLE_UPLOAD_FAILED;
  2101. }
  2102. }
  2103. else {
  2104. /* else, no chunky upload */
  2105. data->req.upload_chunky = FALSE;
  2106. }
  2107. if(data->req.upload_chunky)
  2108. *tep = "Transfer-Encoding: chunked\r\n";
  2109. }
  2110. return result;
  2111. }
  2112. CURLcode Curl_http_bodysend(struct Curl_easy *data, struct connectdata *conn,
  2113. struct dynbuf *r, Curl_HttpReq httpreq)
  2114. {
  2115. #ifndef USE_HYPER
  2116. /* Hyper always handles the body separately */
  2117. curl_off_t included_body = 0;
  2118. #endif
  2119. CURLcode result = CURLE_OK;
  2120. struct HTTP *http = data->req.p.http;
  2121. const char *ptr;
  2122. /* If 'authdone' is FALSE, we must not set the write socket index to the
  2123. Curl_transfer() call below, as we're not ready to actually upload any
  2124. data yet. */
  2125. switch(httpreq) {
  2126. case HTTPREQ_PUT: /* Let's PUT the data to the server! */
  2127. if(conn->bits.authneg)
  2128. http->postsize = 0;
  2129. else
  2130. http->postsize = data->state.infilesize;
  2131. if((http->postsize != -1) && !data->req.upload_chunky &&
  2132. (conn->bits.authneg || !Curl_checkheaders(data, "Content-Length"))) {
  2133. /* only add Content-Length if not uploading chunked */
  2134. result = Curl_dyn_addf(r, "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2135. "\r\n", http->postsize);
  2136. if(result)
  2137. return result;
  2138. }
  2139. if(http->postsize) {
  2140. result = expect100(data, conn, r);
  2141. if(result)
  2142. return result;
  2143. }
  2144. /* end of headers */
  2145. result = Curl_dyn_add(r, "\r\n");
  2146. if(result)
  2147. return result;
  2148. /* set the upload size to the progress meter */
  2149. Curl_pgrsSetUploadSize(data, http->postsize);
  2150. /* this sends the buffer and frees all the buffer resources */
  2151. result = Curl_buffer_send(r, data, &data->info.request_size, 0,
  2152. FIRSTSOCKET);
  2153. if(result)
  2154. failf(data, "Failed sending PUT request");
  2155. else
  2156. /* prepare for transfer */
  2157. Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE,
  2158. http->postsize?FIRSTSOCKET:-1);
  2159. if(result)
  2160. return result;
  2161. break;
  2162. case HTTPREQ_POST_FORM:
  2163. case HTTPREQ_POST_MIME:
  2164. /* This is form posting using mime data. */
  2165. if(conn->bits.authneg) {
  2166. /* nothing to post! */
  2167. result = Curl_dyn_add(r, "Content-Length: 0\r\n\r\n");
  2168. if(result)
  2169. return result;
  2170. result = Curl_buffer_send(r, data, &data->info.request_size, 0,
  2171. FIRSTSOCKET);
  2172. if(result)
  2173. failf(data, "Failed sending POST request");
  2174. else
  2175. /* setup variables for the upcoming transfer */
  2176. Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
  2177. break;
  2178. }
  2179. data->state.infilesize = http->postsize;
  2180. /* We only set Content-Length and allow a custom Content-Length if
  2181. we don't upload data chunked, as RFC2616 forbids us to set both
  2182. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2183. if(http->postsize != -1 && !data->req.upload_chunky &&
  2184. (conn->bits.authneg || !Curl_checkheaders(data, "Content-Length"))) {
  2185. /* we allow replacing this header if not during auth negotiation,
  2186. although it isn't very wise to actually set your own */
  2187. result = Curl_dyn_addf(r,
  2188. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2189. "\r\n", http->postsize);
  2190. if(result)
  2191. return result;
  2192. }
  2193. #ifndef CURL_DISABLE_MIME
  2194. /* Output mime-generated headers. */
  2195. {
  2196. struct curl_slist *hdr;
  2197. for(hdr = http->sendit->curlheaders; hdr; hdr = hdr->next) {
  2198. result = Curl_dyn_addf(r, "%s\r\n", hdr->data);
  2199. if(result)
  2200. return result;
  2201. }
  2202. }
  2203. #endif
  2204. /* For really small posts we don't use Expect: headers at all, and for
  2205. the somewhat bigger ones we allow the app to disable it. Just make
  2206. sure that the expect100header is always set to the preferred value
  2207. here. */
  2208. ptr = Curl_checkheaders(data, "Expect");
  2209. if(ptr) {
  2210. data->state.expect100header =
  2211. Curl_compareheader(ptr, "Expect:", "100-continue");
  2212. }
  2213. else if(http->postsize > EXPECT_100_THRESHOLD || http->postsize < 0) {
  2214. result = expect100(data, conn, r);
  2215. if(result)
  2216. return result;
  2217. }
  2218. else
  2219. data->state.expect100header = FALSE;
  2220. /* make the request end in a true CRLF */
  2221. result = Curl_dyn_add(r, "\r\n");
  2222. if(result)
  2223. return result;
  2224. /* set the upload size to the progress meter */
  2225. Curl_pgrsSetUploadSize(data, http->postsize);
  2226. /* Read from mime structure. */
  2227. data->state.fread_func = (curl_read_callback) Curl_mime_read;
  2228. data->state.in = (void *) http->sendit;
  2229. http->sending = HTTPSEND_BODY;
  2230. /* this sends the buffer and frees all the buffer resources */
  2231. result = Curl_buffer_send(r, data, &data->info.request_size, 0,
  2232. FIRSTSOCKET);
  2233. if(result)
  2234. failf(data, "Failed sending POST request");
  2235. else
  2236. /* prepare for transfer */
  2237. Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE,
  2238. http->postsize?FIRSTSOCKET:-1);
  2239. if(result)
  2240. return result;
  2241. break;
  2242. case HTTPREQ_POST:
  2243. /* this is the simple POST, using x-www-form-urlencoded style */
  2244. if(conn->bits.authneg)
  2245. http->postsize = 0;
  2246. else
  2247. /* the size of the post body */
  2248. http->postsize = data->state.infilesize;
  2249. /* We only set Content-Length and allow a custom Content-Length if
  2250. we don't upload data chunked, as RFC2616 forbids us to set both
  2251. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2252. if((http->postsize != -1) && !data->req.upload_chunky &&
  2253. (conn->bits.authneg || !Curl_checkheaders(data, "Content-Length"))) {
  2254. /* we allow replacing this header if not during auth negotiation,
  2255. although it isn't very wise to actually set your own */
  2256. result = Curl_dyn_addf(r, "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2257. "\r\n", http->postsize);
  2258. if(result)
  2259. return result;
  2260. }
  2261. if(!Curl_checkheaders(data, "Content-Type")) {
  2262. result = Curl_dyn_add(r, "Content-Type: application/"
  2263. "x-www-form-urlencoded\r\n");
  2264. if(result)
  2265. return result;
  2266. }
  2267. /* For really small posts we don't use Expect: headers at all, and for
  2268. the somewhat bigger ones we allow the app to disable it. Just make
  2269. sure that the expect100header is always set to the preferred value
  2270. here. */
  2271. ptr = Curl_checkheaders(data, "Expect");
  2272. if(ptr) {
  2273. data->state.expect100header =
  2274. Curl_compareheader(ptr, "Expect:", "100-continue");
  2275. }
  2276. else if(http->postsize > EXPECT_100_THRESHOLD || http->postsize < 0) {
  2277. result = expect100(data, conn, r);
  2278. if(result)
  2279. return result;
  2280. }
  2281. else
  2282. data->state.expect100header = FALSE;
  2283. #ifndef USE_HYPER
  2284. /* With Hyper the body is always passed on separately */
  2285. if(data->set.postfields) {
  2286. /* In HTTP2, we send request body in DATA frame regardless of
  2287. its size. */
  2288. if(conn->httpversion != 20 &&
  2289. !data->state.expect100header &&
  2290. (http->postsize < MAX_INITIAL_POST_SIZE)) {
  2291. /* if we don't use expect: 100 AND
  2292. postsize is less than MAX_INITIAL_POST_SIZE
  2293. then append the post data to the HTTP request header. This limit
  2294. is no magic limit but only set to prevent really huge POSTs to
  2295. get the data duplicated with malloc() and family. */
  2296. /* end of headers! */
  2297. result = Curl_dyn_add(r, "\r\n");
  2298. if(result)
  2299. return result;
  2300. if(!data->req.upload_chunky) {
  2301. /* We're not sending it 'chunked', append it to the request
  2302. already now to reduce the number if send() calls */
  2303. result = Curl_dyn_addn(r, data->set.postfields,
  2304. (size_t)http->postsize);
  2305. included_body = http->postsize;
  2306. }
  2307. else {
  2308. if(http->postsize) {
  2309. char chunk[16];
  2310. /* Append the POST data chunky-style */
  2311. msnprintf(chunk, sizeof(chunk), "%x\r\n", (int)http->postsize);
  2312. result = Curl_dyn_add(r, chunk);
  2313. if(!result) {
  2314. included_body = http->postsize + strlen(chunk);
  2315. result = Curl_dyn_addn(r, data->set.postfields,
  2316. (size_t)http->postsize);
  2317. if(!result)
  2318. result = Curl_dyn_add(r, "\r\n");
  2319. included_body += 2;
  2320. }
  2321. }
  2322. if(!result) {
  2323. result = Curl_dyn_add(r, "\x30\x0d\x0a\x0d\x0a");
  2324. /* 0 CR LF CR LF */
  2325. included_body += 5;
  2326. }
  2327. }
  2328. if(result)
  2329. return result;
  2330. /* Make sure the progress information is accurate */
  2331. Curl_pgrsSetUploadSize(data, http->postsize);
  2332. }
  2333. else {
  2334. /* A huge POST coming up, do data separate from the request */
  2335. http->postdata = data->set.postfields;
  2336. http->sending = HTTPSEND_BODY;
  2337. data->state.fread_func = (curl_read_callback)readmoredata;
  2338. data->state.in = (void *)data;
  2339. /* set the upload size to the progress meter */
  2340. Curl_pgrsSetUploadSize(data, http->postsize);
  2341. /* end of headers! */
  2342. result = Curl_dyn_add(r, "\r\n");
  2343. if(result)
  2344. return result;
  2345. }
  2346. }
  2347. else
  2348. #endif
  2349. {
  2350. /* end of headers! */
  2351. result = Curl_dyn_add(r, "\r\n");
  2352. if(result)
  2353. return result;
  2354. if(data->req.upload_chunky && conn->bits.authneg) {
  2355. /* Chunky upload is selected and we're negotiating auth still, send
  2356. end-of-data only */
  2357. result = Curl_dyn_add(r, (char *)"\x30\x0d\x0a\x0d\x0a");
  2358. /* 0 CR LF CR LF */
  2359. if(result)
  2360. return result;
  2361. }
  2362. else if(data->state.infilesize) {
  2363. /* set the upload size to the progress meter */
  2364. Curl_pgrsSetUploadSize(data, http->postsize?http->postsize:-1);
  2365. /* set the pointer to mark that we will send the post body using the
  2366. read callback, but only if we're not in authenticate negotiation */
  2367. if(!conn->bits.authneg)
  2368. http->postdata = (char *)&http->postdata;
  2369. }
  2370. }
  2371. /* issue the request */
  2372. result = Curl_buffer_send(r, data, &data->info.request_size, included_body,
  2373. FIRSTSOCKET);
  2374. if(result)
  2375. failf(data, "Failed sending HTTP POST request");
  2376. else
  2377. Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE,
  2378. http->postdata?FIRSTSOCKET:-1);
  2379. break;
  2380. default:
  2381. result = Curl_dyn_add(r, "\r\n");
  2382. if(result)
  2383. return result;
  2384. /* issue the request */
  2385. result = Curl_buffer_send(r, data, &data->info.request_size, 0,
  2386. FIRSTSOCKET);
  2387. if(result)
  2388. failf(data, "Failed sending HTTP request");
  2389. else
  2390. /* HTTP GET/HEAD download: */
  2391. Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1);
  2392. }
  2393. return result;
  2394. }
  2395. #if !defined(CURL_DISABLE_COOKIES)
  2396. CURLcode Curl_http_cookies(struct Curl_easy *data,
  2397. struct connectdata *conn,
  2398. struct dynbuf *r)
  2399. {
  2400. CURLcode result = CURLE_OK;
  2401. char *addcookies = NULL;
  2402. if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(data, "Cookie"))
  2403. addcookies = data->set.str[STRING_COOKIE];
  2404. if(data->cookies || addcookies) {
  2405. struct Cookie *co = NULL; /* no cookies from start */
  2406. int count = 0;
  2407. if(data->cookies && data->state.cookie_engine) {
  2408. const char *host = data->state.aptr.cookiehost ?
  2409. data->state.aptr.cookiehost : conn->host.name;
  2410. const bool secure_context =
  2411. conn->handler->protocol&CURLPROTO_HTTPS ||
  2412. strcasecompare("localhost", host) ||
  2413. !strcmp(host, "127.0.0.1") ||
  2414. !strcmp(host, "[::1]") ? TRUE : FALSE;
  2415. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  2416. co = Curl_cookie_getlist(data->cookies, host, data->state.up.path,
  2417. secure_context);
  2418. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  2419. }
  2420. if(co) {
  2421. struct Cookie *store = co;
  2422. /* now loop through all cookies that matched */
  2423. while(co) {
  2424. if(co->value) {
  2425. if(0 == count) {
  2426. result = Curl_dyn_add(r, "Cookie: ");
  2427. if(result)
  2428. break;
  2429. }
  2430. result = Curl_dyn_addf(r, "%s%s=%s", count?"; ":"",
  2431. co->name, co->value);
  2432. if(result)
  2433. break;
  2434. count++;
  2435. }
  2436. co = co->next; /* next cookie please */
  2437. }
  2438. Curl_cookie_freelist(store);
  2439. }
  2440. if(addcookies && !result) {
  2441. if(!count)
  2442. result = Curl_dyn_add(r, "Cookie: ");
  2443. if(!result) {
  2444. result = Curl_dyn_addf(r, "%s%s", count?"; ":"", addcookies);
  2445. count++;
  2446. }
  2447. }
  2448. if(count && !result)
  2449. result = Curl_dyn_add(r, "\r\n");
  2450. if(result)
  2451. return result;
  2452. }
  2453. return result;
  2454. }
  2455. #endif
  2456. CURLcode Curl_http_range(struct Curl_easy *data,
  2457. Curl_HttpReq httpreq)
  2458. {
  2459. if(data->state.use_range) {
  2460. /*
  2461. * A range is selected. We use different headers whether we're downloading
  2462. * or uploading and we always let customized headers override our internal
  2463. * ones if any such are specified.
  2464. */
  2465. if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
  2466. !Curl_checkheaders(data, "Range")) {
  2467. /* if a line like this was already allocated, free the previous one */
  2468. free(data->state.aptr.rangeline);
  2469. data->state.aptr.rangeline = aprintf("Range: bytes=%s\r\n",
  2470. data->state.range);
  2471. }
  2472. else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) &&
  2473. !Curl_checkheaders(data, "Content-Range")) {
  2474. /* if a line like this was already allocated, free the previous one */
  2475. free(data->state.aptr.rangeline);
  2476. if(data->set.set_resume_from < 0) {
  2477. /* Upload resume was asked for, but we don't know the size of the
  2478. remote part so we tell the server (and act accordingly) that we
  2479. upload the whole file (again) */
  2480. data->state.aptr.rangeline =
  2481. aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T
  2482. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2483. data->state.infilesize - 1, data->state.infilesize);
  2484. }
  2485. else if(data->state.resume_from) {
  2486. /* This is because "resume" was selected */
  2487. curl_off_t total_expected_size =
  2488. data->state.resume_from + data->state.infilesize;
  2489. data->state.aptr.rangeline =
  2490. aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
  2491. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2492. data->state.range, total_expected_size-1,
  2493. total_expected_size);
  2494. }
  2495. else {
  2496. /* Range was selected and then we just pass the incoming range and
  2497. append total size */
  2498. data->state.aptr.rangeline =
  2499. aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2500. data->state.range, data->state.infilesize);
  2501. }
  2502. if(!data->state.aptr.rangeline)
  2503. return CURLE_OUT_OF_MEMORY;
  2504. }
  2505. }
  2506. return CURLE_OK;
  2507. }
  2508. CURLcode Curl_http_resume(struct Curl_easy *data,
  2509. struct connectdata *conn,
  2510. Curl_HttpReq httpreq)
  2511. {
  2512. if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) &&
  2513. data->state.resume_from) {
  2514. /**********************************************************************
  2515. * Resuming upload in HTTP means that we PUT or POST and that we have
  2516. * got a resume_from value set. The resume value has already created
  2517. * a Range: header that will be passed along. We need to "fast forward"
  2518. * the file the given number of bytes and decrease the assume upload
  2519. * file size before we continue this venture in the dark lands of HTTP.
  2520. * Resuming mime/form posting at an offset > 0 has no sense and is ignored.
  2521. *********************************************************************/
  2522. if(data->state.resume_from < 0) {
  2523. /*
  2524. * This is meant to get the size of the present remote-file by itself.
  2525. * We don't support this now. Bail out!
  2526. */
  2527. data->state.resume_from = 0;
  2528. }
  2529. if(data->state.resume_from && !data->state.this_is_a_follow) {
  2530. /* do we still game? */
  2531. /* Now, let's read off the proper amount of bytes from the
  2532. input. */
  2533. int seekerr = CURL_SEEKFUNC_CANTSEEK;
  2534. if(conn->seek_func) {
  2535. Curl_set_in_callback(data, true);
  2536. seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
  2537. SEEK_SET);
  2538. Curl_set_in_callback(data, false);
  2539. }
  2540. if(seekerr != CURL_SEEKFUNC_OK) {
  2541. curl_off_t passed = 0;
  2542. if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
  2543. failf(data, "Could not seek stream");
  2544. return CURLE_READ_ERROR;
  2545. }
  2546. /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
  2547. do {
  2548. size_t readthisamountnow =
  2549. (data->state.resume_from - passed > data->set.buffer_size) ?
  2550. (size_t)data->set.buffer_size :
  2551. curlx_sotouz(data->state.resume_from - passed);
  2552. size_t actuallyread =
  2553. data->state.fread_func(data->state.buffer, 1, readthisamountnow,
  2554. data->state.in);
  2555. passed += actuallyread;
  2556. if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
  2557. /* this checks for greater-than only to make sure that the
  2558. CURL_READFUNC_ABORT return code still aborts */
  2559. failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T
  2560. " bytes from the input", passed);
  2561. return CURLE_READ_ERROR;
  2562. }
  2563. } while(passed < data->state.resume_from);
  2564. }
  2565. /* now, decrease the size of the read */
  2566. if(data->state.infilesize>0) {
  2567. data->state.infilesize -= data->state.resume_from;
  2568. if(data->state.infilesize <= 0) {
  2569. failf(data, "File already completely uploaded");
  2570. return CURLE_PARTIAL_FILE;
  2571. }
  2572. }
  2573. /* we've passed, proceed as normal */
  2574. }
  2575. }
  2576. return CURLE_OK;
  2577. }
  2578. CURLcode Curl_http_firstwrite(struct Curl_easy *data,
  2579. struct connectdata *conn,
  2580. bool *done)
  2581. {
  2582. struct SingleRequest *k = &data->req;
  2583. DEBUGASSERT(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP));
  2584. if(data->req.ignore_cl) {
  2585. k->size = k->maxdownload = -1;
  2586. }
  2587. else if(k->size != -1) {
  2588. /* We wait until after all headers have been received to set this so that
  2589. we know for sure Content-Length is valid. */
  2590. if(data->set.max_filesize &&
  2591. k->size > data->set.max_filesize) {
  2592. failf(data, "Maximum file size exceeded");
  2593. return CURLE_FILESIZE_EXCEEDED;
  2594. }
  2595. Curl_pgrsSetDownloadSize(data, k->size);
  2596. }
  2597. if(data->req.newurl) {
  2598. if(conn->bits.close) {
  2599. /* Abort after the headers if "follow Location" is set
  2600. and we're set to close anyway. */
  2601. k->keepon &= ~KEEP_RECV;
  2602. *done = TRUE;
  2603. return CURLE_OK;
  2604. }
  2605. /* We have a new url to load, but since we want to be able to re-use this
  2606. connection properly, we read the full response in "ignore more" */
  2607. k->ignorebody = TRUE;
  2608. infof(data, "Ignoring the response-body");
  2609. }
  2610. if(data->state.resume_from && !k->content_range &&
  2611. (data->state.httpreq == HTTPREQ_GET) &&
  2612. !k->ignorebody) {
  2613. if(k->size == data->state.resume_from) {
  2614. /* The resume point is at the end of file, consider this fine even if it
  2615. doesn't allow resume from here. */
  2616. infof(data, "The entire document is already downloaded");
  2617. connclose(conn, "already downloaded");
  2618. /* Abort download */
  2619. k->keepon &= ~KEEP_RECV;
  2620. *done = TRUE;
  2621. return CURLE_OK;
  2622. }
  2623. /* we wanted to resume a download, although the server doesn't seem to
  2624. * support this and we did this with a GET (if it wasn't a GET we did a
  2625. * POST or PUT resume) */
  2626. failf(data, "HTTP server doesn't seem to support "
  2627. "byte ranges. Cannot resume.");
  2628. return CURLE_RANGE_ERROR;
  2629. }
  2630. if(data->set.timecondition && !data->state.range) {
  2631. /* A time condition has been set AND no ranges have been requested. This
  2632. seems to be what chapter 13.3.4 of RFC 2616 defines to be the correct
  2633. action for a HTTP/1.1 client */
  2634. if(!Curl_meets_timecondition(data, k->timeofdoc)) {
  2635. *done = TRUE;
  2636. /* We're simulating a http 304 from server so we return
  2637. what should have been returned from the server */
  2638. data->info.httpcode = 304;
  2639. infof(data, "Simulate a HTTP 304 response!");
  2640. /* we abort the transfer before it is completed == we ruin the
  2641. re-use ability. Close the connection */
  2642. connclose(conn, "Simulated 304 handling");
  2643. return CURLE_OK;
  2644. }
  2645. } /* we have a time condition */
  2646. return CURLE_OK;
  2647. }
  2648. #ifdef HAVE_LIBZ
  2649. CURLcode Curl_transferencode(struct Curl_easy *data)
  2650. {
  2651. if(!Curl_checkheaders(data, "TE") &&
  2652. data->set.http_transfer_encoding) {
  2653. /* When we are to insert a TE: header in the request, we must also insert
  2654. TE in a Connection: header, so we need to merge the custom provided
  2655. Connection: header and prevent the original to get sent. Note that if
  2656. the user has inserted his/her own TE: header we don't do this magic
  2657. but then assume that the user will handle it all! */
  2658. char *cptr = Curl_checkheaders(data, "Connection");
  2659. #define TE_HEADER "TE: gzip\r\n"
  2660. Curl_safefree(data->state.aptr.te);
  2661. if(cptr) {
  2662. cptr = Curl_copy_header_value(cptr);
  2663. if(!cptr)
  2664. return CURLE_OUT_OF_MEMORY;
  2665. }
  2666. /* Create the (updated) Connection: header */
  2667. data->state.aptr.te = aprintf("Connection: %s%sTE\r\n" TE_HEADER,
  2668. cptr ? cptr : "", (cptr && *cptr) ? ", ":"");
  2669. free(cptr);
  2670. if(!data->state.aptr.te)
  2671. return CURLE_OUT_OF_MEMORY;
  2672. }
  2673. return CURLE_OK;
  2674. }
  2675. #endif
  2676. #ifndef USE_HYPER
  2677. /*
  2678. * Curl_http() gets called from the generic multi_do() function when a HTTP
  2679. * request is to be performed. This creates and sends a properly constructed
  2680. * HTTP request.
  2681. */
  2682. CURLcode Curl_http(struct Curl_easy *data, bool *done)
  2683. {
  2684. struct connectdata *conn = data->conn;
  2685. CURLcode result = CURLE_OK;
  2686. struct HTTP *http;
  2687. Curl_HttpReq httpreq;
  2688. const char *te = ""; /* transfer-encoding */
  2689. const char *request;
  2690. const char *httpstring;
  2691. struct dynbuf req;
  2692. char *altused = NULL;
  2693. const char *p_accept; /* Accept: string */
  2694. /* Always consider the DO phase done after this function call, even if there
  2695. may be parts of the request that are not yet sent, since we can deal with
  2696. the rest of the request in the PERFORM phase. */
  2697. *done = TRUE;
  2698. if(conn->transport != TRNSPRT_QUIC) {
  2699. if(conn->httpversion < 20) { /* unless the connection is re-used and
  2700. already http2 */
  2701. switch(conn->negnpn) {
  2702. case CURL_HTTP_VERSION_2:
  2703. conn->httpversion = 20; /* we know we're on HTTP/2 now */
  2704. result = Curl_http2_switched(data, NULL, 0);
  2705. if(result)
  2706. return result;
  2707. break;
  2708. case CURL_HTTP_VERSION_1_1:
  2709. /* continue with HTTP/1.1 when explicitly requested */
  2710. break;
  2711. default:
  2712. /* Check if user wants to use HTTP/2 with clear TCP*/
  2713. #ifdef USE_NGHTTP2
  2714. if(data->state.httpwant == CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) {
  2715. #ifndef CURL_DISABLE_PROXY
  2716. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  2717. /* We don't support HTTP/2 proxies yet. Also it's debatable
  2718. whether or not this setting should apply to HTTP/2 proxies. */
  2719. infof(data, "Ignoring HTTP/2 prior knowledge due to proxy");
  2720. break;
  2721. }
  2722. #endif
  2723. DEBUGF(infof(data, "HTTP/2 over clean TCP"));
  2724. conn->httpversion = 20;
  2725. result = Curl_http2_switched(data, NULL, 0);
  2726. if(result)
  2727. return result;
  2728. }
  2729. #endif
  2730. break;
  2731. }
  2732. }
  2733. else {
  2734. /* prepare for a http2 request */
  2735. result = Curl_http2_setup(data, conn);
  2736. if(result)
  2737. return result;
  2738. }
  2739. }
  2740. http = data->req.p.http;
  2741. DEBUGASSERT(http);
  2742. result = Curl_http_host(data, conn);
  2743. if(result)
  2744. return result;
  2745. result = Curl_http_useragent(data);
  2746. if(result)
  2747. return result;
  2748. Curl_http_method(data, conn, &request, &httpreq);
  2749. /* setup the authentication headers */
  2750. {
  2751. char *pq = NULL;
  2752. if(data->state.up.query) {
  2753. pq = aprintf("%s?%s", data->state.up.path, data->state.up.query);
  2754. if(!pq)
  2755. return CURLE_OUT_OF_MEMORY;
  2756. }
  2757. result = Curl_http_output_auth(data, conn, request, httpreq,
  2758. (pq ? pq : data->state.up.path), FALSE);
  2759. free(pq);
  2760. if(result)
  2761. return result;
  2762. }
  2763. Curl_safefree(data->state.aptr.ref);
  2764. if(data->state.referer && !Curl_checkheaders(data, "Referer")) {
  2765. data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer);
  2766. if(!data->state.aptr.ref)
  2767. return CURLE_OUT_OF_MEMORY;
  2768. }
  2769. if(!Curl_checkheaders(data, "Accept-Encoding") &&
  2770. data->set.str[STRING_ENCODING]) {
  2771. Curl_safefree(data->state.aptr.accept_encoding);
  2772. data->state.aptr.accept_encoding =
  2773. aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
  2774. if(!data->state.aptr.accept_encoding)
  2775. return CURLE_OUT_OF_MEMORY;
  2776. }
  2777. else
  2778. Curl_safefree(data->state.aptr.accept_encoding);
  2779. #ifdef HAVE_LIBZ
  2780. /* we only consider transfer-encoding magic if libz support is built-in */
  2781. result = Curl_transferencode(data);
  2782. if(result)
  2783. return result;
  2784. #endif
  2785. result = Curl_http_body(data, conn, httpreq, &te);
  2786. if(result)
  2787. return result;
  2788. p_accept = Curl_checkheaders(data, "Accept")?NULL:"Accept: */*\r\n";
  2789. result = Curl_http_resume(data, conn, httpreq);
  2790. if(result)
  2791. return result;
  2792. result = Curl_http_range(data, httpreq);
  2793. if(result)
  2794. return result;
  2795. httpstring = get_http_string(data, conn);
  2796. /* initialize a dynamic send-buffer */
  2797. Curl_dyn_init(&req, DYN_HTTP_REQUEST);
  2798. /* make sure the header buffer is reset - if there are leftovers from a
  2799. previous transfer */
  2800. Curl_dyn_reset(&data->state.headerb);
  2801. /* add the main request stuff */
  2802. /* GET/HEAD/POST/PUT */
  2803. result = Curl_dyn_addf(&req, "%s ", request);
  2804. if(!result)
  2805. result = Curl_http_target(data, conn, &req);
  2806. if(result) {
  2807. Curl_dyn_free(&req);
  2808. return result;
  2809. }
  2810. #ifndef CURL_DISABLE_ALTSVC
  2811. if(conn->bits.altused && !Curl_checkheaders(data, "Alt-Used")) {
  2812. altused = aprintf("Alt-Used: %s:%d\r\n",
  2813. conn->conn_to_host.name, conn->conn_to_port);
  2814. if(!altused) {
  2815. Curl_dyn_free(&req);
  2816. return CURLE_OUT_OF_MEMORY;
  2817. }
  2818. }
  2819. #endif
  2820. result =
  2821. Curl_dyn_addf(&req,
  2822. " HTTP/%s\r\n" /* HTTP version */
  2823. "%s" /* host */
  2824. "%s" /* proxyuserpwd */
  2825. "%s" /* userpwd */
  2826. "%s" /* range */
  2827. "%s" /* user agent */
  2828. "%s" /* accept */
  2829. "%s" /* TE: */
  2830. "%s" /* accept-encoding */
  2831. "%s" /* referer */
  2832. "%s" /* Proxy-Connection */
  2833. "%s" /* transfer-encoding */
  2834. "%s",/* Alt-Used */
  2835. httpstring,
  2836. (data->state.aptr.host?data->state.aptr.host:""),
  2837. data->state.aptr.proxyuserpwd?
  2838. data->state.aptr.proxyuserpwd:"",
  2839. data->state.aptr.userpwd?data->state.aptr.userpwd:"",
  2840. (data->state.use_range && data->state.aptr.rangeline)?
  2841. data->state.aptr.rangeline:"",
  2842. (data->set.str[STRING_USERAGENT] &&
  2843. *data->set.str[STRING_USERAGENT] &&
  2844. data->state.aptr.uagent)?
  2845. data->state.aptr.uagent:"",
  2846. p_accept?p_accept:"",
  2847. data->state.aptr.te?data->state.aptr.te:"",
  2848. (data->set.str[STRING_ENCODING] &&
  2849. *data->set.str[STRING_ENCODING] &&
  2850. data->state.aptr.accept_encoding)?
  2851. data->state.aptr.accept_encoding:"",
  2852. (data->state.referer && data->state.aptr.ref)?
  2853. data->state.aptr.ref:"" /* Referer: <data> */,
  2854. #ifndef CURL_DISABLE_PROXY
  2855. (conn->bits.httpproxy &&
  2856. !conn->bits.tunnel_proxy &&
  2857. !Curl_checkheaders(data, "Proxy-Connection") &&
  2858. !Curl_checkProxyheaders(data, conn, "Proxy-Connection"))?
  2859. "Proxy-Connection: Keep-Alive\r\n":"",
  2860. #else
  2861. "",
  2862. #endif
  2863. te,
  2864. altused ? altused : ""
  2865. );
  2866. /* clear userpwd and proxyuserpwd to avoid re-using old credentials
  2867. * from re-used connections */
  2868. Curl_safefree(data->state.aptr.userpwd);
  2869. Curl_safefree(data->state.aptr.proxyuserpwd);
  2870. free(altused);
  2871. if(result) {
  2872. Curl_dyn_free(&req);
  2873. return result;
  2874. }
  2875. if(!(conn->handler->flags&PROTOPT_SSL) &&
  2876. conn->httpversion != 20 &&
  2877. (data->state.httpwant == CURL_HTTP_VERSION_2)) {
  2878. /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done
  2879. over SSL */
  2880. result = Curl_http2_request_upgrade(&req, data);
  2881. if(result) {
  2882. Curl_dyn_free(&req);
  2883. return result;
  2884. }
  2885. }
  2886. result = Curl_http_cookies(data, conn, &req);
  2887. if(!result)
  2888. result = Curl_add_timecondition(data, &req);
  2889. if(!result)
  2890. result = Curl_add_custom_headers(data, FALSE, &req);
  2891. if(!result) {
  2892. http->postdata = NULL; /* nothing to post at this point */
  2893. if((httpreq == HTTPREQ_GET) ||
  2894. (httpreq == HTTPREQ_HEAD))
  2895. Curl_pgrsSetUploadSize(data, 0); /* nothing */
  2896. /* bodysend takes ownership of the 'req' memory on success */
  2897. result = Curl_http_bodysend(data, conn, &req, httpreq);
  2898. }
  2899. if(result) {
  2900. Curl_dyn_free(&req);
  2901. return result;
  2902. }
  2903. if((http->postsize > -1) &&
  2904. (http->postsize <= data->req.writebytecount) &&
  2905. (http->sending != HTTPSEND_REQUEST))
  2906. data->req.upload_done = TRUE;
  2907. if(data->req.writebytecount) {
  2908. /* if a request-body has been sent off, we make sure this progress is noted
  2909. properly */
  2910. Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
  2911. if(Curl_pgrsUpdate(data))
  2912. result = CURLE_ABORTED_BY_CALLBACK;
  2913. if(!http->postsize) {
  2914. /* already sent the entire request body, mark the "upload" as
  2915. complete */
  2916. infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T
  2917. " out of %" CURL_FORMAT_CURL_OFF_T " bytes",
  2918. data->req.writebytecount, http->postsize);
  2919. data->req.upload_done = TRUE;
  2920. data->req.keepon &= ~KEEP_SEND; /* we're done writing */
  2921. data->req.exp100 = EXP100_SEND_DATA; /* already sent */
  2922. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  2923. }
  2924. }
  2925. if((conn->httpversion == 20) && data->req.upload_chunky)
  2926. /* upload_chunky was set above to set up the request in a chunky fashion,
  2927. but is disabled here again to avoid that the chunked encoded version is
  2928. actually used when sending the request body over h2 */
  2929. data->req.upload_chunky = FALSE;
  2930. return result;
  2931. }
  2932. #endif /* USE_HYPER */
  2933. typedef enum {
  2934. STATUS_UNKNOWN, /* not enough data to tell yet */
  2935. STATUS_DONE, /* a status line was read */
  2936. STATUS_BAD /* not a status line */
  2937. } statusline;
  2938. /* Check a string for a prefix. Check no more than 'len' bytes */
  2939. static bool checkprefixmax(const char *prefix, const char *buffer, size_t len)
  2940. {
  2941. size_t ch = CURLMIN(strlen(prefix), len);
  2942. return curl_strnequal(prefix, buffer, ch);
  2943. }
  2944. /*
  2945. * checkhttpprefix()
  2946. *
  2947. * Returns TRUE if member of the list matches prefix of string
  2948. */
  2949. static statusline
  2950. checkhttpprefix(struct Curl_easy *data,
  2951. const char *s, size_t len)
  2952. {
  2953. struct curl_slist *head = data->set.http200aliases;
  2954. statusline rc = STATUS_BAD;
  2955. statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
  2956. #ifdef CURL_DOES_CONVERSIONS
  2957. /* convert from the network encoding using a scratch area */
  2958. char *scratch = strdup(s);
  2959. if(NULL == scratch) {
  2960. failf(data, "Failed to allocate memory for conversion!");
  2961. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2962. }
  2963. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
  2964. /* Curl_convert_from_network calls failf if unsuccessful */
  2965. free(scratch);
  2966. return FALSE; /* can't return CURLE_foobar so return FALSE */
  2967. }
  2968. s = scratch;
  2969. #endif /* CURL_DOES_CONVERSIONS */
  2970. while(head) {
  2971. if(checkprefixmax(head->data, s, len)) {
  2972. rc = onmatch;
  2973. break;
  2974. }
  2975. head = head->next;
  2976. }
  2977. if((rc != STATUS_DONE) && (checkprefixmax("HTTP/", s, len)))
  2978. rc = onmatch;
  2979. #ifdef CURL_DOES_CONVERSIONS
  2980. free(scratch);
  2981. #endif /* CURL_DOES_CONVERSIONS */
  2982. return rc;
  2983. }
  2984. #ifndef CURL_DISABLE_RTSP
  2985. static statusline
  2986. checkrtspprefix(struct Curl_easy *data,
  2987. const char *s, size_t len)
  2988. {
  2989. statusline result = STATUS_BAD;
  2990. statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
  2991. #ifdef CURL_DOES_CONVERSIONS
  2992. /* convert from the network encoding using a scratch area */
  2993. char *scratch = strdup(s);
  2994. if(NULL == scratch) {
  2995. failf(data, "Failed to allocate memory for conversion!");
  2996. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2997. }
  2998. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
  2999. /* Curl_convert_from_network calls failf if unsuccessful */
  3000. result = FALSE; /* can't return CURLE_foobar so return FALSE */
  3001. }
  3002. else if(checkprefixmax("RTSP/", scratch, len))
  3003. result = onmatch;
  3004. free(scratch);
  3005. #else
  3006. (void)data; /* unused */
  3007. if(checkprefixmax("RTSP/", s, len))
  3008. result = onmatch;
  3009. #endif /* CURL_DOES_CONVERSIONS */
  3010. return result;
  3011. }
  3012. #endif /* CURL_DISABLE_RTSP */
  3013. static statusline
  3014. checkprotoprefix(struct Curl_easy *data, struct connectdata *conn,
  3015. const char *s, size_t len)
  3016. {
  3017. #ifndef CURL_DISABLE_RTSP
  3018. if(conn->handler->protocol & CURLPROTO_RTSP)
  3019. return checkrtspprefix(data, s, len);
  3020. #else
  3021. (void)conn;
  3022. #endif /* CURL_DISABLE_RTSP */
  3023. return checkhttpprefix(data, s, len);
  3024. }
  3025. /*
  3026. * Curl_http_header() parses a single response header.
  3027. */
  3028. CURLcode Curl_http_header(struct Curl_easy *data, struct connectdata *conn,
  3029. char *headp)
  3030. {
  3031. CURLcode result;
  3032. struct SingleRequest *k = &data->req;
  3033. /* Check for Content-Length: header lines to get size */
  3034. if(!k->http_bodyless &&
  3035. !data->set.ignorecl && checkprefix("Content-Length:", headp)) {
  3036. curl_off_t contentlength;
  3037. CURLofft offt = curlx_strtoofft(headp + strlen("Content-Length:"),
  3038. NULL, 10, &contentlength);
  3039. if(offt == CURL_OFFT_OK) {
  3040. k->size = contentlength;
  3041. k->maxdownload = k->size;
  3042. }
  3043. else if(offt == CURL_OFFT_FLOW) {
  3044. /* out of range */
  3045. if(data->set.max_filesize) {
  3046. failf(data, "Maximum file size exceeded");
  3047. return CURLE_FILESIZE_EXCEEDED;
  3048. }
  3049. streamclose(conn, "overflow content-length");
  3050. infof(data, "Overflow Content-Length: value!");
  3051. }
  3052. else {
  3053. /* negative or just rubbish - bad HTTP */
  3054. failf(data, "Invalid Content-Length: value");
  3055. return CURLE_WEIRD_SERVER_REPLY;
  3056. }
  3057. }
  3058. /* check for Content-Type: header lines to get the MIME-type */
  3059. else if(checkprefix("Content-Type:", headp)) {
  3060. char *contenttype = Curl_copy_header_value(headp);
  3061. if(!contenttype)
  3062. return CURLE_OUT_OF_MEMORY;
  3063. if(!*contenttype)
  3064. /* ignore empty data */
  3065. free(contenttype);
  3066. else {
  3067. Curl_safefree(data->info.contenttype);
  3068. data->info.contenttype = contenttype;
  3069. }
  3070. }
  3071. #ifndef CURL_DISABLE_PROXY
  3072. else if((conn->httpversion == 10) &&
  3073. conn->bits.httpproxy &&
  3074. Curl_compareheader(headp, "Proxy-Connection:", "keep-alive")) {
  3075. /*
  3076. * When a HTTP/1.0 reply comes when using a proxy, the
  3077. * 'Proxy-Connection: keep-alive' line tells us the
  3078. * connection will be kept alive for our pleasure.
  3079. * Default action for 1.0 is to close.
  3080. */
  3081. connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
  3082. infof(data, "HTTP/1.0 proxy connection set to keep alive!");
  3083. }
  3084. else if((conn->httpversion == 11) &&
  3085. conn->bits.httpproxy &&
  3086. Curl_compareheader(headp, "Proxy-Connection:", "close")) {
  3087. /*
  3088. * We get a HTTP/1.1 response from a proxy and it says it'll
  3089. * close down after this transfer.
  3090. */
  3091. connclose(conn, "Proxy-Connection: asked to close after done");
  3092. infof(data, "HTTP/1.1 proxy connection set close!");
  3093. }
  3094. #endif
  3095. else if((conn->httpversion == 10) &&
  3096. Curl_compareheader(headp, "Connection:", "keep-alive")) {
  3097. /*
  3098. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  3099. * tells us the connection will be kept alive for our
  3100. * pleasure. Default action for 1.0 is to close.
  3101. *
  3102. * [RFC2068, section 19.7.1] */
  3103. connkeep(conn, "Connection keep-alive");
  3104. infof(data, "HTTP/1.0 connection set to keep alive!");
  3105. }
  3106. else if(Curl_compareheader(headp, "Connection:", "close")) {
  3107. /*
  3108. * [RFC 2616, section 8.1.2.1]
  3109. * "Connection: close" is HTTP/1.1 language and means that
  3110. * the connection will close when this request has been
  3111. * served.
  3112. */
  3113. streamclose(conn, "Connection: close used");
  3114. }
  3115. else if(!k->http_bodyless && checkprefix("Transfer-Encoding:", headp)) {
  3116. /* One or more encodings. We check for chunked and/or a compression
  3117. algorithm. */
  3118. /*
  3119. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  3120. * means that the server will send a series of "chunks". Each
  3121. * chunk starts with line with info (including size of the
  3122. * coming block) (terminated with CRLF), then a block of data
  3123. * with the previously mentioned size. There can be any amount
  3124. * of chunks, and a chunk-data set to zero signals the
  3125. * end-of-chunks. */
  3126. result = Curl_build_unencoding_stack(data,
  3127. headp + strlen("Transfer-Encoding:"),
  3128. TRUE);
  3129. if(result)
  3130. return result;
  3131. if(!k->chunk) {
  3132. /* if this isn't chunked, only close can signal the end of this transfer
  3133. as Content-Length is said not to be trusted for transfer-encoding! */
  3134. connclose(conn, "HTTP/1.1 transfer-encoding without chunks");
  3135. k->ignore_cl = TRUE;
  3136. }
  3137. }
  3138. else if(!k->http_bodyless && checkprefix("Content-Encoding:", headp) &&
  3139. data->set.str[STRING_ENCODING]) {
  3140. /*
  3141. * Process Content-Encoding. Look for the values: identity,
  3142. * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
  3143. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  3144. * 2616). zlib cannot handle compress. However, errors are
  3145. * handled further down when the response body is processed
  3146. */
  3147. result = Curl_build_unencoding_stack(data,
  3148. headp + strlen("Content-Encoding:"),
  3149. FALSE);
  3150. if(result)
  3151. return result;
  3152. }
  3153. else if(checkprefix("Retry-After:", headp)) {
  3154. /* Retry-After = HTTP-date / delay-seconds */
  3155. curl_off_t retry_after = 0; /* zero for unknown or "now" */
  3156. time_t date = Curl_getdate_capped(headp + strlen("Retry-After:"));
  3157. if(-1 == date) {
  3158. /* not a date, try it as a decimal number */
  3159. (void)curlx_strtoofft(headp + strlen("Retry-After:"),
  3160. NULL, 10, &retry_after);
  3161. }
  3162. else
  3163. /* convert date to number of seconds into the future */
  3164. retry_after = date - time(NULL);
  3165. data->info.retry_after = retry_after; /* store it */
  3166. }
  3167. else if(!k->http_bodyless && checkprefix("Content-Range:", headp)) {
  3168. /* Content-Range: bytes [num]-
  3169. Content-Range: bytes: [num]-
  3170. Content-Range: [num]-
  3171. Content-Range: [asterisk]/[total]
  3172. The second format was added since Sun's webserver
  3173. JavaWebServer/1.1.1 obviously sends the header this way!
  3174. The third added since some servers use that!
  3175. The forth means the requested range was unsatisfied.
  3176. */
  3177. char *ptr = headp + strlen("Content-Range:");
  3178. /* Move forward until first digit or asterisk */
  3179. while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
  3180. ptr++;
  3181. /* if it truly stopped on a digit */
  3182. if(ISDIGIT(*ptr)) {
  3183. if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) {
  3184. if(data->state.resume_from == k->offset)
  3185. /* we asked for a resume and we got it */
  3186. k->content_range = TRUE;
  3187. }
  3188. }
  3189. else
  3190. data->state.resume_from = 0; /* get everything */
  3191. }
  3192. #if !defined(CURL_DISABLE_COOKIES)
  3193. else if(data->cookies && data->state.cookie_engine &&
  3194. checkprefix("Set-Cookie:", headp)) {
  3195. /* If there is a custom-set Host: name, use it here, or else use real peer
  3196. host name. */
  3197. const char *host = data->state.aptr.cookiehost?
  3198. data->state.aptr.cookiehost:conn->host.name;
  3199. const bool secure_context =
  3200. conn->handler->protocol&CURLPROTO_HTTPS ||
  3201. strcasecompare("localhost", host) ||
  3202. !strcmp(host, "127.0.0.1") ||
  3203. !strcmp(host, "[::1]") ? TRUE : FALSE;
  3204. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
  3205. CURL_LOCK_ACCESS_SINGLE);
  3206. Curl_cookie_add(data, data->cookies, TRUE, FALSE,
  3207. headp + strlen("Set-Cookie:"), host,
  3208. data->state.up.path, secure_context);
  3209. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  3210. }
  3211. #endif
  3212. else if(!k->http_bodyless && checkprefix("Last-Modified:", headp) &&
  3213. (data->set.timecondition || data->set.get_filetime) ) {
  3214. k->timeofdoc = Curl_getdate_capped(headp + strlen("Last-Modified:"));
  3215. if(data->set.get_filetime)
  3216. data->info.filetime = k->timeofdoc;
  3217. }
  3218. else if((checkprefix("WWW-Authenticate:", headp) &&
  3219. (401 == k->httpcode)) ||
  3220. (checkprefix("Proxy-authenticate:", headp) &&
  3221. (407 == k->httpcode))) {
  3222. bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
  3223. char *auth = Curl_copy_header_value(headp);
  3224. if(!auth)
  3225. return CURLE_OUT_OF_MEMORY;
  3226. result = Curl_http_input_auth(data, proxy, auth);
  3227. free(auth);
  3228. if(result)
  3229. return result;
  3230. }
  3231. #ifdef USE_SPNEGO
  3232. else if(checkprefix("Persistent-Auth:", headp)) {
  3233. struct negotiatedata *negdata = &conn->negotiate;
  3234. struct auth *authp = &data->state.authhost;
  3235. if(authp->picked == CURLAUTH_NEGOTIATE) {
  3236. char *persistentauth = Curl_copy_header_value(headp);
  3237. if(!persistentauth)
  3238. return CURLE_OUT_OF_MEMORY;
  3239. negdata->noauthpersist = checkprefix("false", persistentauth)?
  3240. TRUE:FALSE;
  3241. negdata->havenoauthpersist = TRUE;
  3242. infof(data, "Negotiate: noauthpersist -> %d, header part: %s",
  3243. negdata->noauthpersist, persistentauth);
  3244. free(persistentauth);
  3245. }
  3246. }
  3247. #endif
  3248. else if((k->httpcode >= 300 && k->httpcode < 400) &&
  3249. checkprefix("Location:", headp) &&
  3250. !data->req.location) {
  3251. /* this is the URL that the server advises us to use instead */
  3252. char *location = Curl_copy_header_value(headp);
  3253. if(!location)
  3254. return CURLE_OUT_OF_MEMORY;
  3255. if(!*location)
  3256. /* ignore empty data */
  3257. free(location);
  3258. else {
  3259. data->req.location = location;
  3260. if(data->set.http_follow_location) {
  3261. DEBUGASSERT(!data->req.newurl);
  3262. data->req.newurl = strdup(data->req.location); /* clone */
  3263. if(!data->req.newurl)
  3264. return CURLE_OUT_OF_MEMORY;
  3265. /* some cases of POST and PUT etc needs to rewind the data
  3266. stream at this point */
  3267. result = http_perhapsrewind(data, conn);
  3268. if(result)
  3269. return result;
  3270. }
  3271. }
  3272. }
  3273. #ifndef CURL_DISABLE_HSTS
  3274. /* If enabled, the header is incoming and this is over HTTPS */
  3275. else if(data->hsts && checkprefix("Strict-Transport-Security:", headp) &&
  3276. (conn->handler->flags & PROTOPT_SSL)) {
  3277. CURLcode check =
  3278. Curl_hsts_parse(data->hsts, data->state.up.hostname,
  3279. headp + strlen("Strict-Transport-Security:"));
  3280. if(check)
  3281. infof(data, "Illegal STS header skipped");
  3282. #ifdef DEBUGBUILD
  3283. else
  3284. infof(data, "Parsed STS header fine (%zu entries)",
  3285. data->hsts->list.size);
  3286. #endif
  3287. }
  3288. #endif
  3289. #ifndef CURL_DISABLE_ALTSVC
  3290. /* If enabled, the header is incoming and this is over HTTPS */
  3291. else if(data->asi && checkprefix("Alt-Svc:", headp) &&
  3292. ((conn->handler->flags & PROTOPT_SSL) ||
  3293. #ifdef CURLDEBUG
  3294. /* allow debug builds to circumvent the HTTPS restriction */
  3295. getenv("CURL_ALTSVC_HTTP")
  3296. #else
  3297. 0
  3298. #endif
  3299. )) {
  3300. /* the ALPN of the current request */
  3301. enum alpnid id = (conn->httpversion == 20) ? ALPN_h2 : ALPN_h1;
  3302. result = Curl_altsvc_parse(data, data->asi,
  3303. headp + strlen("Alt-Svc:"),
  3304. id, conn->host.name,
  3305. curlx_uitous(conn->remote_port));
  3306. if(result)
  3307. return result;
  3308. }
  3309. #endif
  3310. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  3311. result = Curl_rtsp_parseheader(data, headp);
  3312. if(result)
  3313. return result;
  3314. }
  3315. return CURLE_OK;
  3316. }
  3317. /*
  3318. * Called after the first HTTP response line (the status line) has been
  3319. * received and parsed.
  3320. */
  3321. CURLcode Curl_http_statusline(struct Curl_easy *data,
  3322. struct connectdata *conn)
  3323. {
  3324. struct SingleRequest *k = &data->req;
  3325. data->info.httpcode = k->httpcode;
  3326. data->info.httpversion = conn->httpversion;
  3327. if(!data->state.httpversion ||
  3328. data->state.httpversion > conn->httpversion)
  3329. /* store the lowest server version we encounter */
  3330. data->state.httpversion = conn->httpversion;
  3331. /*
  3332. * This code executes as part of processing the header. As a
  3333. * result, it's not totally clear how to interpret the
  3334. * response code yet as that depends on what other headers may
  3335. * be present. 401 and 407 may be errors, but may be OK
  3336. * depending on how authentication is working. Other codes
  3337. * are definitely errors, so give up here.
  3338. */
  3339. if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET &&
  3340. k->httpcode == 416) {
  3341. /* "Requested Range Not Satisfiable", just proceed and
  3342. pretend this is no error */
  3343. k->ignorebody = TRUE; /* Avoid appending error msg to good data. */
  3344. }
  3345. if(conn->httpversion == 10) {
  3346. /* Default action for HTTP/1.0 must be to close, unless
  3347. we get one of those fancy headers that tell us the
  3348. server keeps it open for us! */
  3349. infof(data, "HTTP 1.0, assume close after body");
  3350. connclose(conn, "HTTP/1.0 close after body");
  3351. }
  3352. else if(conn->httpversion == 20 ||
  3353. (k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) {
  3354. DEBUGF(infof(data, "HTTP/2 found, allow multiplexing"));
  3355. /* HTTP/2 cannot avoid multiplexing since it is a core functionality
  3356. of the protocol */
  3357. conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  3358. }
  3359. else if(conn->httpversion >= 11 &&
  3360. !conn->bits.close) {
  3361. /* If HTTP version is >= 1.1 and connection is persistent */
  3362. DEBUGF(infof(data,
  3363. "HTTP 1.1 or later with persistent connection"));
  3364. }
  3365. k->http_bodyless = k->httpcode >= 100 && k->httpcode < 200;
  3366. switch(k->httpcode) {
  3367. case 304:
  3368. /* (quote from RFC2616, section 10.3.5): The 304 response
  3369. * MUST NOT contain a message-body, and thus is always
  3370. * terminated by the first empty line after the header
  3371. * fields. */
  3372. if(data->set.timecondition)
  3373. data->info.timecond = TRUE;
  3374. /* FALLTHROUGH */
  3375. case 204:
  3376. /* (quote from RFC2616, section 10.2.5): The server has
  3377. * fulfilled the request but does not need to return an
  3378. * entity-body ... The 204 response MUST NOT include a
  3379. * message-body, and thus is always terminated by the first
  3380. * empty line after the header fields. */
  3381. k->size = 0;
  3382. k->maxdownload = 0;
  3383. k->http_bodyless = TRUE;
  3384. break;
  3385. default:
  3386. break;
  3387. }
  3388. return CURLE_OK;
  3389. }
  3390. /*
  3391. * Read any HTTP header lines from the server and pass them to the client app.
  3392. */
  3393. CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
  3394. struct connectdata *conn,
  3395. ssize_t *nread,
  3396. bool *stop_reading)
  3397. {
  3398. CURLcode result;
  3399. struct SingleRequest *k = &data->req;
  3400. ssize_t onread = *nread;
  3401. char *ostr = k->str;
  3402. char *headp;
  3403. char *str_start;
  3404. char *end_ptr;
  3405. /* header line within buffer loop */
  3406. do {
  3407. size_t rest_length;
  3408. size_t full_length;
  3409. int writetype;
  3410. /* str_start is start of line within buf */
  3411. str_start = k->str;
  3412. /* data is in network encoding so use 0x0a instead of '\n' */
  3413. end_ptr = memchr(str_start, 0x0a, *nread);
  3414. if(!end_ptr) {
  3415. /* Not a complete header line within buffer, append the data to
  3416. the end of the headerbuff. */
  3417. result = Curl_dyn_addn(&data->state.headerb, str_start, *nread);
  3418. if(result)
  3419. return result;
  3420. if(!k->headerline) {
  3421. /* check if this looks like a protocol header */
  3422. statusline st =
  3423. checkprotoprefix(data, conn,
  3424. Curl_dyn_ptr(&data->state.headerb),
  3425. Curl_dyn_len(&data->state.headerb));
  3426. if(st == STATUS_BAD) {
  3427. /* this is not the beginning of a protocol first header line */
  3428. k->header = FALSE;
  3429. k->badheader = HEADER_ALLBAD;
  3430. streamclose(conn, "bad HTTP: No end-of-message indicator");
  3431. if(!data->set.http09_allowed) {
  3432. failf(data, "Received HTTP/0.9 when not allowed");
  3433. return CURLE_UNSUPPORTED_PROTOCOL;
  3434. }
  3435. break;
  3436. }
  3437. }
  3438. break; /* read more and try again */
  3439. }
  3440. /* decrease the size of the remaining (supposed) header line */
  3441. rest_length = (end_ptr - k->str) + 1;
  3442. *nread -= (ssize_t)rest_length;
  3443. k->str = end_ptr + 1; /* move past new line */
  3444. full_length = k->str - str_start;
  3445. result = Curl_dyn_addn(&data->state.headerb, str_start, full_length);
  3446. if(result)
  3447. return result;
  3448. /****
  3449. * We now have a FULL header line in 'headerb'.
  3450. *****/
  3451. if(!k->headerline) {
  3452. /* the first read header */
  3453. statusline st = checkprotoprefix(data, conn,
  3454. Curl_dyn_ptr(&data->state.headerb),
  3455. Curl_dyn_len(&data->state.headerb));
  3456. if(st == STATUS_BAD) {
  3457. streamclose(conn, "bad HTTP: No end-of-message indicator");
  3458. /* this is not the beginning of a protocol first header line */
  3459. if(!data->set.http09_allowed) {
  3460. failf(data, "Received HTTP/0.9 when not allowed");
  3461. return CURLE_UNSUPPORTED_PROTOCOL;
  3462. }
  3463. k->header = FALSE;
  3464. if(*nread)
  3465. /* since there's more, this is a partial bad header */
  3466. k->badheader = HEADER_PARTHEADER;
  3467. else {
  3468. /* this was all we read so it's all a bad header */
  3469. k->badheader = HEADER_ALLBAD;
  3470. *nread = onread;
  3471. k->str = ostr;
  3472. return CURLE_OK;
  3473. }
  3474. break;
  3475. }
  3476. }
  3477. /* headers are in network encoding so use 0x0a and 0x0d instead of '\n'
  3478. and '\r' */
  3479. headp = Curl_dyn_ptr(&data->state.headerb);
  3480. if((0x0a == *headp) || (0x0d == *headp)) {
  3481. size_t headerlen;
  3482. /* Zero-length header line means end of headers! */
  3483. #ifdef CURL_DOES_CONVERSIONS
  3484. if(0x0d == *headp) {
  3485. *headp = '\r'; /* replace with CR in host encoding */
  3486. headp++; /* pass the CR byte */
  3487. }
  3488. if(0x0a == *headp) {
  3489. *headp = '\n'; /* replace with LF in host encoding */
  3490. headp++; /* pass the LF byte */
  3491. }
  3492. #else
  3493. if('\r' == *headp)
  3494. headp++; /* pass the \r byte */
  3495. if('\n' == *headp)
  3496. headp++; /* pass the \n byte */
  3497. #endif /* CURL_DOES_CONVERSIONS */
  3498. if(100 <= k->httpcode && 199 >= k->httpcode) {
  3499. /* "A user agent MAY ignore unexpected 1xx status responses." */
  3500. switch(k->httpcode) {
  3501. case 100:
  3502. /*
  3503. * We have made a HTTP PUT or POST and this is 1.1-lingo
  3504. * that tells us that the server is OK with this and ready
  3505. * to receive the data.
  3506. * However, we'll get more headers now so we must get
  3507. * back into the header-parsing state!
  3508. */
  3509. k->header = TRUE;
  3510. k->headerline = 0; /* restart the header line counter */
  3511. /* if we did wait for this do enable write now! */
  3512. if(k->exp100 > EXP100_SEND_DATA) {
  3513. k->exp100 = EXP100_SEND_DATA;
  3514. k->keepon |= KEEP_SEND;
  3515. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  3516. }
  3517. break;
  3518. case 101:
  3519. /* Switching Protocols */
  3520. if(k->upgr101 == UPGR101_REQUESTED) {
  3521. /* Switching to HTTP/2 */
  3522. infof(data, "Received 101");
  3523. k->upgr101 = UPGR101_RECEIVED;
  3524. /* we'll get more headers (HTTP/2 response) */
  3525. k->header = TRUE;
  3526. k->headerline = 0; /* restart the header line counter */
  3527. /* switch to http2 now. The bytes after response headers
  3528. are also processed here, otherwise they are lost. */
  3529. result = Curl_http2_switched(data, k->str, *nread);
  3530. if(result)
  3531. return result;
  3532. *nread = 0;
  3533. }
  3534. else {
  3535. /* Switching to another protocol (e.g. WebSocket) */
  3536. k->header = FALSE; /* no more header to parse! */
  3537. }
  3538. break;
  3539. default:
  3540. /* the status code 1xx indicates a provisional response, so
  3541. we'll get another set of headers */
  3542. k->header = TRUE;
  3543. k->headerline = 0; /* restart the header line counter */
  3544. break;
  3545. }
  3546. }
  3547. else {
  3548. k->header = FALSE; /* no more header to parse! */
  3549. if((k->size == -1) && !k->chunk && !conn->bits.close &&
  3550. (conn->httpversion == 11) &&
  3551. !(conn->handler->protocol & CURLPROTO_RTSP) &&
  3552. data->state.httpreq != HTTPREQ_HEAD) {
  3553. /* On HTTP 1.1, when connection is not to get closed, but no
  3554. Content-Length nor Transfer-Encoding chunked have been
  3555. received, according to RFC2616 section 4.4 point 5, we
  3556. assume that the server will close the connection to
  3557. signal the end of the document. */
  3558. infof(data, "no chunk, no close, no size. Assume close to "
  3559. "signal end");
  3560. streamclose(conn, "HTTP: No end-of-message indicator");
  3561. }
  3562. }
  3563. /* At this point we have some idea about the fate of the connection.
  3564. If we are closing the connection it may result auth failure. */
  3565. #if defined(USE_NTLM)
  3566. if(conn->bits.close &&
  3567. (((data->req.httpcode == 401) &&
  3568. (conn->http_ntlm_state == NTLMSTATE_TYPE2)) ||
  3569. ((data->req.httpcode == 407) &&
  3570. (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) {
  3571. infof(data, "Connection closure while negotiating auth (HTTP 1.0?)");
  3572. data->state.authproblem = TRUE;
  3573. }
  3574. #endif
  3575. #if defined(USE_SPNEGO)
  3576. if(conn->bits.close &&
  3577. (((data->req.httpcode == 401) &&
  3578. (conn->http_negotiate_state == GSS_AUTHRECV)) ||
  3579. ((data->req.httpcode == 407) &&
  3580. (conn->proxy_negotiate_state == GSS_AUTHRECV)))) {
  3581. infof(data, "Connection closure while negotiating auth (HTTP 1.0?)");
  3582. data->state.authproblem = TRUE;
  3583. }
  3584. if((conn->http_negotiate_state == GSS_AUTHDONE) &&
  3585. (data->req.httpcode != 401)) {
  3586. conn->http_negotiate_state = GSS_AUTHSUCC;
  3587. }
  3588. if((conn->proxy_negotiate_state == GSS_AUTHDONE) &&
  3589. (data->req.httpcode != 407)) {
  3590. conn->proxy_negotiate_state = GSS_AUTHSUCC;
  3591. }
  3592. #endif
  3593. /* now, only output this if the header AND body are requested:
  3594. */
  3595. writetype = CLIENTWRITE_HEADER;
  3596. if(data->set.include_header)
  3597. writetype |= CLIENTWRITE_BODY;
  3598. headerlen = Curl_dyn_len(&data->state.headerb);
  3599. result = Curl_client_write(data, writetype,
  3600. Curl_dyn_ptr(&data->state.headerb),
  3601. headerlen);
  3602. if(result)
  3603. return result;
  3604. data->info.header_size += (long)headerlen;
  3605. data->req.headerbytecount += (long)headerlen;
  3606. /*
  3607. * When all the headers have been parsed, see if we should give
  3608. * up and return an error.
  3609. */
  3610. if(http_should_fail(data)) {
  3611. failf(data, "The requested URL returned error: %d",
  3612. k->httpcode);
  3613. return CURLE_HTTP_RETURNED_ERROR;
  3614. }
  3615. data->req.deductheadercount =
  3616. (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
  3617. /* Curl_http_auth_act() checks what authentication methods
  3618. * that are available and decides which one (if any) to
  3619. * use. It will set 'newurl' if an auth method was picked. */
  3620. result = Curl_http_auth_act(data);
  3621. if(result)
  3622. return result;
  3623. if(k->httpcode >= 300) {
  3624. if((!conn->bits.authneg) && !conn->bits.close &&
  3625. !conn->bits.rewindaftersend) {
  3626. /*
  3627. * General treatment of errors when about to send data. Including :
  3628. * "417 Expectation Failed", while waiting for 100-continue.
  3629. *
  3630. * The check for close above is done simply because of something
  3631. * else has already deemed the connection to get closed then
  3632. * something else should've considered the big picture and we
  3633. * avoid this check.
  3634. *
  3635. * rewindaftersend indicates that something has told libcurl to
  3636. * continue sending even if it gets discarded
  3637. */
  3638. switch(data->state.httpreq) {
  3639. case HTTPREQ_PUT:
  3640. case HTTPREQ_POST:
  3641. case HTTPREQ_POST_FORM:
  3642. case HTTPREQ_POST_MIME:
  3643. /* We got an error response. If this happened before the whole
  3644. * request body has been sent we stop sending and mark the
  3645. * connection for closure after we've read the entire response.
  3646. */
  3647. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  3648. if(!k->upload_done) {
  3649. if((k->httpcode == 417) && data->state.expect100header) {
  3650. /* 417 Expectation Failed - try again without the Expect
  3651. header */
  3652. infof(data, "Got 417 while waiting for a 100");
  3653. data->state.disableexpect = TRUE;
  3654. DEBUGASSERT(!data->req.newurl);
  3655. data->req.newurl = strdup(data->state.url);
  3656. Curl_done_sending(data, k);
  3657. }
  3658. else if(data->set.http_keep_sending_on_error) {
  3659. infof(data, "HTTP error before end of send, keep sending");
  3660. if(k->exp100 > EXP100_SEND_DATA) {
  3661. k->exp100 = EXP100_SEND_DATA;
  3662. k->keepon |= KEEP_SEND;
  3663. }
  3664. }
  3665. else {
  3666. infof(data, "HTTP error before end of send, stop sending");
  3667. streamclose(conn, "Stop sending data before everything sent");
  3668. result = Curl_done_sending(data, k);
  3669. if(result)
  3670. return result;
  3671. k->upload_done = TRUE;
  3672. if(data->state.expect100header)
  3673. k->exp100 = EXP100_FAILED;
  3674. }
  3675. }
  3676. break;
  3677. default: /* default label present to avoid compiler warnings */
  3678. break;
  3679. }
  3680. }
  3681. if(conn->bits.rewindaftersend) {
  3682. /* We rewind after a complete send, so thus we continue
  3683. sending now */
  3684. infof(data, "Keep sending data to get tossed away!");
  3685. k->keepon |= KEEP_SEND;
  3686. }
  3687. }
  3688. if(!k->header) {
  3689. /*
  3690. * really end-of-headers.
  3691. *
  3692. * If we requested a "no body", this is a good time to get
  3693. * out and return home.
  3694. */
  3695. if(data->set.opt_no_body)
  3696. *stop_reading = TRUE;
  3697. #ifndef CURL_DISABLE_RTSP
  3698. else if((conn->handler->protocol & CURLPROTO_RTSP) &&
  3699. (data->set.rtspreq == RTSPREQ_DESCRIBE) &&
  3700. (k->size <= -1))
  3701. /* Respect section 4.4 of rfc2326: If the Content-Length header is
  3702. absent, a length 0 must be assumed. It will prevent libcurl from
  3703. hanging on DESCRIBE request that got refused for whatever
  3704. reason */
  3705. *stop_reading = TRUE;
  3706. #endif
  3707. else {
  3708. /* If we know the expected size of this document, we set the
  3709. maximum download size to the size of the expected
  3710. document or else, we won't know when to stop reading!
  3711. Note that we set the download maximum even if we read a
  3712. "Connection: close" header, to make sure that
  3713. "Content-Length: 0" still prevents us from attempting to
  3714. read the (missing) response-body.
  3715. */
  3716. /* According to RFC2616 section 4.4, we MUST ignore
  3717. Content-Length: headers if we are now receiving data
  3718. using chunked Transfer-Encoding.
  3719. */
  3720. if(k->chunk)
  3721. k->maxdownload = k->size = -1;
  3722. }
  3723. if(-1 != k->size) {
  3724. /* We do this operation even if no_body is true, since this
  3725. data might be retrieved later with curl_easy_getinfo()
  3726. and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
  3727. Curl_pgrsSetDownloadSize(data, k->size);
  3728. k->maxdownload = k->size;
  3729. }
  3730. /* If max download size is *zero* (nothing) we already have
  3731. nothing and can safely return ok now! But for HTTP/2, we'd
  3732. like to call http2_handle_stream_close to properly close a
  3733. stream. In order to do this, we keep reading until we
  3734. close the stream. */
  3735. if(0 == k->maxdownload
  3736. #if defined(USE_NGHTTP2)
  3737. && !((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  3738. conn->httpversion == 20)
  3739. #endif
  3740. )
  3741. *stop_reading = TRUE;
  3742. if(*stop_reading) {
  3743. /* we make sure that this socket isn't read more now */
  3744. k->keepon &= ~KEEP_RECV;
  3745. }
  3746. Curl_debug(data, CURLINFO_HEADER_IN, str_start, headerlen);
  3747. break; /* exit header line loop */
  3748. }
  3749. /* We continue reading headers, reset the line-based header */
  3750. Curl_dyn_reset(&data->state.headerb);
  3751. continue;
  3752. }
  3753. /*
  3754. * Checks for special headers coming up.
  3755. */
  3756. if(!k->headerline++) {
  3757. /* This is the first header, it MUST be the error code line
  3758. or else we consider this to be the body right away! */
  3759. int httpversion_major;
  3760. int rtspversion_major;
  3761. int nc = 0;
  3762. #ifdef CURL_DOES_CONVERSIONS
  3763. #define HEADER1 scratch
  3764. #define SCRATCHSIZE 21
  3765. CURLcode res;
  3766. char scratch[SCRATCHSIZE + 1]; /* "HTTP/major.minor 123" */
  3767. /* We can't really convert this yet because we don't know if it's the
  3768. 1st header line or the body. So we do a partial conversion into a
  3769. scratch area, leaving the data at 'headp' as-is.
  3770. */
  3771. strncpy(&scratch[0], headp, SCRATCHSIZE);
  3772. scratch[SCRATCHSIZE] = 0; /* null terminate */
  3773. res = Curl_convert_from_network(data,
  3774. &scratch[0],
  3775. SCRATCHSIZE);
  3776. if(res)
  3777. /* Curl_convert_from_network calls failf if unsuccessful */
  3778. return res;
  3779. #else
  3780. #define HEADER1 headp /* no conversion needed, just use headp */
  3781. #endif /* CURL_DOES_CONVERSIONS */
  3782. if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
  3783. /*
  3784. * https://tools.ietf.org/html/rfc7230#section-3.1.2
  3785. *
  3786. * The response code is always a three-digit number in HTTP as the spec
  3787. * says. We allow any three-digit number here, but we cannot make
  3788. * guarantees on future behaviors since it isn't within the protocol.
  3789. */
  3790. char separator;
  3791. char twoorthree[2];
  3792. int httpversion = 0;
  3793. char digit4 = 0;
  3794. nc = sscanf(HEADER1,
  3795. " HTTP/%1d.%1d%c%3d%c",
  3796. &httpversion_major,
  3797. &httpversion,
  3798. &separator,
  3799. &k->httpcode,
  3800. &digit4);
  3801. if(nc == 1 && httpversion_major >= 2 &&
  3802. 2 == sscanf(HEADER1, " HTTP/%1[23] %d", twoorthree, &k->httpcode)) {
  3803. conn->httpversion = 0;
  3804. nc = 4;
  3805. separator = ' ';
  3806. }
  3807. /* There can only be a 4th response code digit stored in 'digit4' if
  3808. all the other fields were parsed and stored first, so nc is 5 when
  3809. digit4 a digit */
  3810. else if(ISDIGIT(digit4)) {
  3811. failf(data, "Unsupported response code in HTTP response");
  3812. return CURLE_UNSUPPORTED_PROTOCOL;
  3813. }
  3814. if((nc >= 4) && (' ' == separator)) {
  3815. httpversion += 10 * httpversion_major;
  3816. switch(httpversion) {
  3817. case 10:
  3818. case 11:
  3819. #if defined(USE_NGHTTP2) || defined(USE_HYPER)
  3820. case 20:
  3821. #endif
  3822. #if defined(ENABLE_QUIC)
  3823. case 30:
  3824. #endif
  3825. conn->httpversion = (unsigned char)httpversion;
  3826. break;
  3827. default:
  3828. failf(data, "Unsupported HTTP version (%u.%d) in response",
  3829. httpversion/10, httpversion%10);
  3830. return CURLE_UNSUPPORTED_PROTOCOL;
  3831. }
  3832. if(k->upgr101 == UPGR101_RECEIVED) {
  3833. /* supposedly upgraded to http2 now */
  3834. if(conn->httpversion != 20)
  3835. infof(data, "Lying server, not serving HTTP/2");
  3836. }
  3837. if(conn->httpversion < 20) {
  3838. conn->bundle->multiuse = BUNDLE_NO_MULTIUSE;
  3839. infof(data, "Mark bundle as not supporting multiuse");
  3840. }
  3841. }
  3842. else if(!nc) {
  3843. /* this is the real world, not a Nirvana
  3844. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  3845. */
  3846. nc = sscanf(HEADER1, " HTTP %3d", &k->httpcode);
  3847. conn->httpversion = 10;
  3848. /* If user has set option HTTP200ALIASES,
  3849. compare header line against list of aliases
  3850. */
  3851. if(!nc) {
  3852. statusline check =
  3853. checkhttpprefix(data,
  3854. Curl_dyn_ptr(&data->state.headerb),
  3855. Curl_dyn_len(&data->state.headerb));
  3856. if(check == STATUS_DONE) {
  3857. nc = 1;
  3858. k->httpcode = 200;
  3859. conn->httpversion = 10;
  3860. }
  3861. }
  3862. }
  3863. else {
  3864. failf(data, "Unsupported HTTP version in response");
  3865. return CURLE_UNSUPPORTED_PROTOCOL;
  3866. }
  3867. }
  3868. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  3869. char separator;
  3870. int rtspversion;
  3871. nc = sscanf(HEADER1,
  3872. " RTSP/%1d.%1d%c%3d",
  3873. &rtspversion_major,
  3874. &rtspversion,
  3875. &separator,
  3876. &k->httpcode);
  3877. if((nc == 4) && (' ' == separator)) {
  3878. conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
  3879. }
  3880. else {
  3881. nc = 0;
  3882. }
  3883. }
  3884. if(nc) {
  3885. result = Curl_http_statusline(data, conn);
  3886. if(result)
  3887. return result;
  3888. }
  3889. else {
  3890. k->header = FALSE; /* this is not a header line */
  3891. break;
  3892. }
  3893. }
  3894. result = Curl_convert_from_network(data, headp, strlen(headp));
  3895. /* Curl_convert_from_network calls failf if unsuccessful */
  3896. if(result)
  3897. return result;
  3898. result = Curl_http_header(data, conn, headp);
  3899. if(result)
  3900. return result;
  3901. /*
  3902. * End of header-checks. Write them to the client.
  3903. */
  3904. writetype = CLIENTWRITE_HEADER;
  3905. if(data->set.include_header)
  3906. writetype |= CLIENTWRITE_BODY;
  3907. Curl_debug(data, CURLINFO_HEADER_IN, headp,
  3908. Curl_dyn_len(&data->state.headerb));
  3909. result = Curl_client_write(data, writetype, headp,
  3910. Curl_dyn_len(&data->state.headerb));
  3911. if(result)
  3912. return result;
  3913. data->info.header_size += Curl_dyn_len(&data->state.headerb);
  3914. data->req.headerbytecount += Curl_dyn_len(&data->state.headerb);
  3915. Curl_dyn_reset(&data->state.headerb);
  3916. }
  3917. while(*k->str); /* header line within buffer */
  3918. /* We might have reached the end of the header part here, but
  3919. there might be a non-header part left in the end of the read
  3920. buffer. */
  3921. return CURLE_OK;
  3922. }
  3923. #endif /* CURL_DISABLE_HTTP */