http.c 137 KB

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