http.c 128 KB

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