transfer.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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 https://curl.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include "strtoofft.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. #include <signal.h>
  42. #ifdef HAVE_SYS_PARAM_H
  43. #include <sys/param.h>
  44. #endif
  45. #ifdef HAVE_SYS_SELECT_H
  46. #include <sys/select.h>
  47. #elif defined(HAVE_UNISTD_H)
  48. #include <unistd.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 "cfilters.h"
  59. #include "transfer.h"
  60. #include "sendf.h"
  61. #include "speedcheck.h"
  62. #include "progress.h"
  63. #include "http.h"
  64. #include "url.h"
  65. #include "getinfo.h"
  66. #include "vtls/vtls.h"
  67. #include "vquic/vquic.h"
  68. #include "select.h"
  69. #include "multiif.h"
  70. #include "connect.h"
  71. #include "http2.h"
  72. #include "mime.h"
  73. #include "strcase.h"
  74. #include "urlapi-int.h"
  75. #include "hsts.h"
  76. #include "setopt.h"
  77. #include "headers.h"
  78. /* The last 3 #include files should be in this order */
  79. #include "curl_printf.h"
  80. #include "curl_memory.h"
  81. #include "memdebug.h"
  82. #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
  83. !defined(CURL_DISABLE_IMAP)
  84. /*
  85. * checkheaders() checks the linked list of custom headers for a
  86. * particular header (prefix). Provide the prefix without colon!
  87. *
  88. * Returns a pointer to the first matching header or NULL if none matched.
  89. */
  90. char *Curl_checkheaders(const struct Curl_easy *data,
  91. const char *thisheader,
  92. const size_t thislen)
  93. {
  94. struct curl_slist *head;
  95. DEBUGASSERT(thislen);
  96. DEBUGASSERT(thisheader[thislen-1] != ':');
  97. for(head = data->set.headers; head; head = head->next) {
  98. if(strncasecompare(head->data, thisheader, thislen) &&
  99. Curl_headersep(head->data[thislen]) )
  100. return head->data;
  101. }
  102. return NULL;
  103. }
  104. #endif
  105. CURLcode Curl_get_upload_buffer(struct Curl_easy *data)
  106. {
  107. if(!data->state.ulbuf) {
  108. data->state.ulbuf = malloc(data->set.upload_buffer_size);
  109. if(!data->state.ulbuf)
  110. return CURLE_OUT_OF_MEMORY;
  111. }
  112. return CURLE_OK;
  113. }
  114. #ifndef CURL_DISABLE_HTTP
  115. /*
  116. * This function will be called to loop through the trailers buffer
  117. * until no more data is available for sending.
  118. */
  119. static size_t trailers_read(char *buffer, size_t size, size_t nitems,
  120. void *raw)
  121. {
  122. struct Curl_easy *data = (struct Curl_easy *)raw;
  123. struct dynbuf *trailers_buf = &data->state.trailers_buf;
  124. size_t bytes_left = Curl_dyn_len(trailers_buf) -
  125. data->state.trailers_bytes_sent;
  126. size_t to_copy = (size*nitems < bytes_left) ? size*nitems : bytes_left;
  127. if(to_copy) {
  128. memcpy(buffer,
  129. Curl_dyn_ptr(trailers_buf) + data->state.trailers_bytes_sent,
  130. to_copy);
  131. data->state.trailers_bytes_sent += to_copy;
  132. }
  133. return to_copy;
  134. }
  135. static size_t trailers_left(void *raw)
  136. {
  137. struct Curl_easy *data = (struct Curl_easy *)raw;
  138. struct dynbuf *trailers_buf = &data->state.trailers_buf;
  139. return Curl_dyn_len(trailers_buf) - data->state.trailers_bytes_sent;
  140. }
  141. #endif
  142. /*
  143. * This function will call the read callback to fill our buffer with data
  144. * to upload.
  145. */
  146. CURLcode Curl_fillreadbuffer(struct Curl_easy *data, size_t bytes,
  147. size_t *nreadp)
  148. {
  149. size_t buffersize = bytes;
  150. size_t nread;
  151. curl_read_callback readfunc = NULL;
  152. void *extra_data = NULL;
  153. int eof_index = 0;
  154. #ifndef CURL_DISABLE_HTTP
  155. if(data->state.trailers_state == TRAILERS_INITIALIZED) {
  156. struct curl_slist *trailers = NULL;
  157. CURLcode result;
  158. int trailers_ret_code;
  159. /* at this point we already verified that the callback exists
  160. so we compile and store the trailers buffer, then proceed */
  161. infof(data,
  162. "Moving trailers state machine from initialized to sending.");
  163. data->state.trailers_state = TRAILERS_SENDING;
  164. Curl_dyn_init(&data->state.trailers_buf, DYN_TRAILERS);
  165. data->state.trailers_bytes_sent = 0;
  166. Curl_set_in_callback(data, true);
  167. trailers_ret_code = data->set.trailer_callback(&trailers,
  168. data->set.trailer_data);
  169. Curl_set_in_callback(data, false);
  170. if(trailers_ret_code == CURL_TRAILERFUNC_OK) {
  171. result = Curl_http_compile_trailers(trailers, &data->state.trailers_buf,
  172. data);
  173. }
  174. else {
  175. failf(data, "operation aborted by trailing headers callback");
  176. *nreadp = 0;
  177. result = CURLE_ABORTED_BY_CALLBACK;
  178. }
  179. if(result) {
  180. Curl_dyn_free(&data->state.trailers_buf);
  181. curl_slist_free_all(trailers);
  182. return result;
  183. }
  184. infof(data, "Successfully compiled trailers.");
  185. curl_slist_free_all(trailers);
  186. }
  187. #endif
  188. #ifndef CURL_DISABLE_HTTP
  189. /* if we are transmitting trailing data, we don't need to write
  190. a chunk size so we skip this */
  191. if(data->req.upload_chunky &&
  192. data->state.trailers_state == TRAILERS_NONE) {
  193. /* if chunked Transfer-Encoding */
  194. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  195. data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
  196. }
  197. if(data->state.trailers_state == TRAILERS_SENDING) {
  198. /* if we're here then that means that we already sent the last empty chunk
  199. but we didn't send a final CR LF, so we sent 0 CR LF. We then start
  200. pulling trailing data until we have no more at which point we
  201. simply return to the previous point in the state machine as if
  202. nothing happened.
  203. */
  204. readfunc = trailers_read;
  205. extra_data = (void *)data;
  206. eof_index = 1;
  207. }
  208. else
  209. #endif
  210. {
  211. readfunc = data->state.fread_func;
  212. extra_data = data->state.in;
  213. }
  214. if(!data->req.fread_eof[eof_index]) {
  215. Curl_set_in_callback(data, true);
  216. nread = readfunc(data->req.upload_fromhere, 1, buffersize, extra_data);
  217. Curl_set_in_callback(data, false);
  218. /* make sure the callback is not called again after EOF */
  219. data->req.fread_eof[eof_index] = !nread;
  220. }
  221. else
  222. nread = 0;
  223. if(nread == CURL_READFUNC_ABORT) {
  224. failf(data, "operation aborted by callback");
  225. *nreadp = 0;
  226. return CURLE_ABORTED_BY_CALLBACK;
  227. }
  228. if(nread == CURL_READFUNC_PAUSE) {
  229. struct SingleRequest *k = &data->req;
  230. if(data->conn->handler->flags & PROTOPT_NONETWORK) {
  231. /* protocols that work without network cannot be paused. This is
  232. actually only FILE:// just now, and it can't pause since the transfer
  233. isn't done using the "normal" procedure. */
  234. failf(data, "Read callback asked for PAUSE when not supported");
  235. return CURLE_READ_ERROR;
  236. }
  237. /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
  238. k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
  239. if(data->req.upload_chunky) {
  240. /* Back out the preallocation done above */
  241. data->req.upload_fromhere -= (8 + 2);
  242. }
  243. *nreadp = 0;
  244. return CURLE_OK; /* nothing was read */
  245. }
  246. else if(nread > buffersize) {
  247. /* the read function returned a too large value */
  248. *nreadp = 0;
  249. failf(data, "read function returned funny value");
  250. return CURLE_READ_ERROR;
  251. }
  252. #ifndef CURL_DISABLE_HTTP
  253. if(!data->req.forbidchunk && data->req.upload_chunky) {
  254. /* if chunked Transfer-Encoding
  255. * build chunk:
  256. *
  257. * <HEX SIZE> CRLF
  258. * <DATA> CRLF
  259. */
  260. /* On non-ASCII platforms the <DATA> may or may not be
  261. translated based on state.prefer_ascii while the protocol
  262. portion must always be translated to the network encoding.
  263. To further complicate matters, line end conversion might be
  264. done later on, so we need to prevent CRLFs from becoming
  265. CRCRLFs if that's the case. To do this we use bare LFs
  266. here, knowing they'll become CRLFs later on.
  267. */
  268. bool added_crlf = FALSE;
  269. int hexlen = 0;
  270. const char *endofline_native;
  271. const char *endofline_network;
  272. if(
  273. #ifdef CURL_DO_LINEEND_CONV
  274. (data->state.prefer_ascii) ||
  275. #endif
  276. (data->set.crlf)) {
  277. /* \n will become \r\n later on */
  278. endofline_native = "\n";
  279. endofline_network = "\x0a";
  280. }
  281. else {
  282. endofline_native = "\r\n";
  283. endofline_network = "\x0d\x0a";
  284. }
  285. /* if we're not handling trailing data, proceed as usual */
  286. if(data->state.trailers_state != TRAILERS_SENDING) {
  287. char hexbuffer[11] = "";
  288. hexlen = msnprintf(hexbuffer, sizeof(hexbuffer),
  289. "%zx%s", nread, endofline_native);
  290. /* move buffer pointer */
  291. data->req.upload_fromhere -= hexlen;
  292. nread += hexlen;
  293. /* copy the prefix to the buffer, leaving out the NUL */
  294. memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
  295. /* always append ASCII CRLF to the data unless
  296. we have a valid trailer callback */
  297. if((nread-hexlen) == 0 &&
  298. data->set.trailer_callback != NULL &&
  299. data->state.trailers_state == TRAILERS_NONE) {
  300. data->state.trailers_state = TRAILERS_INITIALIZED;
  301. }
  302. else {
  303. memcpy(data->req.upload_fromhere + nread,
  304. endofline_network,
  305. strlen(endofline_network));
  306. added_crlf = TRUE;
  307. }
  308. }
  309. if(data->state.trailers_state == TRAILERS_SENDING &&
  310. !trailers_left(data)) {
  311. Curl_dyn_free(&data->state.trailers_buf);
  312. data->state.trailers_state = TRAILERS_DONE;
  313. data->set.trailer_data = NULL;
  314. data->set.trailer_callback = NULL;
  315. /* mark the transfer as done */
  316. data->req.upload_done = TRUE;
  317. infof(data, "Signaling end of chunked upload after trailers.");
  318. }
  319. else
  320. if((nread - hexlen) == 0 &&
  321. data->state.trailers_state != TRAILERS_INITIALIZED) {
  322. /* mark this as done once this chunk is transferred */
  323. data->req.upload_done = TRUE;
  324. infof(data,
  325. "Signaling end of chunked upload via terminating chunk.");
  326. }
  327. if(added_crlf)
  328. nread += strlen(endofline_network); /* for the added end of line */
  329. }
  330. #endif
  331. *nreadp = nread;
  332. return CURLE_OK;
  333. }
  334. static int data_pending(struct Curl_easy *data)
  335. {
  336. struct connectdata *conn = data->conn;
  337. if(conn->handler->protocol&PROTO_FAMILY_FTP)
  338. return Curl_conn_data_pending(data, SECONDARYSOCKET);
  339. /* in the case of libssh2, we can never be really sure that we have emptied
  340. its internal buffers so we MUST always try until we get EAGAIN back */
  341. return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
  342. Curl_conn_data_pending(data, FIRSTSOCKET);
  343. }
  344. /*
  345. * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
  346. * remote document with the time provided by CURLOPT_TIMEVAL
  347. */
  348. bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
  349. {
  350. if((timeofdoc == 0) || (data->set.timevalue == 0))
  351. return TRUE;
  352. switch(data->set.timecondition) {
  353. case CURL_TIMECOND_IFMODSINCE:
  354. default:
  355. if(timeofdoc <= data->set.timevalue) {
  356. infof(data,
  357. "The requested document is not new enough");
  358. data->info.timecond = TRUE;
  359. return FALSE;
  360. }
  361. break;
  362. case CURL_TIMECOND_IFUNMODSINCE:
  363. if(timeofdoc >= data->set.timevalue) {
  364. infof(data,
  365. "The requested document is not old enough");
  366. data->info.timecond = TRUE;
  367. return FALSE;
  368. }
  369. break;
  370. }
  371. return TRUE;
  372. }
  373. /*
  374. * Go ahead and do a read if we have a readable socket or if
  375. * the stream was rewound (in which case we have data in a
  376. * buffer)
  377. *
  378. * return '*comeback' TRUE if we didn't properly drain the socket so this
  379. * function should get called again without select() or similar in between!
  380. */
  381. static CURLcode readwrite_data(struct Curl_easy *data,
  382. struct connectdata *conn,
  383. struct SingleRequest *k,
  384. int *didwhat, bool *done,
  385. bool *comeback)
  386. {
  387. CURLcode result = CURLE_OK;
  388. char *buf;
  389. size_t blen;
  390. size_t consumed;
  391. int maxloops = 100;
  392. curl_off_t max_recv = data->set.max_recv_speed?
  393. data->set.max_recv_speed : CURL_OFF_T_MAX;
  394. bool data_eof_handled = FALSE;
  395. DEBUGASSERT(data->state.buffer);
  396. *done = FALSE;
  397. *comeback = FALSE;
  398. /* This is where we loop until we have read everything there is to
  399. read or we get a CURLE_AGAIN */
  400. do {
  401. bool is_empty_data = FALSE;
  402. size_t bytestoread = data->set.buffer_size;
  403. /* For HTTP/2 and HTTP/3, read data without caring about the content
  404. length. This is safe because body in HTTP/2 is always segmented
  405. thanks to its framing layer. Meanwhile, we have to call Curl_read
  406. to ensure that http2_handle_stream_close is called when we read all
  407. incoming bytes for a particular stream. */
  408. bool is_http3 = Curl_conn_is_http3(data, conn, FIRSTSOCKET);
  409. data_eof_handled = is_http3 || Curl_conn_is_http2(data, conn, FIRSTSOCKET);
  410. /* Each loop iteration starts with a fresh buffer and handles
  411. * all data read into it. */
  412. buf = data->state.buffer;
  413. blen = 0;
  414. /* If we are reading BODY data and the connection does NOT handle EOF
  415. * and we know the size of the BODY data, limit the read amount */
  416. if(!k->header && !data_eof_handled && k->size != -1) {
  417. curl_off_t totalleft = k->size - k->bytecount;
  418. if(totalleft <= 0)
  419. bytestoread = 0;
  420. else if(totalleft < (curl_off_t)bytestoread)
  421. bytestoread = (size_t)totalleft;
  422. }
  423. if(bytestoread) {
  424. /* receive data from the network! */
  425. ssize_t nread; /* number of bytes read */
  426. result = Curl_read(data, conn->sockfd, buf, bytestoread, &nread);
  427. if(CURLE_AGAIN == result) {
  428. result = CURLE_OK;
  429. break; /* get out of loop */
  430. }
  431. else if(result)
  432. goto out;
  433. DEBUGASSERT(nread >= 0);
  434. blen = (size_t)nread;
  435. }
  436. else {
  437. /* read nothing but since we wanted nothing we consider this an OK
  438. situation to proceed from */
  439. DEBUGF(infof(data, "readwrite_data: we're done"));
  440. }
  441. if(!k->bytecount) {
  442. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  443. if(k->exp100 > EXP100_SEND_DATA)
  444. /* set time stamp to compare with when waiting for the 100 */
  445. k->start100 = Curl_now();
  446. }
  447. *didwhat |= KEEP_RECV;
  448. /* indicates data of zero size, i.e. empty file */
  449. is_empty_data = ((blen == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
  450. if(0 < blen || is_empty_data) {
  451. /* data->state.buffer is allocated 1 byte larger than
  452. * data->set.buffer_size admits. *wink* */
  453. /* TODO: we should really not rely on this being 0-terminated, since
  454. * the actual data read might contain 0s. */
  455. buf[blen] = 0;
  456. }
  457. if(!blen) {
  458. /* if we receive 0 or less here, either the data transfer is done or the
  459. server closed the connection and we bail out from this! */
  460. if(data_eof_handled)
  461. DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
  462. else
  463. DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
  464. k->keepon = 0; /* stop sending as well */
  465. if(!is_empty_data)
  466. break;
  467. }
  468. if(conn->handler->readwrite) {
  469. bool readmore = FALSE; /* indicates data is incomplete, need more */
  470. consumed = 0;
  471. result = conn->handler->readwrite(data, conn, buf, blen,
  472. &consumed, &readmore);
  473. if(result)
  474. goto out;
  475. if(readmore)
  476. break;
  477. buf += consumed;
  478. blen -= consumed;
  479. if(k->download_done) {
  480. /* We've stopped dealing with input, get out of the do-while loop */
  481. if(blen > 0) {
  482. infof(data,
  483. "Excess found:"
  484. " excess = %zu"
  485. " url = %s (zero-length body)",
  486. blen, data->state.up.path);
  487. }
  488. /* we make sure that this socket isn't read more now */
  489. k->keepon &= ~KEEP_RECV;
  490. break;
  491. }
  492. }
  493. #ifndef CURL_DISABLE_HTTP
  494. /* Since this is a two-state thing, we check if we are parsing
  495. headers at the moment or not. */
  496. if(k->header) {
  497. consumed = 0;
  498. result = Curl_http_readwrite_headers(data, conn, buf, blen, &consumed);
  499. if(result)
  500. goto out;
  501. buf += consumed;
  502. blen -= consumed;
  503. if(conn->handler->readwrite &&
  504. (k->maxdownload <= 0 && blen > 0)) {
  505. bool readmore = FALSE; /* indicates data is incomplete, need more */
  506. consumed = 0;
  507. result = conn->handler->readwrite(data, conn, buf, blen,
  508. &consumed, &readmore);
  509. if(result)
  510. goto out;
  511. if(readmore)
  512. break;
  513. buf += consumed;
  514. blen -= consumed;
  515. }
  516. if(k->download_done) {
  517. /* We've stopped dealing with input, get out of the do-while loop */
  518. if(blen > 0) {
  519. infof(data,
  520. "Excess found:"
  521. " excess = %zu"
  522. " url = %s (zero-length body)",
  523. blen, data->state.up.path);
  524. }
  525. /* we make sure that this socket isn't read more now */
  526. k->keepon &= ~KEEP_RECV;
  527. break;
  528. }
  529. }
  530. #endif /* CURL_DISABLE_HTTP */
  531. /* This is not an 'else if' since it may be a rest from the header
  532. parsing, where the beginning of the buffer is headers and the end
  533. is non-headers. */
  534. if(!k->header && (blen > 0 || is_empty_data)) {
  535. if(data->req.no_body && blen > 0) {
  536. /* data arrives although we want none, bail out */
  537. streamclose(conn, "ignoring body");
  538. DEBUGF(infof(data, "did not want a BODY, but seeing %zu bytes",
  539. blen));
  540. *done = TRUE;
  541. result = CURLE_WEIRD_SERVER_REPLY;
  542. goto out;
  543. }
  544. #ifndef CURL_DISABLE_HTTP
  545. if(0 == k->bodywrites && !is_empty_data) {
  546. /* These checks are only made the first time we are about to
  547. write a piece of the body */
  548. if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
  549. /* HTTP-only checks */
  550. result = Curl_http_firstwrite(data, conn, done);
  551. if(result || *done)
  552. goto out;
  553. }
  554. } /* this is the first time we write a body part */
  555. #endif /* CURL_DISABLE_HTTP */
  556. #ifndef CURL_DISABLE_HTTP
  557. if(k->chunk) {
  558. /*
  559. * Here comes a chunked transfer flying and we need to decode this
  560. * properly. While the name says read, this function both reads
  561. * and writes away the data.
  562. */
  563. CURLcode extra;
  564. CHUNKcode res;
  565. consumed = 0;
  566. res = Curl_httpchunk_read(data, buf, blen, &consumed, &extra);
  567. if(CHUNKE_OK < res) {
  568. if(CHUNKE_PASSTHRU_ERROR == res) {
  569. failf(data, "Failed reading the chunked-encoded stream");
  570. result = extra;
  571. goto out;
  572. }
  573. failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res));
  574. result = CURLE_RECV_ERROR;
  575. goto out;
  576. }
  577. buf += consumed;
  578. blen -= consumed;
  579. if(CHUNKE_STOP == res) {
  580. /* we're done reading chunks! */
  581. k->keepon &= ~KEEP_RECV; /* read no more */
  582. /* chunks read successfully, download is complete */
  583. k->download_done = TRUE;
  584. /* N number of bytes at the end of the str buffer that weren't
  585. written to the client. */
  586. if(conn->chunk.datasize) {
  587. infof(data, "Leftovers after chunking: % "
  588. CURL_FORMAT_CURL_OFF_T "u bytes",
  589. conn->chunk.datasize);
  590. }
  591. }
  592. /* If it returned OK, we just keep going */
  593. }
  594. #endif /* CURL_DISABLE_HTTP */
  595. max_recv -= blen;
  596. if(!k->chunk && (blen || k->badheader || is_empty_data)) {
  597. /* If this is chunky transfer, it was already written */
  598. if(k->badheader) {
  599. /* we parsed a piece of data wrongly assuming it was a header
  600. and now we output it as body instead */
  601. size_t headlen = Curl_dyn_len(&data->state.headerb);
  602. /* Don't let excess data pollute body writes */
  603. if(k->maxdownload != -1 && (curl_off_t)headlen > k->maxdownload)
  604. headlen = (size_t)k->maxdownload;
  605. result = Curl_client_write(data, CLIENTWRITE_BODY,
  606. Curl_dyn_ptr(&data->state.headerb),
  607. headlen);
  608. if(result)
  609. goto out;
  610. }
  611. if(blen) {
  612. #ifndef CURL_DISABLE_POP3
  613. if(conn->handler->protocol & PROTO_FAMILY_POP3) {
  614. result = k->ignorebody? CURLE_OK :
  615. Curl_pop3_write(data, buf, blen);
  616. }
  617. else
  618. #endif /* CURL_DISABLE_POP3 */
  619. result = Curl_client_write(data, CLIENTWRITE_BODY, buf, blen);
  620. }
  621. k->badheader = FALSE; /* taken care of now */
  622. if(result)
  623. goto out;
  624. }
  625. if(k->download_done && !is_http3) {
  626. /* HTTP/3 over QUIC should keep reading until QUIC connection
  627. is closed. In contrast to HTTP/2 which can stop reading
  628. from TCP connection, HTTP/3 over QUIC needs ACK from server
  629. to ensure stream closure. It should keep reading. */
  630. k->keepon &= ~KEEP_RECV; /* we're done reading */
  631. }
  632. } /* if(!header and data to read) */
  633. if(is_empty_data) {
  634. /* if we received nothing, the server closed the connection and we
  635. are done */
  636. k->keepon &= ~KEEP_RECV;
  637. k->download_done = TRUE;
  638. }
  639. if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV)) {
  640. /* this is a paused or stopped transfer */
  641. break;
  642. }
  643. } while((max_recv > 0) && data_pending(data) && maxloops--);
  644. if(maxloops <= 0 || max_recv <= 0) {
  645. /* we mark it as read-again-please */
  646. data->state.dselect_bits = CURL_CSELECT_IN;
  647. *comeback = TRUE;
  648. }
  649. if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
  650. (conn->bits.close || data_eof_handled)) {
  651. /* When we've read the entire thing and the close bit is set, the server
  652. may now close the connection. If there's now any kind of sending going
  653. on from our side, we need to stop that immediately. */
  654. infof(data, "we are done reading and this is set to close, stop send");
  655. k->keepon &= ~KEEP_SEND; /* no writing anymore either */
  656. k->keepon &= ~KEEP_SEND_PAUSE; /* no pausing anymore either */
  657. }
  658. out:
  659. if(result)
  660. DEBUGF(infof(data, "readwrite_data() -> %d", result));
  661. return result;
  662. }
  663. CURLcode Curl_done_sending(struct Curl_easy *data,
  664. struct SingleRequest *k)
  665. {
  666. k->keepon &= ~KEEP_SEND; /* we're done writing */
  667. /* These functions should be moved into the handler struct! */
  668. Curl_conn_ev_data_done_send(data);
  669. return CURLE_OK;
  670. }
  671. #if defined(_WIN32) && defined(USE_WINSOCK)
  672. #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
  673. #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
  674. #endif
  675. static void win_update_buffer_size(curl_socket_t sockfd)
  676. {
  677. int result;
  678. ULONG ideal;
  679. DWORD ideallen;
  680. result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
  681. &ideal, sizeof(ideal), &ideallen, 0, 0);
  682. if(result == 0) {
  683. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
  684. (const char *)&ideal, sizeof(ideal));
  685. }
  686. }
  687. #else
  688. #define win_update_buffer_size(x)
  689. #endif
  690. #define curl_upload_refill_watermark(data) \
  691. ((ssize_t)((data)->set.upload_buffer_size >> 5))
  692. /*
  693. * Send data to upload to the server, when the socket is writable.
  694. */
  695. static CURLcode readwrite_upload(struct Curl_easy *data,
  696. struct connectdata *conn,
  697. int *didwhat)
  698. {
  699. ssize_t i, si;
  700. ssize_t bytes_written;
  701. CURLcode result;
  702. ssize_t nread; /* number of bytes read */
  703. bool sending_http_headers = FALSE;
  704. struct SingleRequest *k = &data->req;
  705. *didwhat |= KEEP_SEND;
  706. do {
  707. curl_off_t nbody;
  708. ssize_t offset = 0;
  709. if(0 != k->upload_present &&
  710. k->upload_present < curl_upload_refill_watermark(data) &&
  711. !k->upload_chunky &&/*(variable sized chunked header; append not safe)*/
  712. !k->upload_done && /*!(k->upload_done once k->upload_present sent)*/
  713. !(k->writebytecount + k->upload_present - k->pendingheader ==
  714. data->state.infilesize)) {
  715. offset = k->upload_present;
  716. }
  717. /* only read more data if there's no upload data already
  718. present in the upload buffer, or if appending to upload buffer */
  719. if(0 == k->upload_present || offset) {
  720. result = Curl_get_upload_buffer(data);
  721. if(result)
  722. return result;
  723. if(offset && k->upload_fromhere != data->state.ulbuf)
  724. memmove(data->state.ulbuf, k->upload_fromhere, offset);
  725. /* init the "upload from here" pointer */
  726. k->upload_fromhere = data->state.ulbuf;
  727. if(!k->upload_done) {
  728. /* HTTP pollution, this should be written nicer to become more
  729. protocol agnostic. */
  730. size_t fillcount;
  731. struct HTTP *http = k->p.http;
  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_now(); /* 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, EXPIRE_100_TIMEOUT);
  743. break;
  744. }
  745. if(conn->handler->protocol&(PROTO_FAMILY_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. k->upload_fromhere += offset;
  754. result = Curl_fillreadbuffer(data, data->set.upload_buffer_size-offset,
  755. &fillcount);
  756. k->upload_fromhere -= offset;
  757. if(result)
  758. return result;
  759. nread = offset + fillcount;
  760. }
  761. else
  762. nread = 0; /* we're done uploading/reading */
  763. if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
  764. /* this is a paused transfer */
  765. break;
  766. }
  767. if(nread <= 0) {
  768. result = Curl_done_sending(data, k);
  769. if(result)
  770. return result;
  771. break;
  772. }
  773. /* store number of bytes available for upload */
  774. k->upload_present = nread;
  775. /* convert LF to CRLF if so asked */
  776. if((!sending_http_headers) && (
  777. #ifdef CURL_DO_LINEEND_CONV
  778. /* always convert if we're FTPing in ASCII mode */
  779. (data->state.prefer_ascii) ||
  780. #endif
  781. (data->set.crlf))) {
  782. /* Do we need to allocate a scratch buffer? */
  783. if(!data->state.scratch) {
  784. data->state.scratch = malloc(2 * data->set.upload_buffer_size);
  785. if(!data->state.scratch) {
  786. failf(data, "Failed to alloc scratch buffer");
  787. return CURLE_OUT_OF_MEMORY;
  788. }
  789. }
  790. /*
  791. * ASCII/EBCDIC Note: This is presumably a text (not binary)
  792. * transfer so the data should already be in ASCII.
  793. * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
  794. * must be used instead of the escape sequences \r & \n.
  795. */
  796. if(offset)
  797. memcpy(data->state.scratch, k->upload_fromhere, offset);
  798. for(i = offset, si = offset; i < nread; i++, si++) {
  799. if(k->upload_fromhere[i] == 0x0a) {
  800. data->state.scratch[si++] = 0x0d;
  801. data->state.scratch[si] = 0x0a;
  802. if(!data->set.crlf) {
  803. /* we're here only because FTP is in ASCII mode...
  804. bump infilesize for the LF we just added */
  805. if(data->state.infilesize != -1)
  806. data->state.infilesize++;
  807. }
  808. }
  809. else
  810. data->state.scratch[si] = k->upload_fromhere[i];
  811. }
  812. if(si != nread) {
  813. /* only perform the special operation if we really did replace
  814. anything */
  815. nread = si;
  816. /* upload from the new (replaced) buffer instead */
  817. k->upload_fromhere = data->state.scratch;
  818. /* set the new amount too */
  819. k->upload_present = nread;
  820. }
  821. }
  822. #ifndef CURL_DISABLE_SMTP
  823. if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
  824. result = Curl_smtp_escape_eob(data, nread, offset);
  825. if(result)
  826. return result;
  827. }
  828. #endif /* CURL_DISABLE_SMTP */
  829. } /* if 0 == k->upload_present or appended to upload buffer */
  830. else {
  831. /* We have a partial buffer left from a previous "round". Use
  832. that instead of reading more data */
  833. }
  834. /* write to socket (send away data) */
  835. result = Curl_write(data,
  836. conn->writesockfd, /* socket to send to */
  837. k->upload_fromhere, /* buffer pointer */
  838. k->upload_present, /* buffer size */
  839. &bytes_written); /* actually sent */
  840. if(result)
  841. return result;
  842. #if defined(_WIN32) && defined(USE_WINSOCK)
  843. {
  844. struct curltime n = Curl_now();
  845. if(Curl_timediff(n, k->last_sndbuf_update) > 1000) {
  846. win_update_buffer_size(conn->writesockfd);
  847. k->last_sndbuf_update = n;
  848. }
  849. }
  850. #endif
  851. if(k->pendingheader) {
  852. /* parts of what was sent was header */
  853. curl_off_t n = CURLMIN(k->pendingheader, bytes_written);
  854. /* show the data before we change the pointer upload_fromhere */
  855. Curl_debug(data, CURLINFO_HEADER_OUT, k->upload_fromhere, (size_t)n);
  856. k->pendingheader -= n;
  857. nbody = bytes_written - n; /* size of the written body part */
  858. }
  859. else
  860. nbody = bytes_written;
  861. if(nbody) {
  862. /* show the data before we change the pointer upload_fromhere */
  863. Curl_debug(data, CURLINFO_DATA_OUT,
  864. &k->upload_fromhere[bytes_written - nbody],
  865. (size_t)nbody);
  866. k->writebytecount += nbody;
  867. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  868. }
  869. if((!k->upload_chunky || k->forbidchunk) &&
  870. (k->writebytecount == data->state.infilesize)) {
  871. /* we have sent all data we were supposed to */
  872. k->upload_done = TRUE;
  873. infof(data, "We are completely uploaded and fine");
  874. }
  875. if(k->upload_present != bytes_written) {
  876. /* we only wrote a part of the buffer (if anything), deal with it! */
  877. /* store the amount of bytes left in the buffer to write */
  878. k->upload_present -= bytes_written;
  879. /* advance the pointer where to find the buffer when the next send
  880. is to happen */
  881. k->upload_fromhere += bytes_written;
  882. }
  883. else {
  884. /* we've uploaded that buffer now */
  885. result = Curl_get_upload_buffer(data);
  886. if(result)
  887. return result;
  888. k->upload_fromhere = data->state.ulbuf;
  889. k->upload_present = 0; /* no more bytes left */
  890. if(k->upload_done) {
  891. result = Curl_done_sending(data, k);
  892. if(result)
  893. return result;
  894. }
  895. }
  896. } while(0); /* just to break out from! */
  897. return CURLE_OK;
  898. }
  899. static int select_bits_paused(struct Curl_easy *data, int select_bits)
  900. {
  901. /* See issue #11982: we really need to be careful not to progress
  902. * a transfer direction when that direction is paused. Not all parts
  903. * of our state machine are handling PAUSED transfers correctly. So, we
  904. * do not want to go there.
  905. * NOTE: we are only interested in PAUSE, not HOLD. */
  906. return (((select_bits & CURL_CSELECT_IN) &&
  907. (data->req.keepon & KEEP_RECV_PAUSE)) ||
  908. ((select_bits & CURL_CSELECT_OUT) &&
  909. (data->req.keepon & KEEP_SEND_PAUSE)));
  910. }
  911. /*
  912. * Curl_readwrite() is the low-level function to be called when data is to
  913. * be read and written to/from the connection.
  914. *
  915. * return '*comeback' TRUE if we didn't properly drain the socket so this
  916. * function should get called again without select() or similar in between!
  917. */
  918. CURLcode Curl_readwrite(struct connectdata *conn,
  919. struct Curl_easy *data,
  920. bool *done,
  921. bool *comeback)
  922. {
  923. struct SingleRequest *k = &data->req;
  924. CURLcode result;
  925. struct curltime now;
  926. int didwhat = 0;
  927. int select_bits;
  928. if(data->state.dselect_bits) {
  929. if(select_bits_paused(data, data->state.dselect_bits)) {
  930. /* leave the bits unchanged, so they'll tell us what to do when
  931. * this transfer gets unpaused. */
  932. DEBUGF(infof(data, "readwrite, dselect_bits, early return on PAUSED"));
  933. result = CURLE_OK;
  934. goto out;
  935. }
  936. select_bits = data->state.dselect_bits;
  937. data->state.dselect_bits = 0;
  938. }
  939. else if(conn->cselect_bits) {
  940. /* CAVEAT: adding `select_bits_paused()` check here makes test640 hang
  941. * (among others). Which hints at strange state handling in FTP land... */
  942. select_bits = conn->cselect_bits;
  943. conn->cselect_bits = 0;
  944. }
  945. else {
  946. curl_socket_t fd_read;
  947. curl_socket_t fd_write;
  948. /* only use the proper socket if the *_HOLD bit is not set simultaneously
  949. as then we are in rate limiting state in that transfer direction */
  950. if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
  951. fd_read = conn->sockfd;
  952. else
  953. fd_read = CURL_SOCKET_BAD;
  954. if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
  955. fd_write = conn->writesockfd;
  956. else
  957. fd_write = CURL_SOCKET_BAD;
  958. select_bits = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
  959. }
  960. if(select_bits == CURL_CSELECT_ERR) {
  961. failf(data, "select/poll returned error");
  962. result = CURLE_SEND_ERROR;
  963. goto out;
  964. }
  965. #ifdef USE_HYPER
  966. if(conn->datastream) {
  967. result = conn->datastream(data, conn, &didwhat, done, select_bits);
  968. if(result || *done)
  969. goto out;
  970. }
  971. else {
  972. #endif
  973. /* We go ahead and do a read if we have a readable socket or if
  974. the stream was rewound (in which case we have data in a
  975. buffer) */
  976. if((k->keepon & KEEP_RECV) && (select_bits & CURL_CSELECT_IN)) {
  977. result = readwrite_data(data, conn, k, &didwhat, done, comeback);
  978. if(result || *done)
  979. goto out;
  980. }
  981. /* If we still have writing to do, we check if we have a writable socket. */
  982. if((k->keepon & KEEP_SEND) && (select_bits & CURL_CSELECT_OUT)) {
  983. /* write */
  984. result = readwrite_upload(data, conn, &didwhat);
  985. if(result)
  986. goto out;
  987. }
  988. #ifdef USE_HYPER
  989. }
  990. #endif
  991. now = Curl_now();
  992. if(!didwhat) {
  993. /* no read no write, this is a timeout? */
  994. if(k->exp100 == EXP100_AWAITING_CONTINUE) {
  995. /* This should allow some time for the header to arrive, but only a
  996. very short time as otherwise it'll be too much wasted time too
  997. often. */
  998. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  999. Therefore, when a client sends this header field to an origin server
  1000. (possibly via a proxy) from which it has never seen a 100 (Continue)
  1001. status, the client SHOULD NOT wait for an indefinite period before
  1002. sending the request body.
  1003. */
  1004. timediff_t ms = Curl_timediff(now, k->start100);
  1005. if(ms >= data->set.expect_100_timeout) {
  1006. /* we've waited long enough, continue anyway */
  1007. k->exp100 = EXP100_SEND_DATA;
  1008. k->keepon |= KEEP_SEND;
  1009. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  1010. infof(data, "Done waiting for 100-continue");
  1011. }
  1012. }
  1013. result = Curl_conn_ev_data_idle(data);
  1014. if(result)
  1015. goto out;
  1016. }
  1017. if(Curl_pgrsUpdate(data))
  1018. result = CURLE_ABORTED_BY_CALLBACK;
  1019. else
  1020. result = Curl_speedcheck(data, now);
  1021. if(result)
  1022. goto out;
  1023. if(k->keepon) {
  1024. if(0 > Curl_timeleft(data, &now, FALSE)) {
  1025. if(k->size != -1) {
  1026. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1027. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
  1028. CURL_FORMAT_CURL_OFF_T " bytes received",
  1029. Curl_timediff(now, data->progress.t_startsingle),
  1030. k->bytecount, k->size);
  1031. }
  1032. else {
  1033. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1034. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received",
  1035. Curl_timediff(now, data->progress.t_startsingle),
  1036. k->bytecount);
  1037. }
  1038. result = CURLE_OPERATION_TIMEDOUT;
  1039. goto out;
  1040. }
  1041. }
  1042. else {
  1043. /*
  1044. * The transfer has been performed. Just make some general checks before
  1045. * returning.
  1046. */
  1047. if(!(data->req.no_body) && (k->size != -1) &&
  1048. (k->bytecount != k->size) &&
  1049. #ifdef CURL_DO_LINEEND_CONV
  1050. /* Most FTP servers don't adjust their file SIZE response for CRLFs,
  1051. so we'll check to see if the discrepancy can be explained
  1052. by the number of CRLFs we've changed to LFs.
  1053. */
  1054. (k->bytecount != (k->size + data->state.crlf_conversions)) &&
  1055. #endif /* CURL_DO_LINEEND_CONV */
  1056. !k->newurl) {
  1057. failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
  1058. " bytes remaining to read", k->size - k->bytecount);
  1059. result = CURLE_PARTIAL_FILE;
  1060. goto out;
  1061. }
  1062. if(!(data->req.no_body) && k->chunk &&
  1063. (conn->chunk.state != CHUNK_STOP)) {
  1064. /*
  1065. * In chunked mode, return an error if the connection is closed prior to
  1066. * the empty (terminating) chunk is read.
  1067. *
  1068. * The condition above used to check for
  1069. * conn->proto.http->chunk.datasize != 0 which is true after reading
  1070. * *any* chunk, not just the empty chunk.
  1071. *
  1072. */
  1073. failf(data, "transfer closed with outstanding read data remaining");
  1074. result = CURLE_PARTIAL_FILE;
  1075. goto out;
  1076. }
  1077. if(Curl_pgrsUpdate(data)) {
  1078. result = CURLE_ABORTED_BY_CALLBACK;
  1079. goto out;
  1080. }
  1081. }
  1082. /* Now update the "done" boolean we return */
  1083. *done = (0 == (k->keepon&(KEEP_RECVBITS|KEEP_SENDBITS))) ? TRUE : FALSE;
  1084. out:
  1085. if(result)
  1086. DEBUGF(infof(data, "Curl_readwrite() -> %d", result));
  1087. return result;
  1088. }
  1089. /*
  1090. * Curl_single_getsock() gets called by the multi interface code when the app
  1091. * has requested to get the sockets for the current connection. This function
  1092. * will then be called once for every connection that the multi interface
  1093. * keeps track of. This function will only be called for connections that are
  1094. * in the proper state to have this information available.
  1095. */
  1096. int Curl_single_getsock(struct Curl_easy *data,
  1097. struct connectdata *conn,
  1098. curl_socket_t *sock)
  1099. {
  1100. int bitmap = GETSOCK_BLANK;
  1101. unsigned sockindex = 0;
  1102. if(conn->handler->perform_getsock)
  1103. return conn->handler->perform_getsock(data, conn, sock);
  1104. /* don't include HOLD and PAUSE connections */
  1105. if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
  1106. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1107. bitmap |= GETSOCK_READSOCK(sockindex);
  1108. sock[sockindex] = conn->sockfd;
  1109. }
  1110. /* don't include HOLD and PAUSE connections */
  1111. if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
  1112. if((conn->sockfd != conn->writesockfd) ||
  1113. bitmap == GETSOCK_BLANK) {
  1114. /* only if they are not the same socket and we have a readable
  1115. one, we increase index */
  1116. if(bitmap != GETSOCK_BLANK)
  1117. sockindex++; /* increase index if we need two entries */
  1118. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1119. sock[sockindex] = conn->writesockfd;
  1120. }
  1121. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1122. }
  1123. return bitmap;
  1124. }
  1125. /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
  1126. which means this gets called once for each subsequent redirect etc */
  1127. void Curl_init_CONNECT(struct Curl_easy *data)
  1128. {
  1129. data->state.fread_func = data->set.fread_func_set;
  1130. data->state.in = data->set.in_set;
  1131. data->state.upload = (data->state.httpreq == HTTPREQ_PUT);
  1132. }
  1133. /*
  1134. * Curl_pretransfer() is called immediately before a transfer starts, and only
  1135. * once for one transfer no matter if it has redirects or do multi-pass
  1136. * authentication etc.
  1137. */
  1138. CURLcode Curl_pretransfer(struct Curl_easy *data)
  1139. {
  1140. CURLcode result;
  1141. if(!data->state.url && !data->set.uh) {
  1142. /* we can't do anything without URL */
  1143. failf(data, "No URL set");
  1144. return CURLE_URL_MALFORMAT;
  1145. }
  1146. /* since the URL may have been redirected in a previous use of this handle */
  1147. if(data->state.url_alloc) {
  1148. /* the already set URL is allocated, free it first! */
  1149. Curl_safefree(data->state.url);
  1150. data->state.url_alloc = FALSE;
  1151. }
  1152. if(!data->state.url && data->set.uh) {
  1153. CURLUcode uc;
  1154. free(data->set.str[STRING_SET_URL]);
  1155. uc = curl_url_get(data->set.uh,
  1156. CURLUPART_URL, &data->set.str[STRING_SET_URL], 0);
  1157. if(uc) {
  1158. failf(data, "No URL set");
  1159. return CURLE_URL_MALFORMAT;
  1160. }
  1161. }
  1162. if(data->set.postfields && data->set.set_resume_from) {
  1163. /* we can't */
  1164. failf(data, "cannot mix POSTFIELDS with RESUME_FROM");
  1165. return CURLE_BAD_FUNCTION_ARGUMENT;
  1166. }
  1167. data->state.prefer_ascii = data->set.prefer_ascii;
  1168. #ifdef CURL_LIST_ONLY_PROTOCOL
  1169. data->state.list_only = data->set.list_only;
  1170. #endif
  1171. data->state.httpreq = data->set.method;
  1172. data->state.url = data->set.str[STRING_SET_URL];
  1173. /* Init the SSL session ID cache here. We do it here since we want to do it
  1174. after the *_setopt() calls (that could specify the size of the cache) but
  1175. before any transfer takes place. */
  1176. result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
  1177. if(result)
  1178. return result;
  1179. data->state.requests = 0;
  1180. data->state.followlocation = 0; /* reset the location-follow counter */
  1181. data->state.this_is_a_follow = FALSE; /* reset this */
  1182. data->state.errorbuf = FALSE; /* no error has occurred */
  1183. data->state.httpwant = data->set.httpwant;
  1184. data->state.httpversion = 0;
  1185. data->state.authproblem = FALSE;
  1186. data->state.authhost.want = data->set.httpauth;
  1187. data->state.authproxy.want = data->set.proxyauth;
  1188. Curl_safefree(data->info.wouldredirect);
  1189. Curl_data_priority_clear_state(data);
  1190. if(data->state.httpreq == HTTPREQ_PUT)
  1191. data->state.infilesize = data->set.filesize;
  1192. else if((data->state.httpreq != HTTPREQ_GET) &&
  1193. (data->state.httpreq != HTTPREQ_HEAD)) {
  1194. data->state.infilesize = data->set.postfieldsize;
  1195. if(data->set.postfields && (data->state.infilesize == -1))
  1196. data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
  1197. }
  1198. else
  1199. data->state.infilesize = 0;
  1200. /* If there is a list of cookie files to read, do it now! */
  1201. Curl_cookie_loadfiles(data);
  1202. /* If there is a list of host pairs to deal with */
  1203. if(data->state.resolve)
  1204. result = Curl_loadhostpairs(data);
  1205. /* If there is a list of hsts files to read */
  1206. Curl_hsts_loadfiles(data);
  1207. if(!result) {
  1208. /* Allow data->set.use_port to set which port to use. This needs to be
  1209. * disabled for example when we follow Location: headers to URLs using
  1210. * different ports! */
  1211. data->state.allow_port = TRUE;
  1212. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1213. /*************************************************************
  1214. * Tell signal handler to ignore SIGPIPE
  1215. *************************************************************/
  1216. if(!data->set.no_signal)
  1217. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1218. #endif
  1219. Curl_initinfo(data); /* reset session-specific information "variables" */
  1220. Curl_pgrsResetTransferSizes(data);
  1221. Curl_pgrsStartNow(data);
  1222. /* In case the handle is reused and an authentication method was picked
  1223. in the session we need to make sure we only use the one(s) we now
  1224. consider to be fine */
  1225. data->state.authhost.picked &= data->state.authhost.want;
  1226. data->state.authproxy.picked &= data->state.authproxy.want;
  1227. #ifndef CURL_DISABLE_FTP
  1228. data->state.wildcardmatch = data->set.wildcard_enabled;
  1229. if(data->state.wildcardmatch) {
  1230. struct WildcardData *wc;
  1231. if(!data->wildcard) {
  1232. data->wildcard = calloc(1, sizeof(struct WildcardData));
  1233. if(!data->wildcard)
  1234. return CURLE_OUT_OF_MEMORY;
  1235. }
  1236. wc = data->wildcard;
  1237. if(wc->state < CURLWC_INIT) {
  1238. if(wc->ftpwc)
  1239. wc->dtor(wc->ftpwc);
  1240. Curl_safefree(wc->pattern);
  1241. Curl_safefree(wc->path);
  1242. result = Curl_wildcard_init(wc); /* init wildcard structures */
  1243. if(result)
  1244. return CURLE_OUT_OF_MEMORY;
  1245. }
  1246. }
  1247. #endif
  1248. result = Curl_hsts_loadcb(data, data->hsts);
  1249. }
  1250. /*
  1251. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  1252. * basically anything through an HTTP proxy we can't limit this based on
  1253. * protocol.
  1254. */
  1255. if(data->set.str[STRING_USERAGENT]) {
  1256. Curl_safefree(data->state.aptr.uagent);
  1257. data->state.aptr.uagent =
  1258. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  1259. if(!data->state.aptr.uagent)
  1260. return CURLE_OUT_OF_MEMORY;
  1261. }
  1262. if(!result)
  1263. result = Curl_setstropt(&data->state.aptr.user,
  1264. data->set.str[STRING_USERNAME]);
  1265. if(!result)
  1266. result = Curl_setstropt(&data->state.aptr.passwd,
  1267. data->set.str[STRING_PASSWORD]);
  1268. if(!result)
  1269. result = Curl_setstropt(&data->state.aptr.proxyuser,
  1270. data->set.str[STRING_PROXYUSERNAME]);
  1271. if(!result)
  1272. result = Curl_setstropt(&data->state.aptr.proxypasswd,
  1273. data->set.str[STRING_PROXYPASSWORD]);
  1274. data->req.headerbytecount = 0;
  1275. Curl_headers_cleanup(data);
  1276. return result;
  1277. }
  1278. /*
  1279. * Curl_posttransfer() is called immediately after a transfer ends
  1280. */
  1281. CURLcode Curl_posttransfer(struct Curl_easy *data)
  1282. {
  1283. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1284. /* restore the signal handler for SIGPIPE before we get back */
  1285. if(!data->set.no_signal)
  1286. signal(SIGPIPE, data->state.prev_signal);
  1287. #else
  1288. (void)data; /* unused parameter */
  1289. #endif
  1290. return CURLE_OK;
  1291. }
  1292. /*
  1293. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1294. * as given by the remote server and set up the new URL to request.
  1295. *
  1296. * This function DOES NOT FREE the given url.
  1297. */
  1298. CURLcode Curl_follow(struct Curl_easy *data,
  1299. char *newurl, /* the Location: string */
  1300. followtype type) /* see transfer.h */
  1301. {
  1302. #ifdef CURL_DISABLE_HTTP
  1303. (void)data;
  1304. (void)newurl;
  1305. (void)type;
  1306. /* Location: following will not happen when HTTP is disabled */
  1307. return CURLE_TOO_MANY_REDIRECTS;
  1308. #else
  1309. /* Location: redirect */
  1310. bool disallowport = FALSE;
  1311. bool reachedmax = FALSE;
  1312. CURLUcode uc;
  1313. DEBUGASSERT(type != FOLLOW_NONE);
  1314. if(type != FOLLOW_FAKE)
  1315. data->state.requests++; /* count all real follows */
  1316. if(type == FOLLOW_REDIR) {
  1317. if((data->set.maxredirs != -1) &&
  1318. (data->state.followlocation >= data->set.maxredirs)) {
  1319. reachedmax = TRUE;
  1320. type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
  1321. to URL */
  1322. }
  1323. else {
  1324. data->state.followlocation++; /* count redirect-followings, including
  1325. auth reloads */
  1326. if(data->set.http_auto_referer) {
  1327. CURLU *u;
  1328. char *referer = NULL;
  1329. /* We are asked to automatically set the previous URL as the referer
  1330. when we get the next URL. We pick the ->url field, which may or may
  1331. not be 100% correct */
  1332. if(data->state.referer_alloc) {
  1333. Curl_safefree(data->state.referer);
  1334. data->state.referer_alloc = FALSE;
  1335. }
  1336. /* Make a copy of the URL without credentials and fragment */
  1337. u = curl_url();
  1338. if(!u)
  1339. return CURLE_OUT_OF_MEMORY;
  1340. uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
  1341. if(!uc)
  1342. uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
  1343. if(!uc)
  1344. uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
  1345. if(!uc)
  1346. uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
  1347. if(!uc)
  1348. uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
  1349. curl_url_cleanup(u);
  1350. if(uc || !referer)
  1351. return CURLE_OUT_OF_MEMORY;
  1352. data->state.referer = referer;
  1353. data->state.referer_alloc = TRUE; /* yes, free this later */
  1354. }
  1355. }
  1356. }
  1357. if((type != FOLLOW_RETRY) &&
  1358. (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
  1359. Curl_is_absolute_url(newurl, NULL, 0, FALSE)) {
  1360. /* If this is not redirect due to a 401 or 407 response and an absolute
  1361. URL: don't allow a custom port number */
  1362. disallowport = TRUE;
  1363. }
  1364. DEBUGASSERT(data->state.uh);
  1365. uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
  1366. (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
  1367. ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
  1368. CURLU_ALLOW_SPACE |
  1369. (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
  1370. if(uc) {
  1371. if(type != FOLLOW_FAKE) {
  1372. failf(data, "The redirect target URL could not be parsed: %s",
  1373. curl_url_strerror(uc));
  1374. return Curl_uc_to_curlcode(uc);
  1375. }
  1376. /* the URL could not be parsed for some reason, but since this is FAKE
  1377. mode, just duplicate the field as-is */
  1378. newurl = strdup(newurl);
  1379. if(!newurl)
  1380. return CURLE_OUT_OF_MEMORY;
  1381. }
  1382. else {
  1383. uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
  1384. if(uc)
  1385. return Curl_uc_to_curlcode(uc);
  1386. /* Clear auth if this redirects to a different port number or protocol,
  1387. unless permitted */
  1388. if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
  1389. char *portnum;
  1390. int port;
  1391. bool clear = FALSE;
  1392. if(data->set.use_port && data->state.allow_port)
  1393. /* a custom port is used */
  1394. port = (int)data->set.use_port;
  1395. else {
  1396. uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
  1397. CURLU_DEFAULT_PORT);
  1398. if(uc) {
  1399. free(newurl);
  1400. return Curl_uc_to_curlcode(uc);
  1401. }
  1402. port = atoi(portnum);
  1403. free(portnum);
  1404. }
  1405. if(port != data->info.conn_remote_port) {
  1406. infof(data, "Clear auth, redirects to port from %u to %u",
  1407. data->info.conn_remote_port, port);
  1408. clear = TRUE;
  1409. }
  1410. else {
  1411. char *scheme;
  1412. const struct Curl_handler *p;
  1413. uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
  1414. if(uc) {
  1415. free(newurl);
  1416. return Curl_uc_to_curlcode(uc);
  1417. }
  1418. p = Curl_get_scheme_handler(scheme);
  1419. if(p && (p->protocol != data->info.conn_protocol)) {
  1420. infof(data, "Clear auth, redirects scheme from %s to %s",
  1421. data->info.conn_scheme, scheme);
  1422. clear = TRUE;
  1423. }
  1424. free(scheme);
  1425. }
  1426. if(clear) {
  1427. Curl_safefree(data->state.aptr.user);
  1428. Curl_safefree(data->state.aptr.passwd);
  1429. }
  1430. }
  1431. }
  1432. if(type == FOLLOW_FAKE) {
  1433. /* we're only figuring out the new url if we would've followed locations
  1434. but now we're done so we can get out! */
  1435. data->info.wouldredirect = newurl;
  1436. if(reachedmax) {
  1437. failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
  1438. return CURLE_TOO_MANY_REDIRECTS;
  1439. }
  1440. return CURLE_OK;
  1441. }
  1442. if(disallowport)
  1443. data->state.allow_port = FALSE;
  1444. if(data->state.url_alloc)
  1445. Curl_safefree(data->state.url);
  1446. data->state.url = newurl;
  1447. data->state.url_alloc = TRUE;
  1448. infof(data, "Issue another request to this URL: '%s'", data->state.url);
  1449. /*
  1450. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1451. * differently based on exactly what return code there was.
  1452. *
  1453. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1454. * an HTTP (proxy-) authentication scheme other than Basic.
  1455. */
  1456. switch(data->info.httpcode) {
  1457. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1458. Authorization: XXXX header in the HTTP request code snippet */
  1459. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1460. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1461. /* 300 - Multiple Choices */
  1462. /* 306 - Not used */
  1463. /* 307 - Temporary Redirect */
  1464. default: /* for all above (and the unknown ones) */
  1465. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1466. * seem to be OK to POST to.
  1467. */
  1468. break;
  1469. case 301: /* Moved Permanently */
  1470. /* (quote from RFC7231, section 6.4.2)
  1471. *
  1472. * Note: For historical reasons, a user agent MAY change the request
  1473. * method from POST to GET for the subsequent request. If this
  1474. * behavior is undesired, the 307 (Temporary Redirect) status code
  1475. * can be used instead.
  1476. *
  1477. * ----
  1478. *
  1479. * Many webservers expect this, so these servers often answers to a POST
  1480. * request with an error page. To be sure that libcurl gets the page that
  1481. * most user agents would get, libcurl has to force GET.
  1482. *
  1483. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1484. * can be overridden with CURLOPT_POSTREDIR.
  1485. */
  1486. if((data->state.httpreq == HTTPREQ_POST
  1487. || data->state.httpreq == HTTPREQ_POST_FORM
  1488. || data->state.httpreq == HTTPREQ_POST_MIME)
  1489. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1490. infof(data, "Switch from POST to GET");
  1491. data->state.httpreq = HTTPREQ_GET;
  1492. }
  1493. break;
  1494. case 302: /* Found */
  1495. /* (quote from RFC7231, section 6.4.3)
  1496. *
  1497. * Note: For historical reasons, a user agent MAY change the request
  1498. * method from POST to GET for the subsequent request. If this
  1499. * behavior is undesired, the 307 (Temporary Redirect) status code
  1500. * can be used instead.
  1501. *
  1502. * ----
  1503. *
  1504. * Many webservers expect this, so these servers often answers to a POST
  1505. * request with an error page. To be sure that libcurl gets the page that
  1506. * most user agents would get, libcurl has to force GET.
  1507. *
  1508. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1509. * can be overridden with CURLOPT_POSTREDIR.
  1510. */
  1511. if((data->state.httpreq == HTTPREQ_POST
  1512. || data->state.httpreq == HTTPREQ_POST_FORM
  1513. || data->state.httpreq == HTTPREQ_POST_MIME)
  1514. && !(data->set.keep_post & CURL_REDIR_POST_302)) {
  1515. infof(data, "Switch from POST to GET");
  1516. data->state.httpreq = HTTPREQ_GET;
  1517. }
  1518. break;
  1519. case 303: /* See Other */
  1520. /* 'See Other' location is not the resource but a substitute for the
  1521. * resource. In this case we switch the method to GET/HEAD, unless the
  1522. * method is POST and the user specified to keep it as POST.
  1523. * https://github.com/curl/curl/issues/5237#issuecomment-614641049
  1524. */
  1525. if(data->state.httpreq != HTTPREQ_GET &&
  1526. ((data->state.httpreq != HTTPREQ_POST &&
  1527. data->state.httpreq != HTTPREQ_POST_FORM &&
  1528. data->state.httpreq != HTTPREQ_POST_MIME) ||
  1529. !(data->set.keep_post & CURL_REDIR_POST_303))) {
  1530. data->state.httpreq = HTTPREQ_GET;
  1531. infof(data, "Switch to %s",
  1532. data->req.no_body?"HEAD":"GET");
  1533. }
  1534. break;
  1535. case 304: /* Not Modified */
  1536. /* 304 means we did a conditional request and it was "Not modified".
  1537. * We shouldn't get any Location: header in this response!
  1538. */
  1539. break;
  1540. case 305: /* Use Proxy */
  1541. /* (quote from RFC2616, section 10.3.6):
  1542. * "The requested resource MUST be accessed through the proxy given
  1543. * by the Location field. The Location field gives the URI of the
  1544. * proxy. The recipient is expected to repeat this single request
  1545. * via the proxy. 305 responses MUST only be generated by origin
  1546. * servers."
  1547. */
  1548. break;
  1549. }
  1550. Curl_pgrsTime(data, TIMER_REDIRECT);
  1551. Curl_pgrsResetTransferSizes(data);
  1552. return CURLE_OK;
  1553. #endif /* CURL_DISABLE_HTTP */
  1554. }
  1555. /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
  1556. NOTE: that the *url is malloc()ed. */
  1557. CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
  1558. {
  1559. struct connectdata *conn = data->conn;
  1560. bool retry = FALSE;
  1561. *url = NULL;
  1562. /* if we're talking upload, we can't do the checks below, unless the protocol
  1563. is HTTP as when uploading over HTTP we will still get a response */
  1564. if(data->state.upload &&
  1565. !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
  1566. return CURLE_OK;
  1567. if((data->req.bytecount + data->req.headerbytecount == 0) &&
  1568. conn->bits.reuse &&
  1569. (!data->req.no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP))
  1570. #ifndef CURL_DISABLE_RTSP
  1571. && (data->set.rtspreq != RTSPREQ_RECEIVE)
  1572. #endif
  1573. )
  1574. /* We got no data, we attempted to reuse a connection. For HTTP this
  1575. can be a retry so we try again regardless if we expected a body.
  1576. For other protocols we only try again only if we expected a body.
  1577. This might happen if the connection was left alive when we were
  1578. done using it before, but that was closed when we wanted to read from
  1579. it again. Bad luck. Retry the same request on a fresh connect! */
  1580. retry = TRUE;
  1581. else if(data->state.refused_stream &&
  1582. (data->req.bytecount + data->req.headerbytecount == 0) ) {
  1583. /* This was sent on a refused stream, safe to rerun. A refused stream
  1584. error can typically only happen on HTTP/2 level if the stream is safe
  1585. to issue again, but the nghttp2 API can deliver the message to other
  1586. streams as well, which is why this adds the check the data counters
  1587. too. */
  1588. infof(data, "REFUSED_STREAM, retrying a fresh connect");
  1589. data->state.refused_stream = FALSE; /* clear again */
  1590. retry = TRUE;
  1591. }
  1592. if(retry) {
  1593. #define CONN_MAX_RETRIES 5
  1594. if(data->state.retrycount++ >= CONN_MAX_RETRIES) {
  1595. failf(data, "Connection died, tried %d times before giving up",
  1596. CONN_MAX_RETRIES);
  1597. data->state.retrycount = 0;
  1598. return CURLE_SEND_ERROR;
  1599. }
  1600. infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
  1601. data->state.retrycount);
  1602. *url = strdup(data->state.url);
  1603. if(!*url)
  1604. return CURLE_OUT_OF_MEMORY;
  1605. connclose(conn, "retry"); /* close this connection */
  1606. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1607. to retry. Marking it this way should
  1608. prevent i.e HTTP transfers to return
  1609. error just because nothing has been
  1610. transferred! */
  1611. if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1612. data->req.writebytecount) {
  1613. data->state.rewindbeforesend = TRUE;
  1614. infof(data, "state.rewindbeforesend = TRUE");
  1615. }
  1616. }
  1617. return CURLE_OK;
  1618. }
  1619. /*
  1620. * Curl_setup_transfer() is called to setup some basic properties for the
  1621. * upcoming transfer.
  1622. */
  1623. void
  1624. Curl_setup_transfer(
  1625. struct Curl_easy *data, /* transfer */
  1626. int sockindex, /* socket index to read from or -1 */
  1627. curl_off_t size, /* -1 if unknown at this point */
  1628. bool getheader, /* TRUE if header parsing is wanted */
  1629. int writesockindex /* socket index to write to, it may very well be
  1630. the same we read from. -1 disables */
  1631. )
  1632. {
  1633. struct SingleRequest *k = &data->req;
  1634. struct connectdata *conn = data->conn;
  1635. struct HTTP *http = data->req.p.http;
  1636. bool httpsending;
  1637. DEBUGASSERT(conn != NULL);
  1638. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  1639. httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1640. (http->sending == HTTPSEND_REQUEST));
  1641. if(conn->bits.multiplex || conn->httpversion >= 20 || httpsending) {
  1642. /* when multiplexing, the read/write sockets need to be the same! */
  1643. conn->sockfd = sockindex == -1 ?
  1644. ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) :
  1645. conn->sock[sockindex];
  1646. conn->writesockfd = conn->sockfd;
  1647. if(httpsending)
  1648. /* special and very HTTP-specific */
  1649. writesockindex = FIRSTSOCKET;
  1650. }
  1651. else {
  1652. conn->sockfd = sockindex == -1 ?
  1653. CURL_SOCKET_BAD : conn->sock[sockindex];
  1654. conn->writesockfd = writesockindex == -1 ?
  1655. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1656. }
  1657. k->getheader = getheader;
  1658. k->size = size;
  1659. /* The code sequence below is placed in this function just because all
  1660. necessary input is not always known in do_complete() as this function may
  1661. be called after that */
  1662. if(!k->getheader) {
  1663. k->header = FALSE;
  1664. if(size > 0)
  1665. Curl_pgrsSetDownloadSize(data, size);
  1666. }
  1667. /* we want header and/or body, if neither then don't do this! */
  1668. if(k->getheader || !data->req.no_body) {
  1669. if(sockindex != -1)
  1670. k->keepon |= KEEP_RECV;
  1671. if(writesockindex != -1) {
  1672. /* HTTP 1.1 magic:
  1673. Even if we require a 100-return code before uploading data, we might
  1674. need to write data before that since the REQUEST may not have been
  1675. finished sent off just yet.
  1676. Thus, we must check if the request has been sent before we set the
  1677. state info where we wait for the 100-return code
  1678. */
  1679. if((data->state.expect100header) &&
  1680. (conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1681. (http->sending == HTTPSEND_BODY)) {
  1682. /* wait with write until we either got 100-continue or a timeout */
  1683. k->exp100 = EXP100_AWAITING_CONTINUE;
  1684. k->start100 = Curl_now();
  1685. /* Set a timeout for the multi interface. Add the inaccuracy margin so
  1686. that we don't fire slightly too early and get denied to run. */
  1687. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  1688. }
  1689. else {
  1690. if(data->state.expect100header)
  1691. /* when we've sent off the rest of the headers, we must await a
  1692. 100-continue but first finish sending the request */
  1693. k->exp100 = EXP100_SENDING_REQUEST;
  1694. /* enable the write bit when we're not waiting for continue */
  1695. k->keepon |= KEEP_SEND;
  1696. }
  1697. } /* if(writesockindex != -1) */
  1698. } /* if(k->getheader || !data->req.no_body) */
  1699. }