2
0

http.c 135 KB

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