http.c 112 KB

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