http.c 153 KB

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