transfer.c 64 KB

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