http.c 149 KB

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