http.c 141 KB

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