http.c 133 KB

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