2
0

transfer.c 63 KB

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