http.c 153 KB

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