http.c 155 KB

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