http.c 154 KB

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