2
0

http.c 133 KB

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