http.c 132 KB

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