2
0

http.c 137 KB

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