http.c 141 KB

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