http.c 136 KB

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