http.c 136 KB

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