http.c 136 KB

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