http.c 128 KB

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