http.c 119 KB

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