http.c 152 KB

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