transfer.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #include "strtoofft.h"
  24. #include "strequal.h"
  25. #include "rawstr.h"
  26. #ifdef HAVE_NETINET_IN_H
  27. #include <netinet/in.h>
  28. #endif
  29. #ifdef HAVE_NETDB_H
  30. #include <netdb.h>
  31. #endif
  32. #ifdef HAVE_ARPA_INET_H
  33. #include <arpa/inet.h>
  34. #endif
  35. #ifdef HAVE_NET_IF_H
  36. #include <net/if.h>
  37. #endif
  38. #ifdef HAVE_SYS_IOCTL_H
  39. #include <sys/ioctl.h>
  40. #endif
  41. #ifdef HAVE_SIGNAL_H
  42. #include <signal.h>
  43. #endif
  44. #ifdef HAVE_SYS_PARAM_H
  45. #include <sys/param.h>
  46. #endif
  47. #ifdef HAVE_SYS_SELECT_H
  48. #include <sys/select.h>
  49. #endif
  50. #ifndef HAVE_SOCKET
  51. #error "We can't compile without socket() support!"
  52. #endif
  53. #include "urldata.h"
  54. #include <curl/curl.h>
  55. #include "netrc.h"
  56. #include "content_encoding.h"
  57. #include "hostip.h"
  58. #include "transfer.h"
  59. #include "sendf.h"
  60. #include "speedcheck.h"
  61. #include "progress.h"
  62. #include "http.h"
  63. #include "url.h"
  64. #include "getinfo.h"
  65. #include "vtls/vtls.h"
  66. #include "http_digest.h"
  67. #include "curl_ntlm.h"
  68. #include "http_negotiate.h"
  69. #include "share.h"
  70. #include "curl_memory.h"
  71. #include "select.h"
  72. #include "multiif.h"
  73. #include "connect.h"
  74. #include "non-ascii.h"
  75. #define _MPRINTF_REPLACE /* use our functions only */
  76. #include <curl/mprintf.h>
  77. /* The last #include file should be: */
  78. #include "memdebug.h"
  79. #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
  80. /*
  81. * This function will call the read callback to fill our buffer with data
  82. * to upload.
  83. */
  84. CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
  85. {
  86. struct SessionHandle *data = conn->data;
  87. size_t buffersize = (size_t)bytes;
  88. int nread;
  89. #ifdef CURL_DOES_CONVERSIONS
  90. bool sending_http_headers = FALSE;
  91. if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
  92. const struct HTTP *http = data->req.protop;
  93. if(http->sending == HTTPSEND_REQUEST)
  94. /* We're sending the HTTP request headers, not the data.
  95. Remember that so we don't re-translate them into garbage. */
  96. sending_http_headers = TRUE;
  97. }
  98. #endif
  99. if(data->req.upload_chunky) {
  100. /* if chunked Transfer-Encoding */
  101. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  102. data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
  103. }
  104. /* this function returns a size_t, so we typecast to int to prevent warnings
  105. with picky compilers */
  106. nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
  107. buffersize, conn->fread_in);
  108. if(nread == CURL_READFUNC_ABORT) {
  109. failf(data, "operation aborted by callback");
  110. *nreadp = 0;
  111. return CURLE_ABORTED_BY_CALLBACK;
  112. }
  113. else if(nread == CURL_READFUNC_PAUSE) {
  114. if(conn->handler->flags & PROTOPT_NONETWORK) {
  115. /* protocols that work without network cannot be paused. This is
  116. actually only FILE:// just now, and it can't pause since the transfer
  117. isn't done using the "normal" procedure. */
  118. failf(data, "Read callback asked for PAUSE when not supported!");
  119. return CURLE_READ_ERROR;
  120. }
  121. else {
  122. struct SingleRequest *k = &data->req;
  123. /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
  124. k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
  125. if(data->req.upload_chunky) {
  126. /* Back out the preallocation done above */
  127. data->req.upload_fromhere -= (8 + 2);
  128. }
  129. *nreadp = 0;
  130. }
  131. return CURLE_OK; /* nothing was read */
  132. }
  133. else if((size_t)nread > buffersize) {
  134. /* the read function returned a too large value */
  135. *nreadp = 0;
  136. failf(data, "read function returned funny value");
  137. return CURLE_READ_ERROR;
  138. }
  139. if(!data->req.forbidchunk && data->req.upload_chunky) {
  140. /* if chunked Transfer-Encoding
  141. * build chunk:
  142. *
  143. * <HEX SIZE> CRLF
  144. * <DATA> CRLF
  145. */
  146. /* On non-ASCII platforms the <DATA> may or may not be
  147. translated based on set.prefer_ascii while the protocol
  148. portion must always be translated to the network encoding.
  149. To further complicate matters, line end conversion might be
  150. done later on, so we need to prevent CRLFs from becoming
  151. CRCRLFs if that's the case. To do this we use bare LFs
  152. here, knowing they'll become CRLFs later on.
  153. */
  154. char hexbuffer[11];
  155. const char *endofline_native;
  156. const char *endofline_network;
  157. int hexlen;
  158. if(
  159. #ifdef CURL_DO_LINEEND_CONV
  160. (data->set.prefer_ascii) ||
  161. #endif
  162. (data->set.crlf)) {
  163. /* \n will become \r\n later on */
  164. endofline_native = "\n";
  165. endofline_network = "\x0a";
  166. }
  167. else {
  168. endofline_native = "\r\n";
  169. endofline_network = "\x0d\x0a";
  170. }
  171. hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
  172. "%x%s", nread, endofline_native);
  173. /* move buffer pointer */
  174. data->req.upload_fromhere -= hexlen;
  175. nread += hexlen;
  176. /* copy the prefix to the buffer, leaving out the NUL */
  177. memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
  178. /* always append ASCII CRLF to the data */
  179. memcpy(data->req.upload_fromhere + nread,
  180. endofline_network,
  181. strlen(endofline_network));
  182. #ifdef CURL_DOES_CONVERSIONS
  183. CURLcode res;
  184. int length;
  185. if(data->set.prefer_ascii) {
  186. /* translate the protocol and data */
  187. length = nread;
  188. }
  189. else {
  190. /* just translate the protocol portion */
  191. length = strlen(hexbuffer);
  192. }
  193. res = Curl_convert_to_network(data, data->req.upload_fromhere, length);
  194. /* Curl_convert_to_network calls failf if unsuccessful */
  195. if(res)
  196. return(res);
  197. #endif /* CURL_DOES_CONVERSIONS */
  198. if((nread - hexlen) == 0)
  199. /* mark this as done once this chunk is transferred */
  200. data->req.upload_done = TRUE;
  201. nread+=(int)strlen(endofline_native); /* for the added end of line */
  202. }
  203. #ifdef CURL_DOES_CONVERSIONS
  204. else if((data->set.prefer_ascii) && (!sending_http_headers)) {
  205. CURLcode res;
  206. res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
  207. /* Curl_convert_to_network calls failf if unsuccessful */
  208. if(res != CURLE_OK)
  209. return(res);
  210. }
  211. #endif /* CURL_DOES_CONVERSIONS */
  212. *nreadp = nread;
  213. return CURLE_OK;
  214. }
  215. /*
  216. * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
  217. * POST/PUT with multi-pass authentication when a sending was denied and a
  218. * resend is necessary.
  219. */
  220. CURLcode Curl_readrewind(struct connectdata *conn)
  221. {
  222. struct SessionHandle *data = conn->data;
  223. conn->bits.rewindaftersend = FALSE; /* we rewind now */
  224. /* explicitly switch off sending data on this connection now since we are
  225. about to restart a new transfer and thus we want to avoid inadvertently
  226. sending more data on the existing connection until the next transfer
  227. starts */
  228. data->req.keepon &= ~KEEP_SEND;
  229. /* We have sent away data. If not using CURLOPT_POSTFIELDS or
  230. CURLOPT_HTTPPOST, call app to rewind
  231. */
  232. if(data->set.postfields ||
  233. (data->set.httpreq == HTTPREQ_POST_FORM))
  234. ; /* do nothing */
  235. else {
  236. if(data->set.seek_func) {
  237. int err;
  238. err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
  239. if(err) {
  240. failf(data, "seek callback returned error %d", (int)err);
  241. return CURLE_SEND_FAIL_REWIND;
  242. }
  243. }
  244. else if(data->set.ioctl_func) {
  245. curlioerr err;
  246. err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
  247. data->set.ioctl_client);
  248. infof(data, "the ioctl callback returned %d\n", (int)err);
  249. if(err) {
  250. /* FIXME: convert to a human readable error message */
  251. failf(data, "ioctl callback returned error %d", (int)err);
  252. return CURLE_SEND_FAIL_REWIND;
  253. }
  254. }
  255. else {
  256. /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
  257. given FILE * stream and we can actually attempt to rewind that
  258. ourselves with fseek() */
  259. if(data->set.fread_func == (curl_read_callback)fread) {
  260. if(-1 != fseek(data->set.in, 0, SEEK_SET))
  261. /* successful rewind */
  262. return CURLE_OK;
  263. }
  264. /* no callback set or failure above, makes us fail at once */
  265. failf(data, "necessary data rewind wasn't possible");
  266. return CURLE_SEND_FAIL_REWIND;
  267. }
  268. }
  269. return CURLE_OK;
  270. }
  271. static int data_pending(const struct connectdata *conn)
  272. {
  273. /* in the case of libssh2, we can never be really sure that we have emptied
  274. its internal buffers so we MUST always try until we get EAGAIN back */
  275. return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
  276. Curl_ssl_data_pending(conn, FIRSTSOCKET);
  277. }
  278. static void read_rewind(struct connectdata *conn,
  279. size_t thismuch)
  280. {
  281. DEBUGASSERT(conn->read_pos >= thismuch);
  282. conn->read_pos -= thismuch;
  283. conn->bits.stream_was_rewound = TRUE;
  284. #ifdef DEBUGBUILD
  285. {
  286. char buf[512 + 1];
  287. size_t show;
  288. show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
  289. if(conn->master_buffer) {
  290. memcpy(buf, conn->master_buffer + conn->read_pos, show);
  291. buf[show] = '\0';
  292. }
  293. else {
  294. buf[0] = '\0';
  295. }
  296. DEBUGF(infof(conn->data,
  297. "Buffer after stream rewind (read_pos = %zu): [%s]\n",
  298. conn->read_pos, buf));
  299. }
  300. #endif
  301. }
  302. /*
  303. * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
  304. * remote document with the time provided by CURLOPT_TIMEVAL
  305. */
  306. bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc)
  307. {
  308. if((timeofdoc == 0) || (data->set.timevalue == 0))
  309. return TRUE;
  310. switch(data->set.timecondition) {
  311. case CURL_TIMECOND_IFMODSINCE:
  312. default:
  313. if(timeofdoc <= data->set.timevalue) {
  314. infof(data,
  315. "The requested document is not new enough\n");
  316. data->info.timecond = TRUE;
  317. return FALSE;
  318. }
  319. break;
  320. case CURL_TIMECOND_IFUNMODSINCE:
  321. if(timeofdoc >= data->set.timevalue) {
  322. infof(data,
  323. "The requested document is not old enough\n");
  324. data->info.timecond = TRUE;
  325. return FALSE;
  326. }
  327. break;
  328. }
  329. return TRUE;
  330. }
  331. /*
  332. * Go ahead and do a read if we have a readable socket or if
  333. * the stream was rewound (in which case we have data in a
  334. * buffer)
  335. */
  336. static CURLcode readwrite_data(struct SessionHandle *data,
  337. struct connectdata *conn,
  338. struct SingleRequest *k,
  339. int *didwhat, bool *done)
  340. {
  341. CURLcode result = CURLE_OK;
  342. ssize_t nread; /* number of bytes read */
  343. size_t excess = 0; /* excess bytes read */
  344. bool is_empty_data = FALSE;
  345. bool readmore = FALSE; /* used by RTP to signal for more data */
  346. *done = FALSE;
  347. /* This is where we loop until we have read everything there is to
  348. read or we get a CURLE_AGAIN */
  349. do {
  350. size_t buffersize = data->set.buffer_size?
  351. data->set.buffer_size : BUFSIZE;
  352. size_t bytestoread = buffersize;
  353. if(k->size != -1 && !k->header) {
  354. /* make sure we don't read "too much" if we can help it since we
  355. might be pipelining and then someone else might want to read what
  356. follows! */
  357. curl_off_t totalleft = k->size - k->bytecount;
  358. if(totalleft < (curl_off_t)bytestoread)
  359. bytestoread = (size_t)totalleft;
  360. }
  361. if(bytestoread) {
  362. /* receive data from the network! */
  363. result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
  364. /* read would've blocked */
  365. if(CURLE_AGAIN == result)
  366. break; /* get out of loop */
  367. if(result>0)
  368. return result;
  369. }
  370. else {
  371. /* read nothing but since we wanted nothing we consider this an OK
  372. situation to proceed from */
  373. nread = 0;
  374. }
  375. if((k->bytecount == 0) && (k->writebytecount == 0)) {
  376. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  377. if(k->exp100 > EXP100_SEND_DATA)
  378. /* set time stamp to compare with when waiting for the 100 */
  379. k->start100 = Curl_tvnow();
  380. }
  381. *didwhat |= KEEP_RECV;
  382. /* indicates data of zero size, i.e. empty file */
  383. is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
  384. /* NUL terminate, allowing string ops to be used */
  385. if(0 < nread || is_empty_data) {
  386. k->buf[nread] = 0;
  387. }
  388. else if(0 >= nread) {
  389. /* if we receive 0 or less here, the server closed the connection
  390. and we bail out from this! */
  391. DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
  392. k->keepon &= ~KEEP_RECV;
  393. break;
  394. }
  395. /* Default buffer to use when we write the buffer, it may be changed
  396. in the flow below before the actual storing is done. */
  397. k->str = k->buf;
  398. if(conn->handler->readwrite) {
  399. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  400. if(result)
  401. return result;
  402. if(readmore)
  403. break;
  404. }
  405. #ifndef CURL_DISABLE_HTTP
  406. /* Since this is a two-state thing, we check if we are parsing
  407. headers at the moment or not. */
  408. if(k->header) {
  409. /* we are in parse-the-header-mode */
  410. bool stop_reading = FALSE;
  411. result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
  412. if(result)
  413. return result;
  414. if(conn->handler->readwrite &&
  415. (k->maxdownload <= 0 && nread > 0)) {
  416. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  417. if(result)
  418. return result;
  419. if(readmore)
  420. break;
  421. }
  422. if(stop_reading) {
  423. /* We've stopped dealing with input, get out of the do-while loop */
  424. if(nread > 0) {
  425. if(Curl_multi_pipeline_enabled(conn->data->multi)) {
  426. infof(data,
  427. "Rewinding stream by : %zd"
  428. " bytes on url %s (zero-length body)\n",
  429. nread, data->state.path);
  430. read_rewind(conn, (size_t)nread);
  431. }
  432. else {
  433. infof(data,
  434. "Excess found in a non pipelined read:"
  435. " excess = %zd"
  436. " url = %s (zero-length body)\n",
  437. nread, data->state.path);
  438. }
  439. }
  440. break;
  441. }
  442. }
  443. #endif /* CURL_DISABLE_HTTP */
  444. /* This is not an 'else if' since it may be a rest from the header
  445. parsing, where the beginning of the buffer is headers and the end
  446. is non-headers. */
  447. if(k->str && !k->header && (nread > 0 || is_empty_data)) {
  448. #ifndef CURL_DISABLE_HTTP
  449. if(0 == k->bodywrites && !is_empty_data) {
  450. /* These checks are only made the first time we are about to
  451. write a piece of the body */
  452. if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
  453. /* HTTP-only checks */
  454. if(data->req.newurl) {
  455. if(conn->bits.close) {
  456. /* Abort after the headers if "follow Location" is set
  457. and we're set to close anyway. */
  458. k->keepon &= ~KEEP_RECV;
  459. *done = TRUE;
  460. return CURLE_OK;
  461. }
  462. /* We have a new url to load, but since we want to be able
  463. to re-use this connection properly, we read the full
  464. response in "ignore more" */
  465. k->ignorebody = TRUE;
  466. infof(data, "Ignoring the response-body\n");
  467. }
  468. if(data->state.resume_from && !k->content_range &&
  469. (data->set.httpreq==HTTPREQ_GET) &&
  470. !k->ignorebody) {
  471. /* we wanted to resume a download, although the server doesn't
  472. * seem to support this and we did this with a GET (if it
  473. * wasn't a GET we did a POST or PUT resume) */
  474. failf(data, "HTTP server doesn't seem to support "
  475. "byte ranges. Cannot resume.");
  476. return CURLE_RANGE_ERROR;
  477. }
  478. if(data->set.timecondition && !data->state.range) {
  479. /* A time condition has been set AND no ranges have been
  480. requested. This seems to be what chapter 13.3.4 of
  481. RFC 2616 defines to be the correct action for a
  482. HTTP/1.1 client */
  483. if(!Curl_meets_timecondition(data, k->timeofdoc)) {
  484. *done = TRUE;
  485. /* We're simulating a http 304 from server so we return
  486. what should have been returned from the server */
  487. data->info.httpcode = 304;
  488. infof(data, "Simulate a HTTP 304 response!\n");
  489. /* we abort the transfer before it is completed == we ruin the
  490. re-use ability. Close the connection */
  491. conn->bits.close = TRUE;
  492. return CURLE_OK;
  493. }
  494. } /* we have a time condition */
  495. } /* this is HTTP or RTSP */
  496. } /* this is the first time we write a body part */
  497. #endif /* CURL_DISABLE_HTTP */
  498. k->bodywrites++;
  499. /* pass data to the debug function before it gets "dechunked" */
  500. if(data->set.verbose) {
  501. if(k->badheader) {
  502. Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
  503. (size_t)k->hbuflen, conn);
  504. if(k->badheader == HEADER_PARTHEADER)
  505. Curl_debug(data, CURLINFO_DATA_IN,
  506. k->str, (size_t)nread, conn);
  507. }
  508. else
  509. Curl_debug(data, CURLINFO_DATA_IN,
  510. k->str, (size_t)nread, conn);
  511. }
  512. #ifndef CURL_DISABLE_HTTP
  513. if(k->chunk) {
  514. /*
  515. * Here comes a chunked transfer flying and we need to decode this
  516. * properly. While the name says read, this function both reads
  517. * and writes away the data. The returned 'nread' holds the number
  518. * of actual data it wrote to the client.
  519. */
  520. CHUNKcode res =
  521. Curl_httpchunk_read(conn, k->str, nread, &nread);
  522. if(CHUNKE_OK < res) {
  523. if(CHUNKE_WRITE_ERROR == res) {
  524. failf(data, "Failed writing data");
  525. return CURLE_WRITE_ERROR;
  526. }
  527. failf(data, "Problem (%d) in the Chunked-Encoded data", (int)res);
  528. return CURLE_RECV_ERROR;
  529. }
  530. else if(CHUNKE_STOP == res) {
  531. size_t dataleft;
  532. /* we're done reading chunks! */
  533. k->keepon &= ~KEEP_RECV; /* read no more */
  534. /* There are now possibly N number of bytes at the end of the
  535. str buffer that weren't written to the client.
  536. We DO care about this data if we are pipelining.
  537. Push it back to be read on the next pass. */
  538. dataleft = conn->chunk.dataleft;
  539. if(dataleft != 0) {
  540. infof(conn->data, "Leftovers after chunking: %zu bytes\n",
  541. dataleft);
  542. if(Curl_multi_pipeline_enabled(conn->data->multi)) {
  543. /* only attempt the rewind if we truly are pipelining */
  544. infof(conn->data, "Rewinding %zu bytes\n",dataleft);
  545. read_rewind(conn, dataleft);
  546. }
  547. }
  548. }
  549. /* If it returned OK, we just keep going */
  550. }
  551. #endif /* CURL_DISABLE_HTTP */
  552. /* Account for body content stored in the header buffer */
  553. if(k->badheader && !k->ignorebody) {
  554. DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
  555. k->hbuflen));
  556. k->bytecount += k->hbuflen;
  557. }
  558. if((-1 != k->maxdownload) &&
  559. (k->bytecount + nread >= k->maxdownload)) {
  560. excess = (size_t)(k->bytecount + nread - k->maxdownload);
  561. if(excess > 0 && !k->ignorebody) {
  562. if(Curl_multi_pipeline_enabled(conn->data->multi)) {
  563. /* The 'excess' amount below can't be more than BUFSIZE which
  564. always will fit in a size_t */
  565. infof(data,
  566. "Rewinding stream by : %zu"
  567. " bytes on url %s (size = %" CURL_FORMAT_CURL_OFF_T
  568. ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
  569. ", bytecount = %" CURL_FORMAT_CURL_OFF_T ", nread = %zd)\n",
  570. excess, data->state.path,
  571. k->size, k->maxdownload, k->bytecount, nread);
  572. read_rewind(conn, excess);
  573. }
  574. else {
  575. infof(data,
  576. "Excess found in a non pipelined read:"
  577. " excess = %zu"
  578. ", size = %" CURL_FORMAT_CURL_OFF_T
  579. ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
  580. ", bytecount = %" CURL_FORMAT_CURL_OFF_T "\n",
  581. excess, k->size, k->maxdownload, k->bytecount);
  582. }
  583. }
  584. nread = (ssize_t) (k->maxdownload - k->bytecount);
  585. if(nread < 0 ) /* this should be unusual */
  586. nread = 0;
  587. k->keepon &= ~KEEP_RECV; /* we're done reading */
  588. }
  589. k->bytecount += nread;
  590. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  591. if(!k->chunk && (nread || k->badheader || is_empty_data)) {
  592. /* If this is chunky transfer, it was already written */
  593. if(k->badheader && !k->ignorebody) {
  594. /* we parsed a piece of data wrongly assuming it was a header
  595. and now we output it as body instead */
  596. /* Don't let excess data pollute body writes */
  597. if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
  598. result = Curl_client_write(conn, CLIENTWRITE_BODY,
  599. data->state.headerbuff,
  600. k->hbuflen);
  601. else
  602. result = Curl_client_write(conn, CLIENTWRITE_BODY,
  603. data->state.headerbuff,
  604. (size_t)k->maxdownload);
  605. if(result)
  606. return result;
  607. }
  608. if(k->badheader < HEADER_ALLBAD) {
  609. /* This switch handles various content encodings. If there's an
  610. error here, be sure to check over the almost identical code
  611. in http_chunks.c.
  612. Make sure that ALL_CONTENT_ENCODINGS contains all the
  613. encodings handled here. */
  614. #ifdef HAVE_LIBZ
  615. switch (conn->data->set.http_ce_skip ?
  616. IDENTITY : k->auto_decoding) {
  617. case IDENTITY:
  618. #endif
  619. /* This is the default when the server sends no
  620. Content-Encoding header. See Curl_readwrite_init; the
  621. memset() call initializes k->auto_decoding to zero. */
  622. if(!k->ignorebody) {
  623. #ifndef CURL_DISABLE_POP3
  624. if(conn->handler->protocol&CURLPROTO_POP3)
  625. result = Curl_pop3_write(conn, k->str, nread);
  626. else
  627. #endif /* CURL_DISABLE_POP3 */
  628. result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
  629. nread);
  630. }
  631. #ifdef HAVE_LIBZ
  632. break;
  633. case DEFLATE:
  634. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  635. if(!k->ignorebody)
  636. result = Curl_unencode_deflate_write(conn, k, nread);
  637. break;
  638. case GZIP:
  639. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  640. if(!k->ignorebody)
  641. result = Curl_unencode_gzip_write(conn, k, nread);
  642. break;
  643. case COMPRESS:
  644. default:
  645. failf (data, "Unrecognized content encoding type. "
  646. "libcurl understands `identity', `deflate' and `gzip' "
  647. "content encodings.");
  648. result = CURLE_BAD_CONTENT_ENCODING;
  649. break;
  650. }
  651. #endif
  652. }
  653. k->badheader = HEADER_NORMAL; /* taken care of now */
  654. if(result)
  655. return result;
  656. }
  657. } /* if(! header and data to read ) */
  658. if(conn->handler->readwrite &&
  659. (excess > 0 && !conn->bits.stream_was_rewound)) {
  660. /* Parse the excess data */
  661. k->str += nread;
  662. nread = (ssize_t)excess;
  663. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  664. if(result)
  665. return result;
  666. if(readmore)
  667. k->keepon |= KEEP_RECV; /* we're not done reading */
  668. break;
  669. }
  670. if(is_empty_data) {
  671. /* if we received nothing, the server closed the connection and we
  672. are done */
  673. k->keepon &= ~KEEP_RECV;
  674. }
  675. } while(data_pending(conn));
  676. if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
  677. conn->bits.close ) {
  678. /* When we've read the entire thing and the close bit is set, the server
  679. may now close the connection. If there's now any kind of sending going
  680. on from our side, we need to stop that immediately. */
  681. infof(data, "we are done reading and this is set to close, stop send\n");
  682. k->keepon &= ~KEEP_SEND; /* no writing anymore either */
  683. }
  684. return CURLE_OK;
  685. }
  686. /*
  687. * Send data to upload to the server, when the socket is writable.
  688. */
  689. static CURLcode readwrite_upload(struct SessionHandle *data,
  690. struct connectdata *conn,
  691. struct SingleRequest *k,
  692. int *didwhat)
  693. {
  694. ssize_t i, si;
  695. ssize_t bytes_written;
  696. CURLcode result;
  697. ssize_t nread; /* number of bytes read */
  698. bool sending_http_headers = FALSE;
  699. if((k->bytecount == 0) && (k->writebytecount == 0))
  700. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  701. *didwhat |= KEEP_SEND;
  702. /*
  703. * We loop here to do the READ and SEND loop until we run out of
  704. * data to send or until we get EWOULDBLOCK back
  705. *
  706. * FIXME: above comment is misleading. Currently no looping is
  707. * actually done in do-while loop below.
  708. */
  709. do {
  710. /* only read more data if there's no upload data already
  711. present in the upload buffer */
  712. if(0 == data->req.upload_present) {
  713. /* init the "upload from here" pointer */
  714. data->req.upload_fromhere = k->uploadbuf;
  715. if(!k->upload_done) {
  716. /* HTTP pollution, this should be written nicer to become more
  717. protocol agnostic. */
  718. int fillcount;
  719. struct HTTP *http = data->req.protop;
  720. if((k->exp100 == EXP100_SENDING_REQUEST) &&
  721. (http->sending == HTTPSEND_BODY)) {
  722. /* If this call is to send body data, we must take some action:
  723. We have sent off the full HTTP 1.1 request, and we shall now
  724. go into the Expect: 100 state and await such a header */
  725. k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
  726. k->keepon &= ~KEEP_SEND; /* disable writing */
  727. k->start100 = Curl_tvnow(); /* timeout count starts now */
  728. *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
  729. /* set a timeout for the multi interface */
  730. Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
  731. break;
  732. }
  733. if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
  734. if(http->sending == HTTPSEND_REQUEST)
  735. /* We're sending the HTTP request headers, not the data.
  736. Remember that so we don't change the line endings. */
  737. sending_http_headers = TRUE;
  738. else
  739. sending_http_headers = FALSE;
  740. }
  741. result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
  742. if(result)
  743. return result;
  744. nread = (ssize_t)fillcount;
  745. }
  746. else
  747. nread = 0; /* we're done uploading/reading */
  748. if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
  749. /* this is a paused transfer */
  750. break;
  751. }
  752. else if(nread<=0) {
  753. /* done */
  754. k->keepon &= ~KEEP_SEND; /* we're done writing */
  755. if(conn->bits.rewindaftersend) {
  756. result = Curl_readrewind(conn);
  757. if(result)
  758. return result;
  759. }
  760. break;
  761. }
  762. /* store number of bytes available for upload */
  763. data->req.upload_present = nread;
  764. #ifndef CURL_DISABLE_SMTP
  765. if(conn->handler->protocol & CURLPROTO_SMTP) {
  766. result = Curl_smtp_escape_eob(conn, nread);
  767. if(result)
  768. return result;
  769. }
  770. else
  771. #endif /* CURL_DISABLE_SMTP */
  772. /* convert LF to CRLF if so asked */
  773. if((!sending_http_headers) && (
  774. #ifdef CURL_DO_LINEEND_CONV
  775. /* always convert if we're FTPing in ASCII mode */
  776. (data->set.prefer_ascii) ||
  777. #endif
  778. (data->set.crlf))) {
  779. if(data->state.scratch == NULL)
  780. data->state.scratch = malloc(2*BUFSIZE);
  781. if(data->state.scratch == NULL) {
  782. failf (data, "Failed to alloc scratch buffer!");
  783. return CURLE_OUT_OF_MEMORY;
  784. }
  785. /*
  786. * ASCII/EBCDIC Note: This is presumably a text (not binary)
  787. * transfer so the data should already be in ASCII.
  788. * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
  789. * must be used instead of the escape sequences \r & \n.
  790. */
  791. for(i = 0, si = 0; i < nread; i++, si++) {
  792. if(data->req.upload_fromhere[i] == 0x0a) {
  793. data->state.scratch[si++] = 0x0d;
  794. data->state.scratch[si] = 0x0a;
  795. if(!data->set.crlf) {
  796. /* we're here only because FTP is in ASCII mode...
  797. bump infilesize for the LF we just added */
  798. data->set.infilesize++;
  799. }
  800. }
  801. else
  802. data->state.scratch[si] = data->req.upload_fromhere[i];
  803. }
  804. if(si != nread) {
  805. /* only perform the special operation if we really did replace
  806. anything */
  807. nread = si;
  808. /* upload from the new (replaced) buffer instead */
  809. data->req.upload_fromhere = data->state.scratch;
  810. /* set the new amount too */
  811. data->req.upload_present = nread;
  812. }
  813. }
  814. } /* if 0 == data->req.upload_present */
  815. else {
  816. /* We have a partial buffer left from a previous "round". Use
  817. that instead of reading more data */
  818. }
  819. /* write to socket (send away data) */
  820. result = Curl_write(conn,
  821. conn->writesockfd, /* socket to send to */
  822. data->req.upload_fromhere, /* buffer pointer */
  823. data->req.upload_present, /* buffer size */
  824. &bytes_written); /* actually sent */
  825. if(result)
  826. return result;
  827. if(data->set.verbose)
  828. /* show the data before we change the pointer upload_fromhere */
  829. Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
  830. (size_t)bytes_written, conn);
  831. k->writebytecount += bytes_written;
  832. if(k->writebytecount == data->set.infilesize) {
  833. /* we have sent all data we were supposed to */
  834. k->upload_done = TRUE;
  835. infof(data, "We are completely uploaded and fine\n");
  836. }
  837. if(data->req.upload_present != bytes_written) {
  838. /* we only wrote a part of the buffer (if anything), deal with it! */
  839. /* store the amount of bytes left in the buffer to write */
  840. data->req.upload_present -= bytes_written;
  841. /* advance the pointer where to find the buffer when the next send
  842. is to happen */
  843. data->req.upload_fromhere += bytes_written;
  844. }
  845. else {
  846. /* we've uploaded that buffer now */
  847. data->req.upload_fromhere = k->uploadbuf;
  848. data->req.upload_present = 0; /* no more bytes left */
  849. if(k->upload_done) {
  850. /* switch off writing, we're done! */
  851. k->keepon &= ~KEEP_SEND; /* we're done writing */
  852. }
  853. }
  854. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  855. } WHILE_FALSE; /* just to break out from! */
  856. return CURLE_OK;
  857. }
  858. /*
  859. * Curl_readwrite() is the low-level function to be called when data is to
  860. * be read and written to/from the connection.
  861. */
  862. CURLcode Curl_readwrite(struct connectdata *conn,
  863. bool *done)
  864. {
  865. struct SessionHandle *data = conn->data;
  866. struct SingleRequest *k = &data->req;
  867. CURLcode result;
  868. int didwhat=0;
  869. curl_socket_t fd_read;
  870. curl_socket_t fd_write;
  871. int select_res = conn->cselect_bits;
  872. conn->cselect_bits = 0;
  873. /* only use the proper socket if the *_HOLD bit is not set simultaneously as
  874. then we are in rate limiting state in that transfer direction */
  875. if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
  876. fd_read = conn->sockfd;
  877. else
  878. fd_read = CURL_SOCKET_BAD;
  879. if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
  880. fd_write = conn->writesockfd;
  881. else
  882. fd_write = CURL_SOCKET_BAD;
  883. if(!select_res) /* Call for select()/poll() only, if read/write/error
  884. status is not known. */
  885. select_res = Curl_socket_ready(fd_read, fd_write, 0);
  886. if(select_res == CURL_CSELECT_ERR) {
  887. failf(data, "select/poll returned error");
  888. return CURLE_SEND_ERROR;
  889. }
  890. /* We go ahead and do a read if we have a readable socket or if
  891. the stream was rewound (in which case we have data in a
  892. buffer) */
  893. if((k->keepon & KEEP_RECV) &&
  894. ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
  895. result = readwrite_data(data, conn, k, &didwhat, done);
  896. if(result || *done)
  897. return result;
  898. }
  899. /* If we still have writing to do, we check if we have a writable socket. */
  900. if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
  901. /* write */
  902. result = readwrite_upload(data, conn, k, &didwhat);
  903. if(result)
  904. return result;
  905. }
  906. k->now = Curl_tvnow();
  907. if(didwhat) {
  908. /* Update read/write counters */
  909. if(k->bytecountp)
  910. *k->bytecountp = k->bytecount; /* read count */
  911. if(k->writebytecountp)
  912. *k->writebytecountp = k->writebytecount; /* write count */
  913. }
  914. else {
  915. /* no read no write, this is a timeout? */
  916. if(k->exp100 == EXP100_AWAITING_CONTINUE) {
  917. /* This should allow some time for the header to arrive, but only a
  918. very short time as otherwise it'll be too much wasted time too
  919. often. */
  920. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  921. Therefore, when a client sends this header field to an origin server
  922. (possibly via a proxy) from which it has never seen a 100 (Continue)
  923. status, the client SHOULD NOT wait for an indefinite period before
  924. sending the request body.
  925. */
  926. long ms = Curl_tvdiff(k->now, k->start100);
  927. if(ms > CURL_TIMEOUT_EXPECT_100) {
  928. /* we've waited long enough, continue anyway */
  929. k->exp100 = EXP100_SEND_DATA;
  930. k->keepon |= KEEP_SEND;
  931. infof(data, "Done waiting for 100-continue\n");
  932. }
  933. }
  934. }
  935. if(Curl_pgrsUpdate(conn))
  936. result = CURLE_ABORTED_BY_CALLBACK;
  937. else
  938. result = Curl_speedcheck(data, k->now);
  939. if(result)
  940. return result;
  941. if(k->keepon) {
  942. if(0 > Curl_timeleft(data, &k->now, FALSE)) {
  943. if(k->size != -1) {
  944. failf(data, "Operation timed out after %ld milliseconds with %"
  945. CURL_FORMAT_CURL_OFF_T " out of %"
  946. CURL_FORMAT_CURL_OFF_T " bytes received",
  947. Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount,
  948. k->size);
  949. }
  950. else {
  951. failf(data, "Operation timed out after %ld milliseconds with %"
  952. CURL_FORMAT_CURL_OFF_T " bytes received",
  953. Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount);
  954. }
  955. return CURLE_OPERATION_TIMEDOUT;
  956. }
  957. }
  958. else {
  959. /*
  960. * The transfer has been performed. Just make some general checks before
  961. * returning.
  962. */
  963. if(!(data->set.opt_no_body) && (k->size != -1) &&
  964. (k->bytecount != k->size) &&
  965. #ifdef CURL_DO_LINEEND_CONV
  966. /* Most FTP servers don't adjust their file SIZE response for CRLFs,
  967. so we'll check to see if the discrepancy can be explained
  968. by the number of CRLFs we've changed to LFs.
  969. */
  970. (k->bytecount != (k->size + data->state.crlf_conversions)) &&
  971. #endif /* CURL_DO_LINEEND_CONV */
  972. !data->req.newurl) {
  973. failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
  974. " bytes remaining to read",
  975. k->size - k->bytecount);
  976. return CURLE_PARTIAL_FILE;
  977. }
  978. else if(!(data->set.opt_no_body) &&
  979. k->chunk &&
  980. (conn->chunk.state != CHUNK_STOP)) {
  981. /*
  982. * In chunked mode, return an error if the connection is closed prior to
  983. * the empty (terminating) chunk is read.
  984. *
  985. * The condition above used to check for
  986. * conn->proto.http->chunk.datasize != 0 which is true after reading
  987. * *any* chunk, not just the empty chunk.
  988. *
  989. */
  990. failf(data, "transfer closed with outstanding read data remaining");
  991. return CURLE_PARTIAL_FILE;
  992. }
  993. if(Curl_pgrsUpdate(conn))
  994. return CURLE_ABORTED_BY_CALLBACK;
  995. }
  996. /* Now update the "done" boolean we return */
  997. *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
  998. KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
  999. return CURLE_OK;
  1000. }
  1001. /*
  1002. * Curl_single_getsock() gets called by the multi interface code when the app
  1003. * has requested to get the sockets for the current connection. This function
  1004. * will then be called once for every connection that the multi interface
  1005. * keeps track of. This function will only be called for connections that are
  1006. * in the proper state to have this information available.
  1007. */
  1008. int Curl_single_getsock(const struct connectdata *conn,
  1009. curl_socket_t *sock, /* points to numsocks number
  1010. of sockets */
  1011. int numsocks)
  1012. {
  1013. const struct SessionHandle *data = conn->data;
  1014. int bitmap = GETSOCK_BLANK;
  1015. unsigned sockindex = 0;
  1016. if(conn->handler->perform_getsock)
  1017. return conn->handler->perform_getsock(conn, sock, numsocks);
  1018. if(numsocks < 2)
  1019. /* simple check but we might need two slots */
  1020. return GETSOCK_BLANK;
  1021. /* don't include HOLD and PAUSE connections */
  1022. if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
  1023. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1024. bitmap |= GETSOCK_READSOCK(sockindex);
  1025. sock[sockindex] = conn->sockfd;
  1026. }
  1027. /* don't include HOLD and PAUSE connections */
  1028. if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
  1029. if((conn->sockfd != conn->writesockfd) ||
  1030. !(data->req.keepon & KEEP_RECV)) {
  1031. /* only if they are not the same socket or we didn't have a readable
  1032. one, we increase index */
  1033. if(data->req.keepon & KEEP_RECV)
  1034. sockindex++; /* increase index if we need two entries */
  1035. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1036. sock[sockindex] = conn->writesockfd;
  1037. }
  1038. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1039. }
  1040. return bitmap;
  1041. }
  1042. /*
  1043. * Determine optimum sleep time based on configured rate, current rate,
  1044. * and packet size.
  1045. * Returns value in milliseconds.
  1046. *
  1047. * The basic idea is to adjust the desired rate up/down in this method
  1048. * based on whether we are running too slow or too fast. Then, calculate
  1049. * how many milliseconds to wait for the next packet to achieve this new
  1050. * rate.
  1051. */
  1052. long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
  1053. int pkt_size)
  1054. {
  1055. curl_off_t min_sleep = 0;
  1056. curl_off_t rv = 0;
  1057. if(rate_bps == 0)
  1058. return 0;
  1059. /* If running faster than about .1% of the desired speed, slow
  1060. * us down a bit. Use shift instead of division as the 0.1%
  1061. * cutoff is arbitrary anyway.
  1062. */
  1063. if(cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
  1064. /* running too fast, decrease target rate by 1/64th of rate */
  1065. rate_bps -= rate_bps >> 6;
  1066. min_sleep = 1;
  1067. }
  1068. else if(cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
  1069. /* running too slow, increase target rate by 1/64th of rate */
  1070. rate_bps += rate_bps >> 6;
  1071. }
  1072. /* Determine number of milliseconds to wait until we do
  1073. * the next packet at the adjusted rate. We should wait
  1074. * longer when using larger packets, for instance.
  1075. */
  1076. rv = ((curl_off_t)((pkt_size * 8) * 1000) / rate_bps);
  1077. /* Catch rounding errors and always slow down at least 1ms if
  1078. * we are running too fast.
  1079. */
  1080. if(rv < min_sleep)
  1081. rv = min_sleep;
  1082. /* Bound value to fit in 'long' on 32-bit platform. That's
  1083. * plenty long enough anyway!
  1084. */
  1085. if(rv > 0x7fffffff)
  1086. rv = 0x7fffffff;
  1087. return (long)rv;
  1088. }
  1089. /*
  1090. * Curl_pretransfer() is called immediately before a transfer starts.
  1091. */
  1092. CURLcode Curl_pretransfer(struct SessionHandle *data)
  1093. {
  1094. CURLcode res;
  1095. if(!data->change.url) {
  1096. /* we can't do anything without URL */
  1097. failf(data, "No URL set!");
  1098. return CURLE_URL_MALFORMAT;
  1099. }
  1100. /* Init the SSL session ID cache here. We do it here since we want to do it
  1101. after the *_setopt() calls (that could specify the size of the cache) but
  1102. before any transfer takes place. */
  1103. res = Curl_ssl_initsessions(data, data->set.ssl.max_ssl_sessions);
  1104. if(res)
  1105. return res;
  1106. data->set.followlocation=0; /* reset the location-follow counter */
  1107. data->state.this_is_a_follow = FALSE; /* reset this */
  1108. data->state.errorbuf = FALSE; /* no error has occurred */
  1109. data->state.httpversion = 0; /* don't assume any particular server version */
  1110. data->state.ssl_connect_retry = FALSE;
  1111. data->state.authproblem = FALSE;
  1112. data->state.authhost.want = data->set.httpauth;
  1113. data->state.authproxy.want = data->set.proxyauth;
  1114. Curl_safefree(data->info.wouldredirect);
  1115. data->info.wouldredirect = NULL;
  1116. /* If there is a list of cookie files to read, do it now! */
  1117. if(data->change.cookielist)
  1118. Curl_cookie_loadfiles(data);
  1119. /* If there is a list of host pairs to deal with */
  1120. if(data->change.resolve)
  1121. res = Curl_loadhostpairs(data);
  1122. if(!res) {
  1123. /* Allow data->set.use_port to set which port to use. This needs to be
  1124. * disabled for example when we follow Location: headers to URLs using
  1125. * different ports! */
  1126. data->state.allow_port = TRUE;
  1127. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1128. /*************************************************************
  1129. * Tell signal handler to ignore SIGPIPE
  1130. *************************************************************/
  1131. if(!data->set.no_signal)
  1132. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1133. #endif
  1134. Curl_initinfo(data); /* reset session-specific information "variables" */
  1135. Curl_pgrsStartNow(data);
  1136. if(data->set.timeout)
  1137. Curl_expire(data, data->set.timeout + MULTI_TIMEOUT_INACCURACY_MS);
  1138. if(data->set.connecttimeout)
  1139. Curl_expire(data, data->set.connecttimeout +
  1140. MULTI_TIMEOUT_INACCURACY_MS);
  1141. /* In case the handle is re-used and an authentication method was picked
  1142. in the session we need to make sure we only use the one(s) we now
  1143. consider to be fine */
  1144. data->state.authhost.picked &= data->state.authhost.want;
  1145. data->state.authproxy.picked &= data->state.authproxy.want;
  1146. }
  1147. return res;
  1148. }
  1149. /*
  1150. * Curl_posttransfer() is called immediately after a transfer ends
  1151. */
  1152. CURLcode Curl_posttransfer(struct SessionHandle *data)
  1153. {
  1154. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1155. /* restore the signal handler for SIGPIPE before we get back */
  1156. if(!data->set.no_signal)
  1157. signal(SIGPIPE, data->state.prev_signal);
  1158. #else
  1159. (void)data; /* unused parameter */
  1160. #endif
  1161. return CURLE_OK;
  1162. }
  1163. #ifndef CURL_DISABLE_HTTP
  1164. /*
  1165. * strlen_url() returns the length of the given URL if the spaces within the
  1166. * URL were properly URL encoded.
  1167. */
  1168. static size_t strlen_url(const char *url)
  1169. {
  1170. const char *ptr;
  1171. size_t newlen=0;
  1172. bool left=TRUE; /* left side of the ? */
  1173. for(ptr=url; *ptr; ptr++) {
  1174. switch(*ptr) {
  1175. case '?':
  1176. left=FALSE;
  1177. /* fall through */
  1178. default:
  1179. newlen++;
  1180. break;
  1181. case ' ':
  1182. if(left)
  1183. newlen+=3;
  1184. else
  1185. newlen++;
  1186. break;
  1187. }
  1188. }
  1189. return newlen;
  1190. }
  1191. /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
  1192. * the source URL accordingly.
  1193. */
  1194. static void strcpy_url(char *output, const char *url)
  1195. {
  1196. /* we must add this with whitespace-replacing */
  1197. bool left=TRUE;
  1198. const char *iptr;
  1199. char *optr = output;
  1200. for(iptr = url; /* read from here */
  1201. *iptr; /* until zero byte */
  1202. iptr++) {
  1203. switch(*iptr) {
  1204. case '?':
  1205. left=FALSE;
  1206. /* fall through */
  1207. default:
  1208. *optr++=*iptr;
  1209. break;
  1210. case ' ':
  1211. if(left) {
  1212. *optr++='%'; /* add a '%' */
  1213. *optr++='2'; /* add a '2' */
  1214. *optr++='0'; /* add a '0' */
  1215. }
  1216. else
  1217. *optr++='+'; /* add a '+' here */
  1218. break;
  1219. }
  1220. }
  1221. *optr=0; /* zero terminate output buffer */
  1222. }
  1223. /*
  1224. * Returns true if the given URL is absolute (as opposed to relative)
  1225. */
  1226. static bool is_absolute_url(const char *url)
  1227. {
  1228. char prot[16]; /* URL protocol string storage */
  1229. char letter; /* used for a silly sscanf */
  1230. return (2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter)) ? TRUE : FALSE;
  1231. }
  1232. /*
  1233. * Concatenate a relative URL to a base URL making it absolute.
  1234. * URL-encodes any spaces.
  1235. * The returned pointer must be freed by the caller unless NULL
  1236. * (returns NULL on out of memory).
  1237. */
  1238. static char *concat_url(const char *base, const char *relurl)
  1239. {
  1240. /***
  1241. TRY to append this new path to the old URL
  1242. to the right of the host part. Oh crap, this is doomed to cause
  1243. problems in the future...
  1244. */
  1245. char *newest;
  1246. char *protsep;
  1247. char *pathsep;
  1248. size_t newlen;
  1249. const char *useurl = relurl;
  1250. size_t urllen;
  1251. /* we must make our own copy of the URL to play with, as it may
  1252. point to read-only data */
  1253. char *url_clone=strdup(base);
  1254. if(!url_clone)
  1255. return NULL; /* skip out of this NOW */
  1256. /* protsep points to the start of the host name */
  1257. protsep=strstr(url_clone, "//");
  1258. if(!protsep)
  1259. protsep=url_clone;
  1260. else
  1261. protsep+=2; /* pass the slashes */
  1262. if('/' != relurl[0]) {
  1263. int level=0;
  1264. /* First we need to find out if there's a ?-letter in the URL,
  1265. and cut it and the right-side of that off */
  1266. pathsep = strchr(protsep, '?');
  1267. if(pathsep)
  1268. *pathsep=0;
  1269. /* we have a relative path to append to the last slash if there's one
  1270. available, or if the new URL is just a query string (starts with a
  1271. '?') we append the new one at the end of the entire currently worked
  1272. out URL */
  1273. if(useurl[0] != '?') {
  1274. pathsep = strrchr(protsep, '/');
  1275. if(pathsep)
  1276. *pathsep=0;
  1277. }
  1278. /* Check if there's any slash after the host name, and if so, remember
  1279. that position instead */
  1280. pathsep = strchr(protsep, '/');
  1281. if(pathsep)
  1282. protsep = pathsep+1;
  1283. else
  1284. protsep = NULL;
  1285. /* now deal with one "./" or any amount of "../" in the newurl
  1286. and act accordingly */
  1287. if((useurl[0] == '.') && (useurl[1] == '/'))
  1288. useurl+=2; /* just skip the "./" */
  1289. while((useurl[0] == '.') &&
  1290. (useurl[1] == '.') &&
  1291. (useurl[2] == '/')) {
  1292. level++;
  1293. useurl+=3; /* pass the "../" */
  1294. }
  1295. if(protsep) {
  1296. while(level--) {
  1297. /* cut off one more level from the right of the original URL */
  1298. pathsep = strrchr(protsep, '/');
  1299. if(pathsep)
  1300. *pathsep=0;
  1301. else {
  1302. *protsep=0;
  1303. break;
  1304. }
  1305. }
  1306. }
  1307. }
  1308. else {
  1309. /* We got a new absolute path for this server */
  1310. if((relurl[0] == '/') && (relurl[1] == '/')) {
  1311. /* the new URL starts with //, just keep the protocol part from the
  1312. original one */
  1313. *protsep=0;
  1314. useurl = &relurl[2]; /* we keep the slashes from the original, so we
  1315. skip the new ones */
  1316. }
  1317. else {
  1318. /* cut off the original URL from the first slash, or deal with URLs
  1319. without slash */
  1320. pathsep = strchr(protsep, '/');
  1321. if(pathsep) {
  1322. /* When people use badly formatted URLs, such as
  1323. "http://www.url.com?dir=/home/daniel" we must not use the first
  1324. slash, if there's a ?-letter before it! */
  1325. char *sep = strchr(protsep, '?');
  1326. if(sep && (sep < pathsep))
  1327. pathsep = sep;
  1328. *pathsep=0;
  1329. }
  1330. else {
  1331. /* There was no slash. Now, since we might be operating on a badly
  1332. formatted URL, such as "http://www.url.com?id=2380" which doesn't
  1333. use a slash separator as it is supposed to, we need to check for a
  1334. ?-letter as well! */
  1335. pathsep = strchr(protsep, '?');
  1336. if(pathsep)
  1337. *pathsep=0;
  1338. }
  1339. }
  1340. }
  1341. /* If the new part contains a space, this is a mighty stupid redirect
  1342. but we still make an effort to do "right". To the left of a '?'
  1343. letter we replace each space with %20 while it is replaced with '+'
  1344. on the right side of the '?' letter.
  1345. */
  1346. newlen = strlen_url(useurl);
  1347. urllen = strlen(url_clone);
  1348. newest = malloc(urllen + 1 + /* possible slash */
  1349. newlen + 1 /* zero byte */);
  1350. if(!newest) {
  1351. free(url_clone); /* don't leak this */
  1352. return NULL;
  1353. }
  1354. /* copy over the root url part */
  1355. memcpy(newest, url_clone, urllen);
  1356. /* check if we need to append a slash */
  1357. if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
  1358. ;
  1359. else
  1360. newest[urllen++]='/';
  1361. /* then append the new piece on the right side */
  1362. strcpy_url(&newest[urllen], useurl);
  1363. free(url_clone);
  1364. return newest;
  1365. }
  1366. #endif /* CURL_DISABLE_HTTP */
  1367. /*
  1368. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1369. * as given by the remote server and set up the new URL to request.
  1370. */
  1371. CURLcode Curl_follow(struct SessionHandle *data,
  1372. char *newurl, /* this 'newurl' is the Location: string,
  1373. and it must be malloc()ed before passed
  1374. here */
  1375. followtype type) /* see transfer.h */
  1376. {
  1377. #ifdef CURL_DISABLE_HTTP
  1378. (void)data;
  1379. (void)newurl;
  1380. (void)type;
  1381. /* Location: following will not happen when HTTP is disabled */
  1382. return CURLE_TOO_MANY_REDIRECTS;
  1383. #else
  1384. /* Location: redirect */
  1385. bool disallowport = FALSE;
  1386. if(type == FOLLOW_REDIR) {
  1387. if((data->set.maxredirs != -1) &&
  1388. (data->set.followlocation >= data->set.maxredirs)) {
  1389. failf(data,"Maximum (%ld) redirects followed", data->set.maxredirs);
  1390. return CURLE_TOO_MANY_REDIRECTS;
  1391. }
  1392. /* mark the next request as a followed location: */
  1393. data->state.this_is_a_follow = TRUE;
  1394. data->set.followlocation++; /* count location-followers */
  1395. if(data->set.http_auto_referer) {
  1396. /* We are asked to automatically set the previous URL as the referer
  1397. when we get the next URL. We pick the ->url field, which may or may
  1398. not be 100% correct */
  1399. if(data->change.referer_alloc) {
  1400. Curl_safefree(data->change.referer);
  1401. data->change.referer_alloc = FALSE;
  1402. }
  1403. data->change.referer = strdup(data->change.url);
  1404. if(!data->change.referer)
  1405. return CURLE_OUT_OF_MEMORY;
  1406. data->change.referer_alloc = TRUE; /* yes, free this later */
  1407. }
  1408. }
  1409. if(!is_absolute_url(newurl)) {
  1410. /***
  1411. *DANG* this is an RFC 2068 violation. The URL is supposed
  1412. to be absolute and this doesn't seem to be that!
  1413. */
  1414. char *absolute = concat_url(data->change.url, newurl);
  1415. if(!absolute)
  1416. return CURLE_OUT_OF_MEMORY;
  1417. free(newurl);
  1418. newurl = absolute;
  1419. }
  1420. else {
  1421. /* This is an absolute URL, don't allow the custom port number */
  1422. disallowport = TRUE;
  1423. if(strchr(newurl, ' ')) {
  1424. /* This new URL contains at least one space, this is a mighty stupid
  1425. redirect but we still make an effort to do "right". */
  1426. char *newest;
  1427. size_t newlen = strlen_url(newurl);
  1428. newest = malloc(newlen+1); /* get memory for this */
  1429. if(!newest)
  1430. return CURLE_OUT_OF_MEMORY;
  1431. strcpy_url(newest, newurl); /* create a space-free URL */
  1432. free(newurl); /* that was no good */
  1433. newurl = newest; /* use this instead now */
  1434. }
  1435. }
  1436. if(type == FOLLOW_FAKE) {
  1437. /* we're only figuring out the new url if we would've followed locations
  1438. but now we're done so we can get out! */
  1439. data->info.wouldredirect = newurl;
  1440. return CURLE_OK;
  1441. }
  1442. if(disallowport)
  1443. data->state.allow_port = FALSE;
  1444. if(data->change.url_alloc) {
  1445. Curl_safefree(data->change.url);
  1446. data->change.url_alloc = FALSE;
  1447. }
  1448. data->change.url = newurl;
  1449. data->change.url_alloc = TRUE;
  1450. newurl = NULL; /* don't free! */
  1451. infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
  1452. /*
  1453. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1454. * differently based on exactly what return code there was.
  1455. *
  1456. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1457. * a HTTP (proxy-) authentication scheme other than Basic.
  1458. */
  1459. switch(data->info.httpcode) {
  1460. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1461. Authorization: XXXX header in the HTTP request code snippet */
  1462. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1463. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1464. /* 300 - Multiple Choices */
  1465. /* 306 - Not used */
  1466. /* 307 - Temporary Redirect */
  1467. default: /* for all above (and the unknown ones) */
  1468. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1469. * seem to be OK to POST to.
  1470. */
  1471. break;
  1472. case 301: /* Moved Permanently */
  1473. /* (quote from RFC2616, section 10.3.2):
  1474. *
  1475. * When automatically redirecting a POST request after receiving a 301
  1476. * status code, some existing HTTP/1.0 user agents will erroneously change
  1477. * it into a GET request.
  1478. *
  1479. * ----
  1480. *
  1481. * As most of the important user agents do this obvious RFC2616 violation,
  1482. * many webservers expect this. So these servers often answers to a POST
  1483. * request with an error page. To be sure that libcurl gets the page that
  1484. * most user agents would get, libcurl has to force GET.
  1485. *
  1486. * This behavior can be overridden with CURLOPT_POSTREDIR.
  1487. */
  1488. if((data->set.httpreq == HTTPREQ_POST
  1489. || data->set.httpreq == HTTPREQ_POST_FORM)
  1490. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1491. infof(data,
  1492. "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
  1493. data->set.httpreq = HTTPREQ_GET;
  1494. }
  1495. break;
  1496. case 302: /* Found */
  1497. /* (From 10.3.3)
  1498. Note: RFC 1945 and RFC 2068 specify that the client is not allowed
  1499. to change the method on the redirected request. However, most
  1500. existing user agent implementations treat 302 as if it were a 303
  1501. response, performing a GET on the Location field-value regardless
  1502. of the original request method. The status codes 303 and 307 have
  1503. been added for servers that wish to make unambiguously clear which
  1504. kind of reaction is expected of the client.
  1505. (From 10.3.4)
  1506. Note: Many pre-HTTP/1.1 user agents do not understand the 303
  1507. status. When interoperability with such clients is a concern, the
  1508. 302 status code may be used instead, since most user agents react
  1509. to a 302 response as described here for 303.
  1510. This behavior can be overridden with CURLOPT_POSTREDIR
  1511. */
  1512. if((data->set.httpreq == HTTPREQ_POST
  1513. || data->set.httpreq == HTTPREQ_POST_FORM)
  1514. && !(data->set.keep_post & CURL_REDIR_POST_302)) {
  1515. infof(data,
  1516. "Violate RFC 2616/10.3.3 and switch from POST to GET\n");
  1517. data->set.httpreq = HTTPREQ_GET;
  1518. }
  1519. break;
  1520. case 303: /* See Other */
  1521. /* Disable both types of POSTs, unless the user explicitely
  1522. asks for POST after POST */
  1523. if(data->set.httpreq != HTTPREQ_GET
  1524. && !(data->set.keep_post & CURL_REDIR_POST_303)) {
  1525. data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
  1526. infof(data, "Disables POST, goes with %s\n",
  1527. data->set.opt_no_body?"HEAD":"GET");
  1528. }
  1529. break;
  1530. case 304: /* Not Modified */
  1531. /* 304 means we did a conditional request and it was "Not modified".
  1532. * We shouldn't get any Location: header in this response!
  1533. */
  1534. break;
  1535. case 305: /* Use Proxy */
  1536. /* (quote from RFC2616, section 10.3.6):
  1537. * "The requested resource MUST be accessed through the proxy given
  1538. * by the Location field. The Location field gives the URI of the
  1539. * proxy. The recipient is expected to repeat this single request
  1540. * via the proxy. 305 responses MUST only be generated by origin
  1541. * servers."
  1542. */
  1543. break;
  1544. }
  1545. Curl_pgrsTime(data, TIMER_REDIRECT);
  1546. Curl_pgrsResetTimesSizes(data);
  1547. return CURLE_OK;
  1548. #endif /* CURL_DISABLE_HTTP */
  1549. }
  1550. CURLcode
  1551. Curl_reconnect_request(struct connectdata **connp)
  1552. {
  1553. CURLcode result = CURLE_OK;
  1554. struct connectdata *conn = *connp;
  1555. struct SessionHandle *data = conn->data;
  1556. /* This was a re-use of a connection and we got a write error in the
  1557. * DO-phase. Then we DISCONNECT this connection and have another attempt to
  1558. * CONNECT and then DO again! The retry cannot possibly find another
  1559. * connection to re-use, since we only keep one possible connection for
  1560. * each. */
  1561. infof(data, "Re-used connection seems dead, get a new one\n");
  1562. conn->bits.close = TRUE; /* enforce close of this connection */
  1563. result = Curl_done(&conn, result, FALSE); /* we are so done with this */
  1564. /* conn may no longer be a good pointer, clear it to avoid mistakes by
  1565. parent functions */
  1566. *connp = NULL;
  1567. /*
  1568. * According to bug report #1330310. We need to check for CURLE_SEND_ERROR
  1569. * here as well. I figure this could happen when the request failed on a FTP
  1570. * connection and thus Curl_done() itself tried to use the connection
  1571. * (again). Slight Lack of feedback in the report, but I don't think this
  1572. * extra check can do much harm.
  1573. */
  1574. if((CURLE_OK == result) || (CURLE_SEND_ERROR == result)) {
  1575. bool async;
  1576. bool protocol_done = TRUE;
  1577. /* Now, redo the connect and get a new connection */
  1578. result = Curl_connect(data, connp, &async, &protocol_done);
  1579. if(CURLE_OK == result) {
  1580. /* We have connected or sent away a name resolve query fine */
  1581. conn = *connp; /* setup conn to again point to something nice */
  1582. if(async) {
  1583. /* Now, if async is TRUE here, we need to wait for the name
  1584. to resolve */
  1585. result = Curl_resolver_wait_resolv(conn, NULL);
  1586. if(result)
  1587. return result;
  1588. /* Resolved, continue with the connection */
  1589. result = Curl_async_resolved(conn, &protocol_done);
  1590. if(result)
  1591. return result;
  1592. }
  1593. }
  1594. }
  1595. return result;
  1596. }
  1597. /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
  1598. NOTE: that the *url is malloc()ed. */
  1599. CURLcode Curl_retry_request(struct connectdata *conn,
  1600. char **url)
  1601. {
  1602. struct SessionHandle *data = conn->data;
  1603. *url = NULL;
  1604. /* if we're talking upload, we can't do the checks below, unless the protocol
  1605. is HTTP as when uploading over HTTP we will still get a response */
  1606. if(data->set.upload &&
  1607. !(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)))
  1608. return CURLE_OK;
  1609. if(/* workaround for broken TLS servers */ data->state.ssl_connect_retry ||
  1610. ((data->req.bytecount +
  1611. data->req.headerbytecount == 0) &&
  1612. conn->bits.reuse &&
  1613. !data->set.opt_no_body &&
  1614. data->set.rtspreq != RTSPREQ_RECEIVE)) {
  1615. /* We got no data, we attempted to re-use a connection and yet we want a
  1616. "body". This might happen if the connection was left alive when we were
  1617. done using it before, but that was closed when we wanted to read from
  1618. it again. Bad luck. Retry the same request on a fresh connect! */
  1619. infof(conn->data, "Connection died, retrying a fresh connect\n");
  1620. *url = strdup(conn->data->change.url);
  1621. if(!*url)
  1622. return CURLE_OUT_OF_MEMORY;
  1623. conn->bits.close = TRUE; /* close this connection */
  1624. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1625. to retry. Marking it this way should
  1626. prevent i.e HTTP transfers to return
  1627. error just because nothing has been
  1628. transferred! */
  1629. if(conn->handler->protocol&CURLPROTO_HTTP) {
  1630. struct HTTP *http = data->req.protop;
  1631. if(http->writebytecount)
  1632. return Curl_readrewind(conn);
  1633. }
  1634. }
  1635. return CURLE_OK;
  1636. }
  1637. /*
  1638. * Curl_setup_transfer() is called to setup some basic properties for the
  1639. * upcoming transfer.
  1640. */
  1641. void
  1642. Curl_setup_transfer(
  1643. struct connectdata *conn, /* connection data */
  1644. int sockindex, /* socket index to read from or -1 */
  1645. curl_off_t size, /* -1 if unknown at this point */
  1646. bool getheader, /* TRUE if header parsing is wanted */
  1647. curl_off_t *bytecountp, /* return number of bytes read or NULL */
  1648. int writesockindex, /* socket index to write to, it may very well be
  1649. the same we read from. -1 disables */
  1650. curl_off_t *writecountp /* return number of bytes written or NULL */
  1651. )
  1652. {
  1653. struct SessionHandle *data;
  1654. struct SingleRequest *k;
  1655. DEBUGASSERT(conn != NULL);
  1656. data = conn->data;
  1657. k = &data->req;
  1658. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  1659. /* now copy all input parameters */
  1660. conn->sockfd = sockindex == -1 ?
  1661. CURL_SOCKET_BAD : conn->sock[sockindex];
  1662. conn->writesockfd = writesockindex == -1 ?
  1663. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1664. k->getheader = getheader;
  1665. k->size = size;
  1666. k->bytecountp = bytecountp;
  1667. k->writebytecountp = writecountp;
  1668. /* The code sequence below is placed in this function just because all
  1669. necessary input is not always known in do_complete() as this function may
  1670. be called after that */
  1671. if(!k->getheader) {
  1672. k->header = FALSE;
  1673. if(size > 0)
  1674. Curl_pgrsSetDownloadSize(data, size);
  1675. }
  1676. /* we want header and/or body, if neither then don't do this! */
  1677. if(k->getheader || !data->set.opt_no_body) {
  1678. if(conn->sockfd != CURL_SOCKET_BAD)
  1679. k->keepon |= KEEP_RECV;
  1680. if(conn->writesockfd != CURL_SOCKET_BAD) {
  1681. struct HTTP *http = data->req.protop;
  1682. /* HTTP 1.1 magic:
  1683. Even if we require a 100-return code before uploading data, we might
  1684. need to write data before that since the REQUEST may not have been
  1685. finished sent off just yet.
  1686. Thus, we must check if the request has been sent before we set the
  1687. state info where we wait for the 100-return code
  1688. */
  1689. if((data->state.expect100header) &&
  1690. (conn->handler->protocol&CURLPROTO_HTTP) &&
  1691. (http->sending == HTTPSEND_BODY)) {
  1692. /* wait with write until we either got 100-continue or a timeout */
  1693. k->exp100 = EXP100_AWAITING_CONTINUE;
  1694. k->start100 = Curl_tvnow();
  1695. /* Set a timeout for the multi interface. Add the inaccuracy margin so
  1696. that we don't fire slightly too early and get denied to run. */
  1697. Curl_expire(data, CURL_TIMEOUT_EXPECT_100 +
  1698. MULTI_TIMEOUT_INACCURACY / 1000);
  1699. }
  1700. else {
  1701. if(data->state.expect100header)
  1702. /* when we've sent off the rest of the headers, we must await a
  1703. 100-continue but first finish sending the request */
  1704. k->exp100 = EXP100_SENDING_REQUEST;
  1705. /* enable the write bit when we're not waiting for continue */
  1706. k->keepon |= KEEP_SEND;
  1707. }
  1708. } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
  1709. } /* if(k->getheader || !data->set.opt_no_body) */
  1710. }