http.c 137 KB

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