2
0

http.c 137 KB

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