transfer.c 64 KB

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