http.c 137 KB

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