transfer.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2009, 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. * $Id$
  22. ***************************************************************************/
  23. #include "setup.h"
  24. /* -- WIN32 approved -- */
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <stdarg.h>
  28. #include <stdlib.h>
  29. #include <ctype.h>
  30. #include <errno.h>
  31. #include "strtoofft.h"
  32. #include "strequal.h"
  33. #include "rawstr.h"
  34. #ifdef WIN32
  35. #include <time.h>
  36. #include <io.h>
  37. #else
  38. #ifdef HAVE_SYS_SOCKET_H
  39. #include <sys/socket.h>
  40. #endif
  41. #ifdef HAVE_NETINET_IN_H
  42. #include <netinet/in.h>
  43. #endif
  44. #ifdef HAVE_SYS_TIME_H
  45. #include <sys/time.h>
  46. #endif
  47. #ifdef HAVE_UNISTD_H
  48. #include <unistd.h>
  49. #endif
  50. #ifdef HAVE_NETDB_H
  51. #include <netdb.h>
  52. #endif
  53. #ifdef HAVE_ARPA_INET_H
  54. #include <arpa/inet.h>
  55. #endif
  56. #ifdef HAVE_NET_IF_H
  57. #include <net/if.h>
  58. #endif
  59. #ifdef HAVE_SYS_IOCTL_H
  60. #include <sys/ioctl.h>
  61. #endif
  62. #ifdef HAVE_SIGNAL_H
  63. #include <signal.h>
  64. #endif
  65. #ifdef HAVE_SYS_PARAM_H
  66. #include <sys/param.h>
  67. #endif
  68. #ifdef HAVE_SYS_SELECT_H
  69. #include <sys/select.h>
  70. #endif
  71. #ifndef HAVE_SOCKET
  72. #error "We can't compile without socket() support!"
  73. #endif
  74. #endif /* WIN32 */
  75. #include "urldata.h"
  76. #include <curl/curl.h>
  77. #include "netrc.h"
  78. #include "content_encoding.h"
  79. #include "hostip.h"
  80. #include "transfer.h"
  81. #include "sendf.h"
  82. #include "speedcheck.h"
  83. #include "progress.h"
  84. #include "http.h"
  85. #include "url.h"
  86. #include "getinfo.h"
  87. #include "sslgen.h"
  88. #include "http_digest.h"
  89. #include "http_ntlm.h"
  90. #include "http_negotiate.h"
  91. #include "share.h"
  92. #include "curl_memory.h"
  93. #include "select.h"
  94. #include "multiif.h"
  95. #include "easyif.h" /* for Curl_convert_to_network prototype */
  96. #define _MPRINTF_REPLACE /* use our functions only */
  97. #include <curl/mprintf.h>
  98. /* The last #include file should be: */
  99. #include "memdebug.h"
  100. #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
  101. #ifndef CURL_DISABLE_HTTP
  102. static CURLcode readwrite_http_headers(struct SessionHandle *data,
  103. struct connectdata *conn,
  104. struct SingleRequest *k,
  105. ssize_t *nread,
  106. bool *stop_reading);
  107. #endif /* CURL_DISABLE_HTTP */
  108. /*
  109. * This function will call the read callback to fill our buffer with data
  110. * to upload.
  111. */
  112. CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
  113. {
  114. struct SessionHandle *data = conn->data;
  115. size_t buffersize = (size_t)bytes;
  116. int nread;
  117. if(data->req.upload_chunky) {
  118. /* if chunked Transfer-Encoding */
  119. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  120. data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
  121. }
  122. /* this function returns a size_t, so we typecast to int to prevent warnings
  123. with picky compilers */
  124. nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
  125. buffersize, conn->fread_in);
  126. if(nread == CURL_READFUNC_ABORT) {
  127. failf(data, "operation aborted by callback");
  128. *nreadp = 0;
  129. return CURLE_ABORTED_BY_CALLBACK;
  130. }
  131. else if(nread == CURL_READFUNC_PAUSE) {
  132. struct SingleRequest *k = &data->req;
  133. /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
  134. k->keepon |= KEEP_WRITE_PAUSE; /* mark socket send as paused */
  135. if(data->req.upload_chunky) {
  136. /* Back out the preallocation done above */
  137. data->req.upload_fromhere -= (8 + 2);
  138. }
  139. *nreadp = 0;
  140. return CURLE_OK; /* nothing was read */
  141. }
  142. else if((size_t)nread > buffersize) {
  143. /* the read function returned a too large value */
  144. *nreadp = 0;
  145. failf(data, "read function returned funny value");
  146. return CURLE_READ_ERROR;
  147. }
  148. if(!data->req.forbidchunk && data->req.upload_chunky) {
  149. /* if chunked Transfer-Encoding */
  150. char hexbuffer[11];
  151. int hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
  152. "%x\r\n", nread);
  153. /* move buffer pointer */
  154. data->req.upload_fromhere -= hexlen;
  155. nread += hexlen;
  156. /* copy the prefix to the buffer, leaving out the NUL */
  157. memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
  158. /* always append CRLF to the data */
  159. memcpy(data->req.upload_fromhere + nread, "\r\n", 2);
  160. if((nread - hexlen) == 0) {
  161. /* mark this as done once this chunk is transfered */
  162. data->req.upload_done = TRUE;
  163. }
  164. nread+=2; /* for the added CRLF */
  165. }
  166. *nreadp = nread;
  167. #ifdef CURL_DOES_CONVERSIONS
  168. if(data->set.prefer_ascii) {
  169. CURLcode res;
  170. res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
  171. /* Curl_convert_to_network calls failf if unsuccessful */
  172. if(res != CURLE_OK) {
  173. return(res);
  174. }
  175. }
  176. #endif /* CURL_DOES_CONVERSIONS */
  177. return CURLE_OK;
  178. }
  179. #ifndef CURL_DISABLE_HTTP
  180. /*
  181. * checkhttpprefix()
  182. *
  183. * Returns TRUE if member of the list matches prefix of string
  184. */
  185. static bool
  186. checkhttpprefix(struct SessionHandle *data,
  187. const char *s)
  188. {
  189. struct curl_slist *head = data->set.http200aliases;
  190. bool rc = FALSE;
  191. #ifdef CURL_DOES_CONVERSIONS
  192. /* convert from the network encoding using a scratch area */
  193. char *scratch = calloc(1, strlen(s)+1);
  194. if(NULL == scratch) {
  195. failf (data, "Failed to calloc memory for conversion!");
  196. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  197. }
  198. strcpy(scratch, s);
  199. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
  200. /* Curl_convert_from_network calls failf if unsuccessful */
  201. free(scratch);
  202. return FALSE; /* can't return CURLE_foobar so return FALSE */
  203. }
  204. s = scratch;
  205. #endif /* CURL_DOES_CONVERSIONS */
  206. while(head) {
  207. if(checkprefix(head->data, s)) {
  208. rc = TRUE;
  209. break;
  210. }
  211. head = head->next;
  212. }
  213. if((rc != TRUE) && (checkprefix("HTTP/", s))) {
  214. rc = TRUE;
  215. }
  216. #ifdef CURL_DOES_CONVERSIONS
  217. free(scratch);
  218. #endif /* CURL_DOES_CONVERSIONS */
  219. return rc;
  220. }
  221. #endif /* CURL_DISABLE_HTTP */
  222. /*
  223. * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
  224. * POST/PUT with multi-pass authentication when a sending was denied and a
  225. * resend is necessary.
  226. */
  227. CURLcode Curl_readrewind(struct connectdata *conn)
  228. {
  229. struct SessionHandle *data = conn->data;
  230. conn->bits.rewindaftersend = FALSE; /* we rewind now */
  231. /* explicitly switch off sending data on this connection now since we are
  232. about to restart a new transfer and thus we want to avoid inadvertently
  233. sending more data on the existing connection until the next transfer
  234. starts */
  235. data->req.keepon &= ~KEEP_WRITE;
  236. /* We have sent away data. If not using CURLOPT_POSTFIELDS or
  237. CURLOPT_HTTPPOST, call app to rewind
  238. */
  239. if(data->set.postfields ||
  240. (data->set.httpreq == HTTPREQ_POST_FORM))
  241. ; /* do nothing */
  242. else {
  243. if(data->set.seek_func) {
  244. int err;
  245. err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
  246. if(err) {
  247. failf(data, "seek callback returned error %d", (int)err);
  248. return CURLE_SEND_FAIL_REWIND;
  249. }
  250. }
  251. else if(data->set.ioctl_func) {
  252. curlioerr err;
  253. err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
  254. data->set.ioctl_client);
  255. infof(data, "the ioctl callback returned %d\n", (int)err);
  256. if(err) {
  257. /* FIXME: convert to a human readable error message */
  258. failf(data, "ioctl callback returned error %d", (int)err);
  259. return CURLE_SEND_FAIL_REWIND;
  260. }
  261. }
  262. else {
  263. /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
  264. given FILE * stream and we can actually attempt to rewind that
  265. ourself with fseek() */
  266. if(data->set.fread_func == (curl_read_callback)fread) {
  267. if(-1 != fseek(data->set.in, 0, SEEK_SET))
  268. /* successful rewind */
  269. return CURLE_OK;
  270. }
  271. /* no callback set or failure above, makes us fail at once */
  272. failf(data, "necessary data rewind wasn't possible");
  273. return CURLE_SEND_FAIL_REWIND;
  274. }
  275. }
  276. return CURLE_OK;
  277. }
  278. static int data_pending(const struct connectdata *conn)
  279. {
  280. /* in the case of libssh2, we can never be really sure that we have emptied
  281. its internal buffers so we MUST always try until we get EAGAIN back */
  282. return conn->protocol&(PROT_SCP|PROT_SFTP) ||
  283. Curl_ssl_data_pending(conn, FIRSTSOCKET);
  284. }
  285. static void read_rewind(struct connectdata *conn,
  286. size_t thismuch)
  287. {
  288. conn->read_pos -= thismuch;
  289. conn->bits.stream_was_rewound = TRUE;
  290. #ifdef CURLDEBUG
  291. {
  292. char buf[512 + 1];
  293. size_t show;
  294. show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
  295. if(conn->master_buffer) {
  296. memcpy(buf, conn->master_buffer + conn->read_pos, show);
  297. buf[show] = '\0';
  298. }
  299. else {
  300. buf[0] = '\0';
  301. }
  302. DEBUGF(infof(conn->data,
  303. "Buffer after stream rewind (read_pos = %d): [%s]",
  304. conn->read_pos, buf));
  305. }
  306. #endif
  307. }
  308. /*
  309. * Go ahead and do a read if we have a readable socket or if
  310. * the stream was rewound (in which case we have data in a
  311. * buffer)
  312. */
  313. static CURLcode readwrite_data(struct SessionHandle *data,
  314. struct connectdata *conn,
  315. struct SingleRequest *k,
  316. int *didwhat, bool *done)
  317. {
  318. CURLcode result = CURLE_OK;
  319. ssize_t nread; /* number of bytes read */
  320. bool is_empty_data = FALSE;
  321. *done = FALSE;
  322. /* This is where we loop until we have read everything there is to
  323. read or we get a EWOULDBLOCK */
  324. do {
  325. size_t buffersize = data->set.buffer_size?
  326. data->set.buffer_size : BUFSIZE;
  327. size_t bytestoread = buffersize;
  328. int readrc;
  329. if(k->size != -1 && !k->header) {
  330. /* make sure we don't read "too much" if we can help it since we
  331. might be pipelining and then someone else might want to read what
  332. follows! */
  333. curl_off_t totalleft = k->size - k->bytecount;
  334. if(totalleft < (curl_off_t)bytestoread)
  335. bytestoread = (size_t)totalleft;
  336. }
  337. if(bytestoread) {
  338. /* receive data from the network! */
  339. readrc = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
  340. /* subzero, this would've blocked */
  341. if(0 > readrc)
  342. break; /* get out of loop */
  343. /* get the CURLcode from the int */
  344. result = (CURLcode)readrc;
  345. if(result>0)
  346. return result;
  347. }
  348. else {
  349. /* read nothing but since we wanted nothing we consider this an OK
  350. situation to proceed from */
  351. nread = 0;
  352. }
  353. if((k->bytecount == 0) && (k->writebytecount == 0)) {
  354. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  355. if(k->exp100 > EXP100_SEND_DATA)
  356. /* set time stamp to compare with when waiting for the 100 */
  357. k->start100 = Curl_tvnow();
  358. }
  359. *didwhat |= KEEP_READ;
  360. /* indicates data of zero size, i.e. empty file */
  361. is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
  362. /* NUL terminate, allowing string ops to be used */
  363. if(0 < nread || is_empty_data) {
  364. k->buf[nread] = 0;
  365. }
  366. else if(0 >= nread) {
  367. /* if we receive 0 or less here, the server closed the connection
  368. and we bail out from this! */
  369. DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
  370. k->keepon &= ~KEEP_READ;
  371. break;
  372. }
  373. /* Default buffer to use when we write the buffer, it may be changed
  374. in the flow below before the actual storing is done. */
  375. k->str = k->buf;
  376. #ifndef CURL_DISABLE_HTTP
  377. /* Since this is a two-state thing, we check if we are parsing
  378. headers at the moment or not. */
  379. if(k->header) {
  380. /* we are in parse-the-header-mode */
  381. bool stop_reading = FALSE;
  382. result = readwrite_http_headers(data, conn, k, &nread, &stop_reading);
  383. if(result)
  384. return result;
  385. if(stop_reading)
  386. /* We've stopped dealing with input, get out of the do-while loop */
  387. break;
  388. }
  389. #endif /* CURL_DISABLE_HTTP */
  390. /* This is not an 'else if' since it may be a rest from the header
  391. parsing, where the beginning of the buffer is headers and the end
  392. is non-headers. */
  393. if(k->str && !k->header && (nread > 0 || is_empty_data)) {
  394. #ifndef CURL_DISABLE_HTTP
  395. if(0 == k->bodywrites && !is_empty_data) {
  396. /* These checks are only made the first time we are about to
  397. write a piece of the body */
  398. if(conn->protocol&PROT_HTTP) {
  399. /* HTTP-only checks */
  400. if(data->req.newurl) {
  401. if(conn->bits.close) {
  402. /* Abort after the headers if "follow Location" is set
  403. and we're set to close anyway. */
  404. k->keepon &= ~KEEP_READ;
  405. *done = TRUE;
  406. return CURLE_OK;
  407. }
  408. /* We have a new url to load, but since we want to be able
  409. to re-use this connection properly, we read the full
  410. response in "ignore more" */
  411. k->ignorebody = TRUE;
  412. infof(data, "Ignoring the response-body\n");
  413. }
  414. if(data->state.resume_from && !k->content_range &&
  415. (data->set.httpreq==HTTPREQ_GET) &&
  416. !k->ignorebody) {
  417. /* we wanted to resume a download, although the server doesn't
  418. * seem to support this and we did this with a GET (if it
  419. * wasn't a GET we did a POST or PUT resume) */
  420. failf(data, "HTTP server doesn't seem to support "
  421. "byte ranges. Cannot resume.");
  422. return CURLE_RANGE_ERROR;
  423. }
  424. if(data->set.timecondition && !data->state.range) {
  425. /* A time condition has been set AND no ranges have been
  426. requested. This seems to be what chapter 13.3.4 of
  427. RFC 2616 defines to be the correct action for a
  428. HTTP/1.1 client */
  429. if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
  430. switch(data->set.timecondition) {
  431. case CURL_TIMECOND_IFMODSINCE:
  432. default:
  433. if(k->timeofdoc < data->set.timevalue) {
  434. infof(data,
  435. "The requested document is not new enough\n");
  436. *done = TRUE;
  437. data->info.timecond = TRUE;
  438. return CURLE_OK;
  439. }
  440. break;
  441. case CURL_TIMECOND_IFUNMODSINCE:
  442. if(k->timeofdoc > data->set.timevalue) {
  443. infof(data,
  444. "The requested document is not old enough\n");
  445. *done = TRUE;
  446. data->info.timecond = TRUE;
  447. return CURLE_OK;
  448. }
  449. break;
  450. } /* switch */
  451. } /* two valid time strings */
  452. } /* we have a time condition */
  453. } /* this is HTTP */
  454. } /* this is the first time we write a body part */
  455. #endif /* CURL_DISABLE_HTTP */
  456. k->bodywrites++;
  457. /* pass data to the debug function before it gets "dechunked" */
  458. if(data->set.verbose) {
  459. if(k->badheader) {
  460. Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
  461. (size_t)k->hbuflen, conn);
  462. if(k->badheader == HEADER_PARTHEADER)
  463. Curl_debug(data, CURLINFO_DATA_IN,
  464. k->str, (size_t)nread, conn);
  465. }
  466. else
  467. Curl_debug(data, CURLINFO_DATA_IN,
  468. k->str, (size_t)nread, conn);
  469. }
  470. #ifndef CURL_DISABLE_HTTP
  471. if(k->chunk) {
  472. /*
  473. * Here comes a chunked transfer flying and we need to decode this
  474. * properly. While the name says read, this function both reads
  475. * and writes away the data. The returned 'nread' holds the number
  476. * of actual data it wrote to the client.
  477. */
  478. CHUNKcode res =
  479. Curl_httpchunk_read(conn, k->str, nread, &nread);
  480. if(CHUNKE_OK < res) {
  481. if(CHUNKE_WRITE_ERROR == res) {
  482. failf(data, "Failed writing data");
  483. return CURLE_WRITE_ERROR;
  484. }
  485. failf(data, "Received problem %d in the chunky parser", res);
  486. return CURLE_RECV_ERROR;
  487. }
  488. else if(CHUNKE_STOP == res) {
  489. size_t dataleft;
  490. /* we're done reading chunks! */
  491. k->keepon &= ~KEEP_READ; /* read no more */
  492. /* There are now possibly N number of bytes at the end of the
  493. str buffer that weren't written to the client.
  494. We DO care about this data if we are pipelining.
  495. Push it back to be read on the next pass. */
  496. dataleft = conn->chunk.dataleft;
  497. if(dataleft != 0) {
  498. infof(conn->data, "Leftovers after chunking. "
  499. " Rewinding %d bytes\n",dataleft);
  500. read_rewind(conn, dataleft);
  501. }
  502. }
  503. /* If it returned OK, we just keep going */
  504. }
  505. #endif /* CURL_DISABLE_HTTP */
  506. if((-1 != k->maxdownload) &&
  507. (k->bytecount + nread >= k->maxdownload)) {
  508. /* The 'excess' amount below can't be more than BUFSIZE which
  509. always will fit in a size_t */
  510. size_t excess = (size_t)(k->bytecount + nread - k->maxdownload);
  511. if(excess > 0 && !k->ignorebody) {
  512. infof(data,
  513. "Rewinding stream by : %d"
  514. " bytes on url %s (size = %" FORMAT_OFF_T
  515. ", maxdownload = %" FORMAT_OFF_T
  516. ", bytecount = %" FORMAT_OFF_T ", nread = %d)\n",
  517. excess, data->state.path,
  518. k->size, k->maxdownload, k->bytecount, nread);
  519. read_rewind(conn, excess);
  520. }
  521. nread = (ssize_t) (k->maxdownload - k->bytecount);
  522. if(nread < 0 ) /* this should be unusual */
  523. nread = 0;
  524. k->keepon &= ~KEEP_READ; /* we're done reading */
  525. }
  526. k->bytecount += nread;
  527. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  528. if(!k->chunk && (nread || k->badheader || is_empty_data)) {
  529. /* If this is chunky transfer, it was already written */
  530. if(k->badheader && !k->ignorebody) {
  531. /* we parsed a piece of data wrongly assuming it was a header
  532. and now we output it as body instead */
  533. result = Curl_client_write(conn, CLIENTWRITE_BODY,
  534. data->state.headerbuff,
  535. k->hbuflen);
  536. if(result)
  537. return result;
  538. }
  539. if(k->badheader < HEADER_ALLBAD) {
  540. /* This switch handles various content encodings. If there's an
  541. error here, be sure to check over the almost identical code
  542. in http_chunks.c.
  543. Make sure that ALL_CONTENT_ENCODINGS contains all the
  544. encodings handled here. */
  545. #ifdef HAVE_LIBZ
  546. switch (conn->data->set.http_ce_skip ?
  547. IDENTITY : k->content_encoding) {
  548. case IDENTITY:
  549. #endif
  550. /* This is the default when the server sends no
  551. Content-Encoding header. See Curl_readwrite_init; the
  552. memset() call initializes k->content_encoding to zero. */
  553. if(!k->ignorebody)
  554. result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
  555. nread);
  556. #ifdef HAVE_LIBZ
  557. break;
  558. case DEFLATE:
  559. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  560. if(!k->ignorebody)
  561. result = Curl_unencode_deflate_write(conn, k, nread);
  562. break;
  563. case GZIP:
  564. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  565. if(!k->ignorebody)
  566. result = Curl_unencode_gzip_write(conn, k, nread);
  567. break;
  568. case COMPRESS:
  569. default:
  570. failf (data, "Unrecognized content encoding type. "
  571. "libcurl understands `identity', `deflate' and `gzip' "
  572. "content encodings.");
  573. result = CURLE_BAD_CONTENT_ENCODING;
  574. break;
  575. }
  576. #endif
  577. }
  578. k->badheader = HEADER_NORMAL; /* taken care of now */
  579. if(result)
  580. return result;
  581. }
  582. } /* if(! header and data to read ) */
  583. if(is_empty_data) {
  584. /* if we received nothing, the server closed the connection and we
  585. are done */
  586. k->keepon &= ~KEEP_READ;
  587. }
  588. } while(data_pending(conn));
  589. if(((k->keepon & (KEEP_READ|KEEP_WRITE)) == KEEP_WRITE) &&
  590. conn->bits.close ) {
  591. /* When we've read the entire thing and the close bit is set, the server
  592. may now close the connection. If there's now any kind of sending going
  593. on from our side, we need to stop that immediately. */
  594. infof(data, "we are done reading and this is set to close, stop send\n");
  595. k->keepon &= ~KEEP_WRITE; /* no writing anymore either */
  596. }
  597. return CURLE_OK;
  598. }
  599. #ifndef CURL_DISABLE_HTTP
  600. /*
  601. * Read any HTTP header lines from the server and pass them to the client app.
  602. */
  603. static CURLcode readwrite_http_headers(struct SessionHandle *data,
  604. struct connectdata *conn,
  605. struct SingleRequest *k,
  606. ssize_t *nread,
  607. bool *stop_reading)
  608. {
  609. CURLcode result;
  610. /* header line within buffer loop */
  611. do {
  612. size_t hbufp_index;
  613. size_t rest_length;
  614. size_t full_length;
  615. int writetype;
  616. /* str_start is start of line within buf */
  617. k->str_start = k->str;
  618. /* data is in network encoding so use 0x0a instead of '\n' */
  619. k->end_ptr = memchr(k->str_start, 0x0a, *nread);
  620. if(!k->end_ptr) {
  621. /* Not a complete header line within buffer, append the data to
  622. the end of the headerbuff. */
  623. if(k->hbuflen + *nread >= data->state.headersize) {
  624. /* We enlarge the header buffer as it is too small */
  625. char *newbuff;
  626. size_t newsize=CURLMAX((k->hbuflen+*nread)*3/2,
  627. data->state.headersize*2);
  628. hbufp_index = k->hbufp - data->state.headerbuff;
  629. newbuff = realloc(data->state.headerbuff, newsize);
  630. if(!newbuff) {
  631. failf (data, "Failed to alloc memory for big header!");
  632. return CURLE_OUT_OF_MEMORY;
  633. }
  634. data->state.headersize=newsize;
  635. data->state.headerbuff = newbuff;
  636. k->hbufp = data->state.headerbuff + hbufp_index;
  637. }
  638. memcpy(k->hbufp, k->str, *nread);
  639. k->hbufp += *nread;
  640. k->hbuflen += *nread;
  641. if(!k->headerline && (k->hbuflen>5)) {
  642. /* make a first check that this looks like a HTTP header */
  643. if(!checkhttpprefix(data, data->state.headerbuff)) {
  644. /* this is not the beginning of a HTTP first header line */
  645. k->header = FALSE;
  646. k->badheader = HEADER_ALLBAD;
  647. break;
  648. }
  649. }
  650. break; /* read more and try again */
  651. }
  652. /* decrease the size of the remaining (supposed) header line */
  653. rest_length = (k->end_ptr - k->str)+1;
  654. *nread -= (ssize_t)rest_length;
  655. k->str = k->end_ptr + 1; /* move past new line */
  656. full_length = k->str - k->str_start;
  657. /*
  658. * We're about to copy a chunk of data to the end of the
  659. * already received header. We make sure that the full string
  660. * fit in the allocated header buffer, or else we enlarge
  661. * it.
  662. */
  663. if(k->hbuflen + full_length >=
  664. data->state.headersize) {
  665. char *newbuff;
  666. size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
  667. data->state.headersize*2);
  668. hbufp_index = k->hbufp - data->state.headerbuff;
  669. newbuff = realloc(data->state.headerbuff, newsize);
  670. if(!newbuff) {
  671. failf (data, "Failed to alloc memory for big header!");
  672. return CURLE_OUT_OF_MEMORY;
  673. }
  674. data->state.headersize= newsize;
  675. data->state.headerbuff = newbuff;
  676. k->hbufp = data->state.headerbuff + hbufp_index;
  677. }
  678. /* copy to end of line */
  679. memcpy(k->hbufp, k->str_start, full_length);
  680. k->hbufp += full_length;
  681. k->hbuflen += full_length;
  682. *k->hbufp = 0;
  683. k->end_ptr = k->hbufp;
  684. k->p = data->state.headerbuff;
  685. /****
  686. * We now have a FULL header line that p points to
  687. *****/
  688. if(!k->headerline) {
  689. /* the first read header */
  690. if((k->hbuflen>5) &&
  691. !checkhttpprefix(data, data->state.headerbuff)) {
  692. /* this is not the beginning of a HTTP first header line */
  693. k->header = FALSE;
  694. if(*nread)
  695. /* since there's more, this is a partial bad header */
  696. k->badheader = HEADER_PARTHEADER;
  697. else {
  698. /* this was all we read so it's all a bad header */
  699. k->badheader = HEADER_ALLBAD;
  700. *nread = (ssize_t)rest_length;
  701. }
  702. break;
  703. }
  704. }
  705. /* headers are in network encoding so
  706. use 0x0a and 0x0d instead of '\n' and '\r' */
  707. if((0x0a == *k->p) || (0x0d == *k->p)) {
  708. size_t headerlen;
  709. /* Zero-length header line means end of headers! */
  710. #ifdef CURL_DOES_CONVERSIONS
  711. if(0x0d == *k->p) {
  712. *k->p = '\r'; /* replace with CR in host encoding */
  713. k->p++; /* pass the CR byte */
  714. }
  715. if(0x0a == *k->p) {
  716. *k->p = '\n'; /* replace with LF in host encoding */
  717. k->p++; /* pass the LF byte */
  718. }
  719. #else
  720. if('\r' == *k->p)
  721. k->p++; /* pass the \r byte */
  722. if('\n' == *k->p)
  723. k->p++; /* pass the \n byte */
  724. #endif /* CURL_DOES_CONVERSIONS */
  725. if(100 <= k->httpcode && 199 >= k->httpcode) {
  726. /*
  727. * We have made a HTTP PUT or POST and this is 1.1-lingo
  728. * that tells us that the server is OK with this and ready
  729. * to receive the data.
  730. * However, we'll get more headers now so we must get
  731. * back into the header-parsing state!
  732. */
  733. k->header = TRUE;
  734. k->headerline = 0; /* restart the header line counter */
  735. /* if we did wait for this do enable write now! */
  736. if(k->exp100) {
  737. k->exp100 = EXP100_SEND_DATA;
  738. k->keepon |= KEEP_WRITE;
  739. }
  740. }
  741. else {
  742. k->header = FALSE; /* no more header to parse! */
  743. if((k->size == -1) && !k->chunk && !conn->bits.close &&
  744. (conn->httpversion >= 11) ) {
  745. /* On HTTP 1.1, when connection is not to get closed, but no
  746. Content-Length nor Content-Encoding chunked have been
  747. received, according to RFC2616 section 4.4 point 5, we
  748. assume that the server will close the connection to
  749. signal the end of the document. */
  750. infof(data, "no chunk, no close, no size. Assume close to "
  751. "signal end\n");
  752. conn->bits.close = TRUE;
  753. }
  754. }
  755. if(417 == k->httpcode) {
  756. /*
  757. * we got: "417 Expectation Failed" this means:
  758. * we have made a HTTP call and our Expect Header
  759. * seems to cause a problem => abort the write operations
  760. * (or prevent them from starting).
  761. */
  762. k->exp100 = EXP100_FAILED;
  763. k->keepon &= ~KEEP_WRITE;
  764. }
  765. /*
  766. * When all the headers have been parsed, see if we should give
  767. * up and return an error.
  768. */
  769. if(Curl_http_should_fail(conn)) {
  770. failf (data, "The requested URL returned error: %d",
  771. k->httpcode);
  772. return CURLE_HTTP_RETURNED_ERROR;
  773. }
  774. /* now, only output this if the header AND body are requested:
  775. */
  776. writetype = CLIENTWRITE_HEADER;
  777. if(data->set.include_header)
  778. writetype |= CLIENTWRITE_BODY;
  779. headerlen = k->p - data->state.headerbuff;
  780. result = Curl_client_write(conn, writetype,
  781. data->state.headerbuff,
  782. headerlen);
  783. if(result)
  784. return result;
  785. data->info.header_size += (long)headerlen;
  786. data->req.headerbytecount += (long)headerlen;
  787. data->req.deductheadercount =
  788. (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
  789. if(data->state.resume_from &&
  790. (data->set.httpreq==HTTPREQ_GET) &&
  791. (k->httpcode == 416)) {
  792. /* "Requested Range Not Satisfiable" */
  793. *stop_reading = TRUE;
  794. }
  795. if(!*stop_reading) {
  796. /* Curl_http_auth_act() checks what authentication methods
  797. * that are available and decides which one (if any) to
  798. * use. It will set 'newurl' if an auth method was picked. */
  799. result = Curl_http_auth_act(conn);
  800. if(result)
  801. return result;
  802. if(conn->bits.rewindaftersend) {
  803. /* We rewind after a complete send, so thus we continue
  804. sending now */
  805. infof(data, "Keep sending data to get tossed away!\n");
  806. k->keepon |= KEEP_WRITE;
  807. }
  808. }
  809. if(!k->header) {
  810. /*
  811. * really end-of-headers.
  812. *
  813. * If we requested a "no body", this is a good time to get
  814. * out and return home.
  815. */
  816. if(data->set.opt_no_body)
  817. *stop_reading = TRUE;
  818. else {
  819. /* If we know the expected size of this document, we set the
  820. maximum download size to the size of the expected
  821. document or else, we won't know when to stop reading!
  822. Note that we set the download maximum even if we read a
  823. "Connection: close" header, to make sure that
  824. "Content-Length: 0" still prevents us from attempting to
  825. read the (missing) response-body.
  826. */
  827. /* According to RFC2616 section 4.4, we MUST ignore
  828. Content-Length: headers if we are now receiving data
  829. using chunked Transfer-Encoding.
  830. */
  831. if(k->chunk)
  832. k->size=-1;
  833. }
  834. if(-1 != k->size) {
  835. /* We do this operation even if no_body is true, since this
  836. data might be retrieved later with curl_easy_getinfo()
  837. and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
  838. Curl_pgrsSetDownloadSize(data, k->size);
  839. k->maxdownload = k->size;
  840. }
  841. /* If max download size is *zero* (nothing) we already
  842. have nothing and can safely return ok now! */
  843. if(0 == k->maxdownload)
  844. *stop_reading = TRUE;
  845. if(*stop_reading) {
  846. /* we make sure that this socket isn't read more now */
  847. k->keepon &= ~KEEP_READ;
  848. }
  849. if(data->set.verbose)
  850. Curl_debug(data, CURLINFO_HEADER_IN,
  851. k->str_start, headerlen, conn);
  852. break; /* exit header line loop */
  853. }
  854. /* We continue reading headers, so reset the line-based
  855. header parsing variables hbufp && hbuflen */
  856. k->hbufp = data->state.headerbuff;
  857. k->hbuflen = 0;
  858. continue;
  859. }
  860. /*
  861. * Checks for special headers coming up.
  862. */
  863. if(!k->headerline++) {
  864. /* This is the first header, it MUST be the error code line
  865. or else we consider this to be the body right away! */
  866. int httpversion_major;
  867. int nc;
  868. #ifdef CURL_DOES_CONVERSIONS
  869. #define HEADER1 scratch
  870. #define SCRATCHSIZE 21
  871. CURLcode res;
  872. char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
  873. /* We can't really convert this yet because we
  874. don't know if it's the 1st header line or the body.
  875. So we do a partial conversion into a scratch area,
  876. leaving the data at k->p as-is.
  877. */
  878. strncpy(&scratch[0], k->p, SCRATCHSIZE);
  879. scratch[SCRATCHSIZE] = 0; /* null terminate */
  880. res = Curl_convert_from_network(data,
  881. &scratch[0],
  882. SCRATCHSIZE);
  883. if(CURLE_OK != res) {
  884. /* Curl_convert_from_network calls failf if unsuccessful */
  885. return res;
  886. }
  887. #else
  888. #define HEADER1 k->p /* no conversion needed, just use k->p */
  889. #endif /* CURL_DOES_CONVERSIONS */
  890. nc = sscanf(HEADER1,
  891. " HTTP/%d.%d %3d",
  892. &httpversion_major,
  893. &conn->httpversion,
  894. &k->httpcode);
  895. if(nc==3) {
  896. conn->httpversion += 10 * httpversion_major;
  897. }
  898. else {
  899. /* this is the real world, not a Nirvana
  900. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  901. */
  902. nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
  903. conn->httpversion = 10;
  904. /* If user has set option HTTP200ALIASES,
  905. compare header line against list of aliases
  906. */
  907. if(!nc) {
  908. if(checkhttpprefix(data, k->p)) {
  909. nc = 1;
  910. k->httpcode = 200;
  911. conn->httpversion = 10;
  912. }
  913. }
  914. }
  915. if(nc) {
  916. data->info.httpcode = k->httpcode;
  917. data->info.httpversion = conn->httpversion;
  918. if (!data->state.httpversion ||
  919. data->state.httpversion > conn->httpversion)
  920. /* store the lowest server version we encounter */
  921. data->state.httpversion = conn->httpversion;
  922. /*
  923. * This code executes as part of processing the header. As a
  924. * result, it's not totally clear how to interpret the
  925. * response code yet as that depends on what other headers may
  926. * be present. 401 and 407 may be errors, but may be OK
  927. * depending on how authentication is working. Other codes
  928. * are definitely errors, so give up here.
  929. */
  930. if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
  931. ((k->httpcode != 401) || !conn->bits.user_passwd) &&
  932. ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
  933. if(data->state.resume_from &&
  934. (data->set.httpreq==HTTPREQ_GET) &&
  935. (k->httpcode == 416)) {
  936. /* "Requested Range Not Satisfiable", just proceed and
  937. pretend this is no error */
  938. }
  939. else {
  940. /* serious error, go home! */
  941. failf (data, "The requested URL returned error: %d",
  942. k->httpcode);
  943. return CURLE_HTTP_RETURNED_ERROR;
  944. }
  945. }
  946. if(conn->httpversion == 10) {
  947. /* Default action for HTTP/1.0 must be to close, unless
  948. we get one of those fancy headers that tell us the
  949. server keeps it open for us! */
  950. infof(data, "HTTP 1.0, assume close after body\n");
  951. conn->bits.close = TRUE;
  952. }
  953. else if(conn->httpversion >= 11 &&
  954. !conn->bits.close) {
  955. /* If HTTP version is >= 1.1 and connection is persistent
  956. server supports pipelining. */
  957. DEBUGF(infof(data,
  958. "HTTP 1.1 or later with persistent connection, "
  959. "pipelining supported\n"));
  960. conn->server_supports_pipelining = TRUE;
  961. }
  962. switch(k->httpcode) {
  963. case 204:
  964. /* (quote from RFC2616, section 10.2.5): The server has
  965. * fulfilled the request but does not need to return an
  966. * entity-body ... The 204 response MUST NOT include a
  967. * message-body, and thus is always terminated by the first
  968. * empty line after the header fields. */
  969. /* FALLTHROUGH */
  970. case 416: /* Requested Range Not Satisfiable, it has the
  971. Content-Length: set as the "real" document but no
  972. actual response is sent. */
  973. case 304:
  974. /* (quote from RFC2616, section 10.3.5): The 304 response
  975. * MUST NOT contain a message-body, and thus is always
  976. * terminated by the first empty line after the header
  977. * fields. */
  978. if(data->set.timecondition)
  979. data->info.timecond = TRUE;
  980. k->size=0;
  981. k->maxdownload=0;
  982. k->ignorecl = TRUE; /* ignore Content-Length headers */
  983. break;
  984. default:
  985. /* nothing */
  986. break;
  987. }
  988. }
  989. else {
  990. k->header = FALSE; /* this is not a header line */
  991. break;
  992. }
  993. }
  994. #ifdef CURL_DOES_CONVERSIONS
  995. /* convert from the network encoding */
  996. result = Curl_convert_from_network(data, k->p, strlen(k->p));
  997. if(CURLE_OK != result) {
  998. return(result);
  999. }
  1000. /* Curl_convert_from_network calls failf if unsuccessful */
  1001. #endif /* CURL_DOES_CONVERSIONS */
  1002. /* Check for Content-Length: header lines to get size. Ignore
  1003. the header completely if we get a 416 response as then we're
  1004. resuming a document that we don't get, and this header contains
  1005. info about the true size of the document we didn't get now. */
  1006. if(!k->ignorecl && !data->set.ignorecl &&
  1007. checkprefix("Content-Length:", k->p)) {
  1008. curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
  1009. if(data->set.max_filesize &&
  1010. contentlength > data->set.max_filesize) {
  1011. failf(data, "Maximum file size exceeded");
  1012. return CURLE_FILESIZE_EXCEEDED;
  1013. }
  1014. if(contentlength >= 0) {
  1015. k->size = contentlength;
  1016. k->maxdownload = k->size;
  1017. /* we set the progress download size already at this point
  1018. just to make it easier for apps/callbacks to extract this
  1019. info as soon as possible */
  1020. Curl_pgrsSetDownloadSize(data, k->size);
  1021. }
  1022. else {
  1023. /* Negative Content-Length is really odd, and we know it
  1024. happens for example when older Apache servers send large
  1025. files */
  1026. conn->bits.close = TRUE;
  1027. infof(data, "Negative content-length: %" FORMAT_OFF_T
  1028. ", closing after transfer\n", contentlength);
  1029. }
  1030. }
  1031. /* check for Content-Type: header lines to get the MIME-type */
  1032. else if(checkprefix("Content-Type:", k->p)) {
  1033. char *contenttype = Curl_copy_header_value(k->p);
  1034. if (!contenttype)
  1035. return CURLE_OUT_OF_MEMORY;
  1036. if (!*contenttype)
  1037. /* ignore empty data */
  1038. free(contenttype);
  1039. else {
  1040. Curl_safefree(data->info.contenttype);
  1041. data->info.contenttype = contenttype;
  1042. }
  1043. }
  1044. else if((conn->httpversion == 10) &&
  1045. conn->bits.httpproxy &&
  1046. Curl_compareheader(k->p,
  1047. "Proxy-Connection:", "keep-alive")) {
  1048. /*
  1049. * When a HTTP/1.0 reply comes when using a proxy, the
  1050. * 'Proxy-Connection: keep-alive' line tells us the
  1051. * connection will be kept alive for our pleasure.
  1052. * Default action for 1.0 is to close.
  1053. */
  1054. conn->bits.close = FALSE; /* don't close when done */
  1055. infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
  1056. }
  1057. else if((conn->httpversion == 11) &&
  1058. conn->bits.httpproxy &&
  1059. Curl_compareheader(k->p,
  1060. "Proxy-Connection:", "close")) {
  1061. /*
  1062. * We get a HTTP/1.1 response from a proxy and it says it'll
  1063. * close down after this transfer.
  1064. */
  1065. conn->bits.close = TRUE; /* close when done */
  1066. infof(data, "HTTP/1.1 proxy connection set close!\n");
  1067. }
  1068. else if((conn->httpversion == 10) &&
  1069. Curl_compareheader(k->p, "Connection:", "keep-alive")) {
  1070. /*
  1071. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  1072. * tells us the connection will be kept alive for our
  1073. * pleasure. Default action for 1.0 is to close.
  1074. *
  1075. * [RFC2068, section 19.7.1] */
  1076. conn->bits.close = FALSE; /* don't close when done */
  1077. infof(data, "HTTP/1.0 connection set to keep alive!\n");
  1078. }
  1079. else if(Curl_compareheader(k->p, "Connection:", "close")) {
  1080. /*
  1081. * [RFC 2616, section 8.1.2.1]
  1082. * "Connection: close" is HTTP/1.1 language and means that
  1083. * the connection will close when this request has been
  1084. * served.
  1085. */
  1086. conn->bits.close = TRUE; /* close when done */
  1087. }
  1088. else if(Curl_compareheader(k->p,
  1089. "Transfer-Encoding:", "chunked")) {
  1090. /*
  1091. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  1092. * means that the server will send a series of "chunks". Each
  1093. * chunk starts with line with info (including size of the
  1094. * coming block) (terminated with CRLF), then a block of data
  1095. * with the previously mentioned size. There can be any amount
  1096. * of chunks, and a chunk-data set to zero signals the
  1097. * end-of-chunks. */
  1098. k->chunk = TRUE; /* chunks coming our way */
  1099. /* init our chunky engine */
  1100. Curl_httpchunk_init(conn);
  1101. }
  1102. else if(checkprefix("Trailer:", k->p) ||
  1103. checkprefix("Trailers:", k->p)) {
  1104. /*
  1105. * This test helps Curl_httpchunk_read() to determine to look
  1106. * for well formed trailers after the zero chunksize record. In
  1107. * this case a CRLF is required after the zero chunksize record
  1108. * when no trailers are sent, or after the last trailer record.
  1109. *
  1110. * It seems both Trailer: and Trailers: occur in the wild.
  1111. */
  1112. k->trailerhdrpresent = TRUE;
  1113. }
  1114. else if(checkprefix("Content-Encoding:", k->p) &&
  1115. data->set.str[STRING_ENCODING]) {
  1116. /*
  1117. * Process Content-Encoding. Look for the values: identity,
  1118. * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
  1119. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  1120. * 2616). zlib cannot handle compress. However, errors are
  1121. * handled further down when the response body is processed
  1122. */
  1123. char *start;
  1124. /* Find the first non-space letter */
  1125. start = k->p + 17;
  1126. while(*start && ISSPACE(*start))
  1127. start++;
  1128. /* Record the content-encoding for later use */
  1129. if(checkprefix("identity", start))
  1130. k->content_encoding = IDENTITY;
  1131. else if(checkprefix("deflate", start))
  1132. k->content_encoding = DEFLATE;
  1133. else if(checkprefix("gzip", start)
  1134. || checkprefix("x-gzip", start))
  1135. k->content_encoding = GZIP;
  1136. else if(checkprefix("compress", start)
  1137. || checkprefix("x-compress", start))
  1138. k->content_encoding = COMPRESS;
  1139. }
  1140. else if(checkprefix("Content-Range:", k->p)) {
  1141. /* Content-Range: bytes [num]-
  1142. Content-Range: bytes: [num]-
  1143. Content-Range: [num]-
  1144. The second format was added since Sun's webserver
  1145. JavaWebServer/1.1.1 obviously sends the header this way!
  1146. The third added since some servers use that!
  1147. */
  1148. char *ptr = k->p + 14;
  1149. /* Move forward until first digit */
  1150. while(*ptr && !ISDIGIT(*ptr))
  1151. ptr++;
  1152. k->offset = curlx_strtoofft(ptr, NULL, 10);
  1153. if(data->state.resume_from == k->offset)
  1154. /* we asked for a resume and we got it */
  1155. k->content_range = TRUE;
  1156. }
  1157. #if !defined(CURL_DISABLE_COOKIES)
  1158. else if(data->cookies &&
  1159. checkprefix("Set-Cookie:", k->p)) {
  1160. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
  1161. CURL_LOCK_ACCESS_SINGLE);
  1162. Curl_cookie_add(data,
  1163. data->cookies, TRUE, k->p+11,
  1164. /* If there is a custom-set Host: name, use it
  1165. here, or else use real peer host name. */
  1166. conn->allocptr.cookiehost?
  1167. conn->allocptr.cookiehost:conn->host.name,
  1168. data->state.path);
  1169. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1170. }
  1171. #endif
  1172. else if(checkprefix("Last-Modified:", k->p) &&
  1173. (data->set.timecondition || data->set.get_filetime) ) {
  1174. time_t secs=time(NULL);
  1175. k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
  1176. &secs);
  1177. if(data->set.get_filetime)
  1178. data->info.filetime = (long)k->timeofdoc;
  1179. }
  1180. else if((checkprefix("WWW-Authenticate:", k->p) &&
  1181. (401 == k->httpcode)) ||
  1182. (checkprefix("Proxy-authenticate:", k->p) &&
  1183. (407 == k->httpcode))) {
  1184. result = Curl_http_input_auth(conn, k->httpcode, k->p);
  1185. if(result)
  1186. return result;
  1187. }
  1188. else if((k->httpcode >= 300 && k->httpcode < 400) &&
  1189. checkprefix("Location:", k->p)) {
  1190. /* this is the URL that the server advises us to use instead */
  1191. char *location = Curl_copy_header_value(k->p);
  1192. if (!location)
  1193. return CURLE_OUT_OF_MEMORY;
  1194. if (!*location)
  1195. /* ignore empty data */
  1196. free(location);
  1197. else {
  1198. DEBUGASSERT(!data->req.location);
  1199. data->req.location = location;
  1200. if(data->set.http_follow_location) {
  1201. DEBUGASSERT(!data->req.newurl);
  1202. data->req.newurl = strdup(data->req.location); /* clone */
  1203. if(!data->req.newurl)
  1204. return CURLE_OUT_OF_MEMORY;
  1205. /* some cases of POST and PUT etc needs to rewind the data
  1206. stream at this point */
  1207. result = Curl_http_perhapsrewind(conn);
  1208. if(result)
  1209. return result;
  1210. }
  1211. }
  1212. }
  1213. /*
  1214. * End of header-checks. Write them to the client.
  1215. */
  1216. writetype = CLIENTWRITE_HEADER;
  1217. if(data->set.include_header)
  1218. writetype |= CLIENTWRITE_BODY;
  1219. if(data->set.verbose)
  1220. Curl_debug(data, CURLINFO_HEADER_IN,
  1221. k->p, (size_t)k->hbuflen, conn);
  1222. result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
  1223. if(result)
  1224. return result;
  1225. data->info.header_size += (long)k->hbuflen;
  1226. data->req.headerbytecount += (long)k->hbuflen;
  1227. /* reset hbufp pointer && hbuflen */
  1228. k->hbufp = data->state.headerbuff;
  1229. k->hbuflen = 0;
  1230. }
  1231. while(!*stop_reading && *k->str); /* header line within buffer */
  1232. /* We might have reached the end of the header part here, but
  1233. there might be a non-header part left in the end of the read
  1234. buffer. */
  1235. return CURLE_OK;
  1236. }
  1237. #endif /* CURL_DISABLE_HTTP */
  1238. /*
  1239. * Send data to upload to the server, when the socket is writable.
  1240. */
  1241. static CURLcode readwrite_upload(struct SessionHandle *data,
  1242. struct connectdata *conn,
  1243. struct SingleRequest *k,
  1244. int *didwhat)
  1245. {
  1246. ssize_t i, si;
  1247. ssize_t bytes_written;
  1248. CURLcode result;
  1249. ssize_t nread; /* number of bytes read */
  1250. if((k->bytecount == 0) && (k->writebytecount == 0))
  1251. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  1252. *didwhat |= KEEP_WRITE;
  1253. /*
  1254. * We loop here to do the READ and SEND loop until we run out of
  1255. * data to send or until we get EWOULDBLOCK back
  1256. */
  1257. do {
  1258. /* only read more data if there's no upload data already
  1259. present in the upload buffer */
  1260. if(0 == data->req.upload_present) {
  1261. /* init the "upload from here" pointer */
  1262. data->req.upload_fromhere = k->uploadbuf;
  1263. if(!k->upload_done) {
  1264. /* HTTP pollution, this should be written nicer to become more
  1265. protocol agnostic. */
  1266. int fillcount;
  1267. if((k->exp100 == EXP100_SENDING_REQUEST) &&
  1268. (data->state.proto.http->sending == HTTPSEND_BODY)) {
  1269. /* If this call is to send body data, we must take some action:
  1270. We have sent off the full HTTP 1.1 request, and we shall now
  1271. go into the Expect: 100 state and await such a header */
  1272. k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
  1273. k->keepon &= ~KEEP_WRITE; /* disable writing */
  1274. k->start100 = Curl_tvnow(); /* timeout count starts now */
  1275. *didwhat &= ~KEEP_WRITE; /* we didn't write anything actually */
  1276. break;
  1277. }
  1278. result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
  1279. if(result)
  1280. return result;
  1281. nread = (ssize_t)fillcount;
  1282. }
  1283. else
  1284. nread = 0; /* we're done uploading/reading */
  1285. if(!nread && (k->keepon & KEEP_WRITE_PAUSE)) {
  1286. /* this is a paused transfer */
  1287. break;
  1288. }
  1289. else if(nread<=0) {
  1290. /* done */
  1291. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  1292. if(conn->bits.rewindaftersend) {
  1293. result = Curl_readrewind(conn);
  1294. if(result)
  1295. return result;
  1296. }
  1297. break;
  1298. }
  1299. /* store number of bytes available for upload */
  1300. data->req.upload_present = nread;
  1301. /* convert LF to CRLF if so asked */
  1302. #ifdef CURL_DO_LINEEND_CONV
  1303. /* always convert if we're FTPing in ASCII mode */
  1304. if((data->set.crlf) || (data->set.prefer_ascii))
  1305. #else
  1306. if(data->set.crlf)
  1307. #endif /* CURL_DO_LINEEND_CONV */
  1308. {
  1309. if(data->state.scratch == NULL)
  1310. data->state.scratch = malloc(2*BUFSIZE);
  1311. if(data->state.scratch == NULL) {
  1312. failf (data, "Failed to alloc scratch buffer!");
  1313. return CURLE_OUT_OF_MEMORY;
  1314. }
  1315. /*
  1316. * ASCII/EBCDIC Note: This is presumably a text (not binary)
  1317. * transfer so the data should already be in ASCII.
  1318. * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
  1319. * must be used instead of the escape sequences \r & \n.
  1320. */
  1321. for(i = 0, si = 0; i < nread; i++, si++) {
  1322. if(data->req.upload_fromhere[i] == 0x0a) {
  1323. data->state.scratch[si++] = 0x0d;
  1324. data->state.scratch[si] = 0x0a;
  1325. if(!data->set.crlf) {
  1326. /* we're here only because FTP is in ASCII mode...
  1327. bump infilesize for the LF we just added */
  1328. data->set.infilesize++;
  1329. }
  1330. }
  1331. else
  1332. data->state.scratch[si] = data->req.upload_fromhere[i];
  1333. }
  1334. if(si != nread) {
  1335. /* only perform the special operation if we really did replace
  1336. anything */
  1337. nread = si;
  1338. /* upload from the new (replaced) buffer instead */
  1339. data->req.upload_fromhere = data->state.scratch;
  1340. /* set the new amount too */
  1341. data->req.upload_present = nread;
  1342. }
  1343. }
  1344. } /* if 0 == data->req.upload_present */
  1345. else {
  1346. /* We have a partial buffer left from a previous "round". Use
  1347. that instead of reading more data */
  1348. }
  1349. /* write to socket (send away data) */
  1350. result = Curl_write(conn,
  1351. conn->writesockfd, /* socket to send to */
  1352. data->req.upload_fromhere, /* buffer pointer */
  1353. data->req.upload_present, /* buffer size */
  1354. &bytes_written); /* actually send away */
  1355. if(result)
  1356. return result;
  1357. if(data->set.verbose)
  1358. /* show the data before we change the pointer upload_fromhere */
  1359. Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
  1360. (size_t)bytes_written, conn);
  1361. if(data->req.upload_present != bytes_written) {
  1362. /* we only wrote a part of the buffer (if anything), deal with it! */
  1363. /* store the amount of bytes left in the buffer to write */
  1364. data->req.upload_present -= bytes_written;
  1365. /* advance the pointer where to find the buffer when the next send
  1366. is to happen */
  1367. data->req.upload_fromhere += bytes_written;
  1368. }
  1369. else {
  1370. /* we've uploaded that buffer now */
  1371. data->req.upload_fromhere = k->uploadbuf;
  1372. data->req.upload_present = 0; /* no more bytes left */
  1373. if(k->upload_done) {
  1374. /* switch off writing, we're done! */
  1375. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  1376. }
  1377. }
  1378. k->writebytecount += bytes_written;
  1379. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  1380. } while(0); /* just to break out from! */
  1381. return CURLE_OK;
  1382. }
  1383. /*
  1384. * Curl_readwrite() is the low-level function to be called when data is to
  1385. * be read and written to/from the connection.
  1386. */
  1387. CURLcode Curl_readwrite(struct connectdata *conn,
  1388. bool *done)
  1389. {
  1390. struct SessionHandle *data = conn->data;
  1391. struct SingleRequest *k = &data->req;
  1392. CURLcode result;
  1393. int didwhat=0;
  1394. curl_socket_t fd_read;
  1395. curl_socket_t fd_write;
  1396. int select_res = conn->cselect_bits;
  1397. conn->cselect_bits = 0;
  1398. /* only use the proper socket if the *_HOLD bit is not set simultaneously as
  1399. then we are in rate limiting state in that transfer direction */
  1400. if((k->keepon & KEEP_READBITS) == KEEP_READ) {
  1401. fd_read = conn->sockfd;
  1402. #if defined(USE_LIBSSH2)
  1403. if(conn->protocol & (PROT_SCP|PROT_SFTP))
  1404. select_res |= CURL_CSELECT_IN;
  1405. #endif /* USE_LIBSSH2 */
  1406. } else
  1407. fd_read = CURL_SOCKET_BAD;
  1408. if((k->keepon & KEEP_WRITEBITS) == KEEP_WRITE)
  1409. fd_write = conn->writesockfd;
  1410. else
  1411. fd_write = CURL_SOCKET_BAD;
  1412. if(!select_res) { /* Call for select()/poll() only, if read/write/error
  1413. status is not known. */
  1414. select_res = Curl_socket_ready(fd_read, fd_write, 0);
  1415. }
  1416. if(select_res == CURL_CSELECT_ERR) {
  1417. failf(data, "select/poll returned error");
  1418. return CURLE_SEND_ERROR;
  1419. }
  1420. /* We go ahead and do a read if we have a readable socket or if
  1421. the stream was rewound (in which case we have data in a
  1422. buffer) */
  1423. if((k->keepon & KEEP_READ) &&
  1424. ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
  1425. result = readwrite_data(data, conn, k, &didwhat, done);
  1426. if(result || *done)
  1427. return result;
  1428. }
  1429. /* If we still have writing to do, we check if we have a writable socket. */
  1430. if((k->keepon & KEEP_WRITE) && (select_res & CURL_CSELECT_OUT)) {
  1431. /* write */
  1432. result = readwrite_upload(data, conn, k, &didwhat);
  1433. if(result)
  1434. return result;
  1435. }
  1436. k->now = Curl_tvnow();
  1437. if(didwhat) {
  1438. /* Update read/write counters */
  1439. if(k->bytecountp)
  1440. *k->bytecountp = k->bytecount; /* read count */
  1441. if(k->writebytecountp)
  1442. *k->writebytecountp = k->writebytecount; /* write count */
  1443. }
  1444. else {
  1445. /* no read no write, this is a timeout? */
  1446. if(k->exp100 == EXP100_AWAITING_CONTINUE) {
  1447. /* This should allow some time for the header to arrive, but only a
  1448. very short time as otherwise it'll be too much wasted time too
  1449. often. */
  1450. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  1451. Therefore, when a client sends this header field to an origin server
  1452. (possibly via a proxy) from which it has never seen a 100 (Continue)
  1453. status, the client SHOULD NOT wait for an indefinite period before
  1454. sending the request body.
  1455. */
  1456. long ms = Curl_tvdiff(k->now, k->start100);
  1457. if(ms > CURL_TIMEOUT_EXPECT_100) {
  1458. /* we've waited long enough, continue anyway */
  1459. k->exp100 = EXP100_SEND_DATA;
  1460. k->keepon |= KEEP_WRITE;
  1461. infof(data, "Done waiting for 100-continue\n");
  1462. }
  1463. }
  1464. }
  1465. if(Curl_pgrsUpdate(conn))
  1466. result = CURLE_ABORTED_BY_CALLBACK;
  1467. else
  1468. result = Curl_speedcheck(data, k->now);
  1469. if(result)
  1470. return result;
  1471. if(data->set.timeout &&
  1472. (Curl_tvdiff(k->now, k->start) >= data->set.timeout)) {
  1473. if(k->size != -1) {
  1474. failf(data, "Operation timed out after %ld milliseconds with %"
  1475. FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes received",
  1476. data->set.timeout, k->bytecount, k->size);
  1477. } else {
  1478. failf(data, "Operation timed out after %ld milliseconds with %"
  1479. FORMAT_OFF_T " bytes received",
  1480. data->set.timeout, k->bytecount);
  1481. }
  1482. return CURLE_OPERATION_TIMEDOUT;
  1483. }
  1484. if(!k->keepon) {
  1485. /*
  1486. * The transfer has been performed. Just make some general checks before
  1487. * returning.
  1488. */
  1489. if(!(data->set.opt_no_body) && (k->size != -1) &&
  1490. (k->bytecount != k->size) &&
  1491. #ifdef CURL_DO_LINEEND_CONV
  1492. /* Most FTP servers don't adjust their file SIZE response for CRLFs,
  1493. so we'll check to see if the discrepancy can be explained
  1494. by the number of CRLFs we've changed to LFs.
  1495. */
  1496. (k->bytecount != (k->size + data->state.crlf_conversions)) &&
  1497. #endif /* CURL_DO_LINEEND_CONV */
  1498. !data->req.newurl) {
  1499. failf(data, "transfer closed with %" FORMAT_OFF_T
  1500. " bytes remaining to read",
  1501. k->size - k->bytecount);
  1502. return CURLE_PARTIAL_FILE;
  1503. }
  1504. else if(!(data->set.opt_no_body) &&
  1505. k->chunk &&
  1506. (conn->chunk.state != CHUNK_STOP)) {
  1507. /*
  1508. * In chunked mode, return an error if the connection is closed prior to
  1509. * the empty (terminiating) chunk is read.
  1510. *
  1511. * The condition above used to check for
  1512. * conn->proto.http->chunk.datasize != 0 which is true after reading
  1513. * *any* chunk, not just the empty chunk.
  1514. *
  1515. */
  1516. failf(data, "transfer closed with outstanding read data remaining");
  1517. return CURLE_PARTIAL_FILE;
  1518. }
  1519. if(Curl_pgrsUpdate(conn))
  1520. return CURLE_ABORTED_BY_CALLBACK;
  1521. }
  1522. /* Now update the "done" boolean we return */
  1523. *done = (bool)(0 == (k->keepon&(KEEP_READ|KEEP_WRITE|
  1524. KEEP_READ_PAUSE|KEEP_WRITE_PAUSE)));
  1525. return CURLE_OK;
  1526. }
  1527. /*
  1528. * Curl_single_getsock() gets called by the multi interface code when the app
  1529. * has requested to get the sockets for the current connection. This function
  1530. * will then be called once for every connection that the multi interface
  1531. * keeps track of. This function will only be called for connections that are
  1532. * in the proper state to have this information available.
  1533. */
  1534. int Curl_single_getsock(const struct connectdata *conn,
  1535. curl_socket_t *sock, /* points to numsocks number
  1536. of sockets */
  1537. int numsocks)
  1538. {
  1539. const struct SessionHandle *data = conn->data;
  1540. int bitmap = GETSOCK_BLANK;
  1541. unsigned sockindex = 0;
  1542. if(conn->handler->perform_getsock)
  1543. return conn->handler->perform_getsock(conn, sock, numsocks);
  1544. if(numsocks < 2)
  1545. /* simple check but we might need two slots */
  1546. return GETSOCK_BLANK;
  1547. /* don't include HOLD and PAUSE connections */
  1548. if((data->req.keepon & KEEP_READBITS) == KEEP_READ) {
  1549. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1550. bitmap |= GETSOCK_READSOCK(sockindex);
  1551. sock[sockindex] = conn->sockfd;
  1552. }
  1553. /* don't include HOLD and PAUSE connections */
  1554. if((data->req.keepon & KEEP_WRITEBITS) == KEEP_WRITE) {
  1555. if((conn->sockfd != conn->writesockfd) ||
  1556. !(data->req.keepon & KEEP_READ)) {
  1557. /* only if they are not the same socket or we didn't have a readable
  1558. one, we increase index */
  1559. if(data->req.keepon & KEEP_READ)
  1560. sockindex++; /* increase index if we need two entries */
  1561. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1562. sock[sockindex] = conn->writesockfd;
  1563. }
  1564. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1565. }
  1566. return bitmap;
  1567. }
  1568. /*
  1569. * Transfer()
  1570. *
  1571. * This function is what performs the actual transfer. It is capable of
  1572. * doing both ways simultaneously.
  1573. * The transfer must already have been setup by a call to Curl_setup_transfer().
  1574. *
  1575. * Note that headers are created in a preallocated buffer of a default size.
  1576. * That buffer can be enlarged on demand, but it is never shrunken again.
  1577. *
  1578. * Parts of this function was once written by the friendly Mark Butler
  1579. * <butlerm@xmission.com>.
  1580. */
  1581. static CURLcode
  1582. Transfer(struct connectdata *conn)
  1583. {
  1584. CURLcode result;
  1585. struct SessionHandle *data = conn->data;
  1586. struct SingleRequest *k = &data->req;
  1587. bool done=FALSE;
  1588. bool first=TRUE;
  1589. int timeout_ms;
  1590. if((conn->sockfd == CURL_SOCKET_BAD) &&
  1591. (conn->writesockfd == CURL_SOCKET_BAD))
  1592. /* nothing to read, nothing to write, we're already OK! */
  1593. return CURLE_OK;
  1594. /* we want header and/or body, if neither then don't do this! */
  1595. if(!k->getheader && data->set.opt_no_body)
  1596. return CURLE_OK;
  1597. while(!done) {
  1598. curl_socket_t fd_read;
  1599. curl_socket_t fd_write;
  1600. /* limit-rate logic: if speed exceeds threshold, then do not include fd in
  1601. select set. The current speed is recalculated in each Curl_readwrite()
  1602. call */
  1603. if((k->keepon & KEEP_WRITE) &&
  1604. (!data->set.max_send_speed ||
  1605. (data->progress.ulspeed < data->set.max_send_speed) )) {
  1606. fd_write = conn->writesockfd;
  1607. k->keepon &= ~KEEP_WRITE_HOLD;
  1608. }
  1609. else {
  1610. fd_write = CURL_SOCKET_BAD;
  1611. if(k->keepon & KEEP_WRITE)
  1612. k->keepon |= KEEP_WRITE_HOLD; /* hold it */
  1613. }
  1614. if((k->keepon & KEEP_READ) &&
  1615. (!data->set.max_recv_speed ||
  1616. (data->progress.dlspeed < data->set.max_recv_speed)) ) {
  1617. fd_read = conn->sockfd;
  1618. k->keepon &= ~KEEP_READ_HOLD;
  1619. }
  1620. else {
  1621. fd_read = CURL_SOCKET_BAD;
  1622. if(k->keepon & KEEP_READ)
  1623. k->keepon |= KEEP_READ_HOLD; /* hold it */
  1624. }
  1625. /* pause logic. Don't check descriptors for paused connections */
  1626. if(k->keepon & KEEP_READ_PAUSE)
  1627. fd_read = CURL_SOCKET_BAD;
  1628. if(k->keepon & KEEP_WRITE_PAUSE)
  1629. fd_write = CURL_SOCKET_BAD;
  1630. /* The *_HOLD and *_PAUSE logic is necessary since even though there might
  1631. be no traffic during the select interval, we still call
  1632. Curl_readwrite() for the timeout case and if we limit transfer speed we
  1633. must make sure that this function doesn't transfer anything while in
  1634. HOLD status.
  1635. The no timeout for the first round is for the protocols for which data
  1636. has already been slurped off the socket and thus waiting for action
  1637. won't work since it'll wait even though there is already data present
  1638. to work with. */
  1639. if(first &&
  1640. ((fd_read != CURL_SOCKET_BAD) || (fd_write != CURL_SOCKET_BAD)))
  1641. /* if this is the first lap and one of the file descriptors is fine
  1642. to work with, skip the timeout */
  1643. timeout_ms = 0;
  1644. else
  1645. timeout_ms = 1000;
  1646. switch (Curl_socket_ready(fd_read, fd_write, timeout_ms)) {
  1647. case -1: /* select() error, stop reading */
  1648. #ifdef EINTR
  1649. /* The EINTR is not serious, and it seems you might get this more
  1650. often when using the lib in a multi-threaded environment! */
  1651. if(SOCKERRNO == EINTR)
  1652. continue;
  1653. #endif
  1654. return CURLE_RECV_ERROR; /* indicate a network problem */
  1655. case 0: /* timeout */
  1656. default: /* readable descriptors */
  1657. result = Curl_readwrite(conn, &done);
  1658. /* "done" signals to us if the transfer(s) are ready */
  1659. break;
  1660. }
  1661. if(result)
  1662. return result;
  1663. first = FALSE; /* not the first lap anymore */
  1664. }
  1665. return CURLE_OK;
  1666. }
  1667. /*
  1668. * Curl_pretransfer() is called immediately before a transfer starts.
  1669. */
  1670. CURLcode Curl_pretransfer(struct SessionHandle *data)
  1671. {
  1672. CURLcode res;
  1673. if(!data->change.url) {
  1674. /* we can't do anything without URL */
  1675. failf(data, "No URL set!");
  1676. return CURLE_URL_MALFORMAT;
  1677. }
  1678. /* Init the SSL session ID cache here. We do it here since we want to do it
  1679. after the *_setopt() calls (that could change the size of the cache) but
  1680. before any transfer takes place. */
  1681. res = Curl_ssl_initsessions(data, data->set.ssl.numsessions);
  1682. if(res)
  1683. return res;
  1684. data->set.followlocation=0; /* reset the location-follow counter */
  1685. data->state.this_is_a_follow = FALSE; /* reset this */
  1686. data->state.errorbuf = FALSE; /* no error has occurred */
  1687. data->state.httpversion = 0; /* don't assume any particular server version */
  1688. data->state.authproblem = FALSE;
  1689. data->state.authhost.want = data->set.httpauth;
  1690. data->state.authproxy.want = data->set.proxyauth;
  1691. Curl_safefree(data->info.wouldredirect);
  1692. data->info.wouldredirect = NULL;
  1693. /* If there is a list of cookie files to read, do it now! */
  1694. if(data->change.cookielist) {
  1695. Curl_cookie_loadfiles(data);
  1696. }
  1697. /* Allow data->set.use_port to set which port to use. This needs to be
  1698. * disabled for example when we follow Location: headers to URLs using
  1699. * different ports! */
  1700. data->state.allow_port = TRUE;
  1701. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1702. /*************************************************************
  1703. * Tell signal handler to ignore SIGPIPE
  1704. *************************************************************/
  1705. if(!data->set.no_signal)
  1706. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1707. #endif
  1708. Curl_initinfo(data); /* reset session-specific information "variables" */
  1709. Curl_pgrsStartNow(data);
  1710. return CURLE_OK;
  1711. }
  1712. /*
  1713. * Curl_posttransfer() is called immediately after a transfer ends
  1714. */
  1715. CURLcode Curl_posttransfer(struct SessionHandle *data)
  1716. {
  1717. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1718. /* restore the signal handler for SIGPIPE before we get back */
  1719. if(!data->set.no_signal)
  1720. signal(SIGPIPE, data->state.prev_signal);
  1721. #else
  1722. (void)data; /* unused parameter */
  1723. #endif
  1724. if(!(data->progress.flags & PGRS_HIDE) &&
  1725. !data->progress.callback)
  1726. /* only output if we don't use a progress callback and we're not hidden */
  1727. fprintf(data->set.err, "\n");
  1728. return CURLE_OK;
  1729. }
  1730. #ifndef CURL_DISABLE_HTTP
  1731. /*
  1732. * strlen_url() returns the length of the given URL if the spaces within the
  1733. * URL were properly URL encoded.
  1734. */
  1735. static size_t strlen_url(const char *url)
  1736. {
  1737. const char *ptr;
  1738. size_t newlen=0;
  1739. bool left=TRUE; /* left side of the ? */
  1740. for(ptr=url; *ptr; ptr++) {
  1741. switch(*ptr) {
  1742. case '?':
  1743. left=FALSE;
  1744. /* fall through */
  1745. default:
  1746. newlen++;
  1747. break;
  1748. case ' ':
  1749. if(left)
  1750. newlen+=3;
  1751. else
  1752. newlen++;
  1753. break;
  1754. }
  1755. }
  1756. return newlen;
  1757. }
  1758. /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
  1759. * the source URL accordingly.
  1760. */
  1761. static void strcpy_url(char *output, const char *url)
  1762. {
  1763. /* we must add this with whitespace-replacing */
  1764. bool left=TRUE;
  1765. const char *iptr;
  1766. char *optr = output;
  1767. for(iptr = url; /* read from here */
  1768. *iptr; /* until zero byte */
  1769. iptr++) {
  1770. switch(*iptr) {
  1771. case '?':
  1772. left=FALSE;
  1773. /* fall through */
  1774. default:
  1775. *optr++=*iptr;
  1776. break;
  1777. case ' ':
  1778. if(left) {
  1779. *optr++='%'; /* add a '%' */
  1780. *optr++='2'; /* add a '2' */
  1781. *optr++='0'; /* add a '0' */
  1782. }
  1783. else
  1784. *optr++='+'; /* add a '+' here */
  1785. break;
  1786. }
  1787. }
  1788. *optr=0; /* zero terminate output buffer */
  1789. }
  1790. /*
  1791. * Returns true if the given URL is absolute (as opposed to relative)
  1792. */
  1793. static bool is_absolute_url(const char *url)
  1794. {
  1795. char prot[16]; /* URL protocol string storage */
  1796. char letter; /* used for a silly sscanf */
  1797. return (bool)(2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter));
  1798. }
  1799. /*
  1800. * Concatenate a relative URL to a base URL making it absolute.
  1801. * URL-encodes any spaces.
  1802. * The returned pointer must be freed by the caller unless NULL
  1803. * (returns NULL on out of memory).
  1804. */
  1805. static char *concat_url(const char *base, const char *relurl)
  1806. {
  1807. /***
  1808. TRY to append this new path to the old URL
  1809. to the right of the host part. Oh crap, this is doomed to cause
  1810. problems in the future...
  1811. */
  1812. char *newest;
  1813. char *protsep;
  1814. char *pathsep;
  1815. size_t newlen;
  1816. const char *useurl = relurl;
  1817. size_t urllen;
  1818. /* we must make our own copy of the URL to play with, as it may
  1819. point to read-only data */
  1820. char *url_clone=strdup(base);
  1821. if(!url_clone)
  1822. return NULL; /* skip out of this NOW */
  1823. /* protsep points to the start of the host name */
  1824. protsep=strstr(url_clone, "//");
  1825. if(!protsep)
  1826. protsep=url_clone;
  1827. else
  1828. protsep+=2; /* pass the slashes */
  1829. if('/' != relurl[0]) {
  1830. int level=0;
  1831. /* First we need to find out if there's a ?-letter in the URL,
  1832. and cut it and the right-side of that off */
  1833. pathsep = strchr(protsep, '?');
  1834. if(pathsep)
  1835. *pathsep=0;
  1836. /* we have a relative path to append to the last slash if there's one
  1837. available, or if the new URL is just a query string (starts with a
  1838. '?') we append the new one at the end of the entire currently worked
  1839. out URL */
  1840. if(useurl[0] != '?') {
  1841. pathsep = strrchr(protsep, '/');
  1842. if(pathsep)
  1843. *pathsep=0;
  1844. }
  1845. /* Check if there's any slash after the host name, and if so, remember
  1846. that position instead */
  1847. pathsep = strchr(protsep, '/');
  1848. if(pathsep)
  1849. protsep = pathsep+1;
  1850. else
  1851. protsep = NULL;
  1852. /* now deal with one "./" or any amount of "../" in the newurl
  1853. and act accordingly */
  1854. if((useurl[0] == '.') && (useurl[1] == '/'))
  1855. useurl+=2; /* just skip the "./" */
  1856. while((useurl[0] == '.') &&
  1857. (useurl[1] == '.') &&
  1858. (useurl[2] == '/')) {
  1859. level++;
  1860. useurl+=3; /* pass the "../" */
  1861. }
  1862. if(protsep) {
  1863. while(level--) {
  1864. /* cut off one more level from the right of the original URL */
  1865. pathsep = strrchr(protsep, '/');
  1866. if(pathsep)
  1867. *pathsep=0;
  1868. else {
  1869. *protsep=0;
  1870. break;
  1871. }
  1872. }
  1873. }
  1874. }
  1875. else {
  1876. /* We got a new absolute path for this server, cut off from the
  1877. first slash */
  1878. pathsep = strchr(protsep, '/');
  1879. if(pathsep) {
  1880. /* When people use badly formatted URLs, such as
  1881. "http://www.url.com?dir=/home/daniel" we must not use the first
  1882. slash, if there's a ?-letter before it! */
  1883. char *sep = strchr(protsep, '?');
  1884. if(sep && (sep < pathsep))
  1885. pathsep = sep;
  1886. *pathsep=0;
  1887. }
  1888. else {
  1889. /* There was no slash. Now, since we might be operating on a badly
  1890. formatted URL, such as "http://www.url.com?id=2380" which doesn't
  1891. use a slash separator as it is supposed to, we need to check for a
  1892. ?-letter as well! */
  1893. pathsep = strchr(protsep, '?');
  1894. if(pathsep)
  1895. *pathsep=0;
  1896. }
  1897. }
  1898. /* If the new part contains a space, this is a mighty stupid redirect
  1899. but we still make an effort to do "right". To the left of a '?'
  1900. letter we replace each space with %20 while it is replaced with '+'
  1901. on the right side of the '?' letter.
  1902. */
  1903. newlen = strlen_url(useurl);
  1904. urllen = strlen(url_clone);
  1905. newest = malloc( urllen + 1 + /* possible slash */
  1906. newlen + 1 /* zero byte */);
  1907. if(!newest) {
  1908. free(url_clone); /* don't leak this */
  1909. return NULL;
  1910. }
  1911. /* copy over the root url part */
  1912. memcpy(newest, url_clone, urllen);
  1913. /* check if we need to append a slash */
  1914. if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
  1915. ;
  1916. else
  1917. newest[urllen++]='/';
  1918. /* then append the new piece on the right side */
  1919. strcpy_url(&newest[urllen], useurl);
  1920. free(url_clone);
  1921. return newest;
  1922. }
  1923. #endif /* CURL_DISABLE_HTTP */
  1924. /*
  1925. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1926. * as given by the remote server and set up the new URL to request.
  1927. */
  1928. CURLcode Curl_follow(struct SessionHandle *data,
  1929. char *newurl, /* this 'newurl' is the Location: string,
  1930. and it must be malloc()ed before passed
  1931. here */
  1932. followtype type) /* see transfer.h */
  1933. {
  1934. #ifdef CURL_DISABLE_HTTP
  1935. (void)data;
  1936. (void)newurl;
  1937. (void)type;
  1938. /* Location: following will not happen when HTTP is disabled */
  1939. return CURLE_TOO_MANY_REDIRECTS;
  1940. #else
  1941. /* Location: redirect */
  1942. bool disallowport = FALSE;
  1943. if(type == FOLLOW_REDIR) {
  1944. if((data->set.maxredirs != -1) &&
  1945. (data->set.followlocation >= data->set.maxredirs)) {
  1946. failf(data,"Maximum (%d) redirects followed", data->set.maxredirs);
  1947. return CURLE_TOO_MANY_REDIRECTS;
  1948. }
  1949. /* mark the next request as a followed location: */
  1950. data->state.this_is_a_follow = TRUE;
  1951. data->set.followlocation++; /* count location-followers */
  1952. if(data->set.http_auto_referer) {
  1953. /* We are asked to automatically set the previous URL as the referer
  1954. when we get the next URL. We pick the ->url field, which may or may
  1955. not be 100% correct */
  1956. if(data->change.referer_alloc)
  1957. /* If we already have an allocated referer, free this first */
  1958. free(data->change.referer);
  1959. data->change.referer = strdup(data->change.url);
  1960. if (!data->change.referer) {
  1961. data->change.referer_alloc = FALSE;
  1962. return CURLE_OUT_OF_MEMORY;
  1963. }
  1964. data->change.referer_alloc = TRUE; /* yes, free this later */
  1965. }
  1966. }
  1967. if(!is_absolute_url(newurl)) {
  1968. /***
  1969. *DANG* this is an RFC 2068 violation. The URL is supposed
  1970. to be absolute and this doesn't seem to be that!
  1971. */
  1972. char *absolute = concat_url(data->change.url, newurl);
  1973. if (!absolute)
  1974. return CURLE_OUT_OF_MEMORY;
  1975. free(newurl);
  1976. newurl = absolute;
  1977. }
  1978. else {
  1979. /* This is an absolute URL, don't allow the custom port number */
  1980. disallowport = TRUE;
  1981. if(strchr(newurl, ' ')) {
  1982. /* This new URL contains at least one space, this is a mighty stupid
  1983. redirect but we still make an effort to do "right". */
  1984. char *newest;
  1985. size_t newlen = strlen_url(newurl);
  1986. newest = malloc(newlen+1); /* get memory for this */
  1987. if (!newest)
  1988. return CURLE_OUT_OF_MEMORY;
  1989. strcpy_url(newest, newurl); /* create a space-free URL */
  1990. free(newurl); /* that was no good */
  1991. newurl = newest; /* use this instead now */
  1992. }
  1993. }
  1994. if(type == FOLLOW_FAKE) {
  1995. /* we're only figuring out the new url if we would've followed locations
  1996. but now we're done so we can get out! */
  1997. data->info.wouldredirect = newurl;
  1998. return CURLE_OK;
  1999. }
  2000. if(disallowport)
  2001. data->state.allow_port = FALSE;
  2002. if(data->change.url_alloc)
  2003. free(data->change.url);
  2004. else
  2005. data->change.url_alloc = TRUE; /* the URL is allocated */
  2006. data->change.url = newurl;
  2007. newurl = NULL; /* don't free! */
  2008. infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
  2009. /*
  2010. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  2011. * differently based on exactly what return code there was.
  2012. *
  2013. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  2014. * a HTTP (proxy-) authentication scheme other than Basic.
  2015. */
  2016. switch(data->info.httpcode) {
  2017. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  2018. Authorization: XXXX header in the HTTP request code snippet */
  2019. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  2020. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  2021. /* 300 - Multiple Choices */
  2022. /* 306 - Not used */
  2023. /* 307 - Temporary Redirect */
  2024. default: /* for all above (and the unknown ones) */
  2025. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  2026. * seem to be OK to POST to.
  2027. */
  2028. break;
  2029. case 301: /* Moved Permanently */
  2030. /* (quote from RFC2616, section 10.3.2):
  2031. *
  2032. * Note: When automatically redirecting a POST request after receiving a
  2033. * 301 status code, some existing HTTP/1.0 user agents will erroneously
  2034. * change it into a GET request.
  2035. *
  2036. * ----
  2037. *
  2038. * Warning: Because most of importants user agents do this obvious RFC2616
  2039. * violation, many webservers expect this misbehavior. So these servers
  2040. * often answers to a POST request with an error page. To be sure that
  2041. * libcurl gets the page that most user agents would get, libcurl has to
  2042. * force GET.
  2043. *
  2044. * This behaviour can be overridden with CURLOPT_POSTREDIR.
  2045. */
  2046. if( (data->set.httpreq == HTTPREQ_POST
  2047. || data->set.httpreq == HTTPREQ_POST_FORM)
  2048. && !data->set.post301) {
  2049. infof(data,
  2050. "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
  2051. data->set.httpreq = HTTPREQ_GET;
  2052. }
  2053. break;
  2054. case 302: /* Found */
  2055. /* (From 10.3.3)
  2056. Note: RFC 1945 and RFC 2068 specify that the client is not allowed
  2057. to change the method on the redirected request. However, most
  2058. existing user agent implementations treat 302 as if it were a 303
  2059. response, performing a GET on the Location field-value regardless
  2060. of the original request method. The status codes 303 and 307 have
  2061. been added for servers that wish to make unambiguously clear which
  2062. kind of reaction is expected of the client.
  2063. (From 10.3.4)
  2064. Note: Many pre-HTTP/1.1 user agents do not understand the 303
  2065. status. When interoperability with such clients is a concern, the
  2066. 302 status code may be used instead, since most user agents react
  2067. to a 302 response as described here for 303.
  2068. This behaviour can be overriden with CURLOPT_POSTREDIR
  2069. */
  2070. if( (data->set.httpreq == HTTPREQ_POST
  2071. || data->set.httpreq == HTTPREQ_POST_FORM)
  2072. && !data->set.post302) {
  2073. infof(data,
  2074. "Violate RFC 2616/10.3.3 and switch from POST to GET\n");
  2075. data->set.httpreq = HTTPREQ_GET;
  2076. }
  2077. break;
  2078. case 303: /* See Other */
  2079. /* Disable both types of POSTs, since doing a second POST when
  2080. * following isn't what anyone would want! */
  2081. if(data->set.httpreq != HTTPREQ_GET) {
  2082. data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
  2083. infof(data, "Disables POST, goes with %s\n",
  2084. data->set.opt_no_body?"HEAD":"GET");
  2085. }
  2086. break;
  2087. case 304: /* Not Modified */
  2088. /* 304 means we did a conditional request and it was "Not modified".
  2089. * We shouldn't get any Location: header in this response!
  2090. */
  2091. break;
  2092. case 305: /* Use Proxy */
  2093. /* (quote from RFC2616, section 10.3.6):
  2094. * "The requested resource MUST be accessed through the proxy given
  2095. * by the Location field. The Location field gives the URI of the
  2096. * proxy. The recipient is expected to repeat this single request
  2097. * via the proxy. 305 responses MUST only be generated by origin
  2098. * servers."
  2099. */
  2100. break;
  2101. }
  2102. Curl_pgrsTime(data, TIMER_REDIRECT);
  2103. Curl_pgrsResetTimes(data);
  2104. return CURLE_OK;
  2105. #endif /* CURL_DISABLE_HTTP */
  2106. }
  2107. static CURLcode
  2108. connect_host(struct SessionHandle *data,
  2109. struct connectdata **conn)
  2110. {
  2111. CURLcode res = CURLE_OK;
  2112. bool async;
  2113. bool protocol_done=TRUE; /* will be TRUE always since this is only used
  2114. within the easy interface */
  2115. Curl_pgrsTime(data, TIMER_STARTSINGLE);
  2116. res = Curl_connect(data, conn, &async, &protocol_done);
  2117. if((CURLE_OK == res) && async) {
  2118. /* Now, if async is TRUE here, we need to wait for the name
  2119. to resolve */
  2120. res = Curl_wait_for_resolv(*conn, NULL);
  2121. if(CURLE_OK == res)
  2122. /* Resolved, continue with the connection */
  2123. res = Curl_async_resolved(*conn, &protocol_done);
  2124. else
  2125. /* if we can't resolve, we kill this "connection" now */
  2126. (void)Curl_disconnect(*conn);
  2127. }
  2128. return res;
  2129. }
  2130. /* Returns TRUE and sets '*url' if a request retry is wanted.
  2131. NOTE: that the *url is malloc()ed. */
  2132. bool Curl_retry_request(struct connectdata *conn,
  2133. char **url)
  2134. {
  2135. bool retry = FALSE;
  2136. struct SessionHandle *data = conn->data;
  2137. /* if we're talking upload, we can't do the checks below, unless the protocol
  2138. is HTTP as when uploading over HTTP we will still get a response */
  2139. if(data->set.upload && !(conn->protocol&PROT_HTTP))
  2140. return retry;
  2141. if((data->req.bytecount +
  2142. data->req.headerbytecount == 0) &&
  2143. conn->bits.reuse &&
  2144. !data->set.opt_no_body) {
  2145. /* We got no data, we attempted to re-use a connection and yet we want a
  2146. "body". This might happen if the connection was left alive when we were
  2147. done using it before, but that was closed when we wanted to read from
  2148. it again. Bad luck. Retry the same request on a fresh connect! */
  2149. infof(conn->data, "Connection died, retrying a fresh connect\n");
  2150. *url = strdup(conn->data->change.url);
  2151. conn->bits.close = TRUE; /* close this connection */
  2152. conn->bits.retry = TRUE; /* mark this as a connection we're about
  2153. to retry. Marking it this way should
  2154. prevent i.e HTTP transfers to return
  2155. error just because nothing has been
  2156. transfered! */
  2157. retry = TRUE;
  2158. }
  2159. return retry;
  2160. }
  2161. /*
  2162. * Curl_perform() is the internal high-level function that gets called by the
  2163. * external curl_easy_perform() function. It inits, performs and cleans up a
  2164. * single file transfer.
  2165. */
  2166. CURLcode Curl_perform(struct SessionHandle *data)
  2167. {
  2168. CURLcode res;
  2169. CURLcode res2;
  2170. struct connectdata *conn=NULL;
  2171. char *newurl = NULL; /* possibly a new URL to follow to! */
  2172. followtype follow = FOLLOW_NONE;
  2173. data->state.used_interface = Curl_if_easy;
  2174. res = Curl_pretransfer(data);
  2175. if(res)
  2176. return res;
  2177. /*
  2178. * It is important that there is NO 'return' from this function at any other
  2179. * place than falling down to the end of the function! This is because we
  2180. * have cleanup stuff that must be done before we get back, and that is only
  2181. * performed after this do-while loop.
  2182. */
  2183. do {
  2184. res = connect_host(data, &conn); /* primary connection */
  2185. if(res == CURLE_OK) {
  2186. bool do_done;
  2187. if(data->set.connect_only) {
  2188. /* keep connection open for application to use the socket */
  2189. conn->bits.close = FALSE;
  2190. res = Curl_done(&conn, CURLE_OK, FALSE);
  2191. break;
  2192. }
  2193. res = Curl_do(&conn, &do_done);
  2194. if(res == CURLE_OK) {
  2195. res = Transfer(conn); /* now fetch that URL please */
  2196. if((res == CURLE_OK) || (res == CURLE_RECV_ERROR)) {
  2197. bool retry = Curl_retry_request(conn, &newurl);
  2198. if(retry) {
  2199. res = CURLE_OK;
  2200. follow = FOLLOW_RETRY;
  2201. if (!newurl)
  2202. res = CURLE_OUT_OF_MEMORY;
  2203. }
  2204. else if (res == CURLE_OK) {
  2205. /*
  2206. * We must duplicate the new URL here as the connection data may
  2207. * be free()ed in the Curl_done() function. We prefer the newurl
  2208. * one since that's used for redirects or just further requests
  2209. * for retries or multi-stage HTTP auth methods etc.
  2210. */
  2211. if(data->req.newurl) {
  2212. follow = FOLLOW_REDIR;
  2213. newurl = strdup(data->req.newurl);
  2214. if (!newurl)
  2215. res = CURLE_OUT_OF_MEMORY;
  2216. }
  2217. else if(data->req.location) {
  2218. follow = FOLLOW_FAKE;
  2219. newurl = strdup(data->req.location);
  2220. if (!newurl)
  2221. res = CURLE_OUT_OF_MEMORY;
  2222. }
  2223. }
  2224. /* in the above cases where 'newurl' gets assigned, we have a fresh
  2225. * allocated memory pointed to */
  2226. }
  2227. if(res != CURLE_OK) {
  2228. /* The transfer phase returned error, we mark the connection to get
  2229. * closed to prevent being re-used. This is because we can't
  2230. * possibly know if the connection is in a good shape or not now. */
  2231. conn->bits.close = TRUE;
  2232. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
  2233. /* if we failed anywhere, we must clean up the secondary socket if
  2234. it was used */
  2235. sclose(conn->sock[SECONDARYSOCKET]);
  2236. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
  2237. }
  2238. }
  2239. /* Always run Curl_done(), even if some of the previous calls
  2240. failed, but return the previous (original) error code */
  2241. res2 = Curl_done(&conn, res, FALSE);
  2242. if(CURLE_OK == res)
  2243. res = res2;
  2244. }
  2245. else if(conn)
  2246. /* Curl_do() failed, clean up left-overs in the done-call, but note
  2247. that at some cases the conn pointer is NULL when Curl_do() failed
  2248. and the connection cache is very small so only call Curl_done() if
  2249. conn is still "alive".
  2250. */
  2251. res2 = Curl_done(&conn, res, FALSE);
  2252. /*
  2253. * Important: 'conn' cannot be used here, since it may have been closed
  2254. * in 'Curl_done' or other functions.
  2255. */
  2256. if((res == CURLE_OK) && follow) {
  2257. res = Curl_follow(data, newurl, follow);
  2258. if(CURLE_OK == res) {
  2259. /* if things went fine, Curl_follow() freed or otherwise took
  2260. responsibility for the newurl pointer */
  2261. newurl = NULL;
  2262. if(follow >= FOLLOW_RETRY) {
  2263. follow = FOLLOW_NONE;
  2264. continue;
  2265. }
  2266. /* else we break out of the loop below */
  2267. }
  2268. }
  2269. }
  2270. break; /* it only reaches here when this shouldn't loop */
  2271. } while(1); /* loop if Location: */
  2272. if(newurl)
  2273. free(newurl);
  2274. if(res && !data->state.errorbuf) {
  2275. /*
  2276. * As an extra precaution: if no error string has been set and there was
  2277. * an error, use the strerror() string or if things are so bad that not
  2278. * even that is good, set a bad string that mentions the error code.
  2279. */
  2280. const char *str = curl_easy_strerror(res);
  2281. if(!str)
  2282. failf(data, "unspecified error %d", (int)res);
  2283. else
  2284. failf(data, "%s", str);
  2285. }
  2286. /* run post-transfer unconditionally, but don't clobber the return code if
  2287. we already have an error code recorder */
  2288. res2 = Curl_posttransfer(data);
  2289. if(!res && res2)
  2290. res = res2;
  2291. return res;
  2292. }
  2293. /*
  2294. * Curl_setup_transfer() is called to setup some basic properties for the
  2295. * upcoming transfer.
  2296. */
  2297. CURLcode
  2298. Curl_setup_transfer(
  2299. struct connectdata *conn, /* connection data */
  2300. int sockindex, /* socket index to read from or -1 */
  2301. curl_off_t size, /* -1 if unknown at this point */
  2302. bool getheader, /* TRUE if header parsing is wanted */
  2303. curl_off_t *bytecountp, /* return number of bytes read or NULL */
  2304. int writesockindex, /* socket index to write to, it may very well be
  2305. the same we read from. -1 disables */
  2306. curl_off_t *writecountp /* return number of bytes written or NULL */
  2307. )
  2308. {
  2309. struct SessionHandle *data;
  2310. struct SingleRequest *k;
  2311. DEBUGASSERT(conn != NULL);
  2312. data = conn->data;
  2313. k = &data->req;
  2314. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  2315. /* now copy all input parameters */
  2316. conn->sockfd = sockindex == -1 ?
  2317. CURL_SOCKET_BAD : conn->sock[sockindex];
  2318. conn->writesockfd = writesockindex == -1 ?
  2319. CURL_SOCKET_BAD:conn->sock[writesockindex];
  2320. k->getheader = getheader;
  2321. k->size = size;
  2322. k->bytecountp = bytecountp;
  2323. k->writebytecountp = writecountp;
  2324. /* The code sequence below is placed in this function just because all
  2325. necessary input is not always known in do_complete() as this function may
  2326. be called after that */
  2327. if(!k->getheader) {
  2328. k->header = FALSE;
  2329. if(size > 0)
  2330. Curl_pgrsSetDownloadSize(data, size);
  2331. }
  2332. /* we want header and/or body, if neither then don't do this! */
  2333. if(k->getheader || !data->set.opt_no_body) {
  2334. if(conn->sockfd != CURL_SOCKET_BAD) {
  2335. k->keepon |= KEEP_READ;
  2336. }
  2337. if(conn->writesockfd != CURL_SOCKET_BAD) {
  2338. /* HTTP 1.1 magic:
  2339. Even if we require a 100-return code before uploading data, we might
  2340. need to write data before that since the REQUEST may not have been
  2341. finished sent off just yet.
  2342. Thus, we must check if the request has been sent before we set the
  2343. state info where we wait for the 100-return code
  2344. */
  2345. if((data->state.expect100header) &&
  2346. (data->state.proto.http->sending == HTTPSEND_BODY)) {
  2347. /* wait with write until we either got 100-continue or a timeout */
  2348. k->exp100 = EXP100_AWAITING_CONTINUE;
  2349. k->start100 = k->start;
  2350. }
  2351. else {
  2352. if(data->state.expect100header)
  2353. /* when we've sent off the rest of the headers, we must await a
  2354. 100-continue but first finish sending the request */
  2355. k->exp100 = EXP100_SENDING_REQUEST;
  2356. /* enable the write bit when we're not waiting for continue */
  2357. k->keepon |= KEEP_WRITE;
  2358. }
  2359. } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
  2360. } /* if(k->getheader || !data->set.opt_no_body) */
  2361. return CURLE_OK;
  2362. }