http.c 141 KB

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