http.c 137 KB

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