http.c 120 KB

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