2
0

http.c 116 KB

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