http.c 152 KB

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