transfer.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  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_RECV|KEEP_SEND|
  1085. KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
  1086. result = CURLE_OK;
  1087. out:
  1088. if(result)
  1089. DEBUGF(infof(data, DMSG(data, "Curl_readwrite() -> %d"), result));
  1090. return result;
  1091. }
  1092. /*
  1093. * Curl_single_getsock() gets called by the multi interface code when the app
  1094. * has requested to get the sockets for the current connection. This function
  1095. * will then be called once for every connection that the multi interface
  1096. * keeps track of. This function will only be called for connections that are
  1097. * in the proper state to have this information available.
  1098. */
  1099. int Curl_single_getsock(struct Curl_easy *data,
  1100. struct connectdata *conn,
  1101. curl_socket_t *sock)
  1102. {
  1103. int bitmap = GETSOCK_BLANK;
  1104. unsigned sockindex = 0;
  1105. if(conn->handler->perform_getsock)
  1106. return conn->handler->perform_getsock(data, conn, sock);
  1107. /* don't include HOLD and PAUSE connections */
  1108. if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
  1109. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1110. bitmap |= GETSOCK_READSOCK(sockindex);
  1111. sock[sockindex] = conn->sockfd;
  1112. }
  1113. /* don't include HOLD and PAUSE connections */
  1114. if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
  1115. if((conn->sockfd != conn->writesockfd) ||
  1116. bitmap == GETSOCK_BLANK) {
  1117. /* only if they are not the same socket and we have a readable
  1118. one, we increase index */
  1119. if(bitmap != GETSOCK_BLANK)
  1120. sockindex++; /* increase index if we need two entries */
  1121. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1122. sock[sockindex] = conn->writesockfd;
  1123. }
  1124. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1125. }
  1126. return bitmap;
  1127. }
  1128. /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
  1129. which means this gets called once for each subsequent redirect etc */
  1130. void Curl_init_CONNECT(struct Curl_easy *data)
  1131. {
  1132. data->state.fread_func = data->set.fread_func_set;
  1133. data->state.in = data->set.in_set;
  1134. }
  1135. /*
  1136. * Curl_pretransfer() is called immediately before a transfer starts, and only
  1137. * once for one transfer no matter if it has redirects or do multi-pass
  1138. * authentication etc.
  1139. */
  1140. CURLcode Curl_pretransfer(struct Curl_easy *data)
  1141. {
  1142. CURLcode result;
  1143. if(!data->state.url && !data->set.uh) {
  1144. /* we can't do anything without URL */
  1145. failf(data, "No URL set");
  1146. return CURLE_URL_MALFORMAT;
  1147. }
  1148. /* since the URL may have been redirected in a previous use of this handle */
  1149. if(data->state.url_alloc) {
  1150. /* the already set URL is allocated, free it first! */
  1151. Curl_safefree(data->state.url);
  1152. data->state.url_alloc = FALSE;
  1153. }
  1154. if(!data->state.url && data->set.uh) {
  1155. CURLUcode uc;
  1156. free(data->set.str[STRING_SET_URL]);
  1157. uc = curl_url_get(data->set.uh,
  1158. CURLUPART_URL, &data->set.str[STRING_SET_URL], 0);
  1159. if(uc) {
  1160. failf(data, "No URL set");
  1161. return CURLE_URL_MALFORMAT;
  1162. }
  1163. }
  1164. data->state.prefer_ascii = data->set.prefer_ascii;
  1165. data->state.list_only = data->set.list_only;
  1166. data->state.httpreq = data->set.method;
  1167. data->state.url = data->set.str[STRING_SET_URL];
  1168. /* Init the SSL session ID cache here. We do it here since we want to do it
  1169. after the *_setopt() calls (that could specify the size of the cache) but
  1170. before any transfer takes place. */
  1171. result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
  1172. if(result)
  1173. return result;
  1174. data->state.requests = 0;
  1175. data->state.followlocation = 0; /* reset the location-follow counter */
  1176. data->state.this_is_a_follow = FALSE; /* reset this */
  1177. data->state.errorbuf = FALSE; /* no error has occurred */
  1178. data->state.httpwant = data->set.httpwant;
  1179. data->state.httpversion = 0;
  1180. data->state.authproblem = FALSE;
  1181. data->state.authhost.want = data->set.httpauth;
  1182. data->state.authproxy.want = data->set.proxyauth;
  1183. Curl_safefree(data->info.wouldredirect);
  1184. Curl_data_priority_clear_state(data);
  1185. if(data->state.httpreq == HTTPREQ_PUT)
  1186. data->state.infilesize = data->set.filesize;
  1187. else if((data->state.httpreq != HTTPREQ_GET) &&
  1188. (data->state.httpreq != HTTPREQ_HEAD)) {
  1189. data->state.infilesize = data->set.postfieldsize;
  1190. if(data->set.postfields && (data->state.infilesize == -1))
  1191. data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
  1192. }
  1193. else
  1194. data->state.infilesize = 0;
  1195. /* If there is a list of cookie files to read, do it now! */
  1196. Curl_cookie_loadfiles(data);
  1197. /* If there is a list of host pairs to deal with */
  1198. if(data->state.resolve)
  1199. result = Curl_loadhostpairs(data);
  1200. /* If there is a list of hsts files to read */
  1201. Curl_hsts_loadfiles(data);
  1202. if(!result) {
  1203. /* Allow data->set.use_port to set which port to use. This needs to be
  1204. * disabled for example when we follow Location: headers to URLs using
  1205. * different ports! */
  1206. data->state.allow_port = TRUE;
  1207. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1208. /*************************************************************
  1209. * Tell signal handler to ignore SIGPIPE
  1210. *************************************************************/
  1211. if(!data->set.no_signal)
  1212. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1213. #endif
  1214. Curl_initinfo(data); /* reset session-specific information "variables" */
  1215. Curl_pgrsResetTransferSizes(data);
  1216. Curl_pgrsStartNow(data);
  1217. /* In case the handle is re-used and an authentication method was picked
  1218. in the session we need to make sure we only use the one(s) we now
  1219. consider to be fine */
  1220. data->state.authhost.picked &= data->state.authhost.want;
  1221. data->state.authproxy.picked &= data->state.authproxy.want;
  1222. #ifndef CURL_DISABLE_FTP
  1223. data->state.wildcardmatch = data->set.wildcard_enabled;
  1224. if(data->state.wildcardmatch) {
  1225. struct WildcardData *wc = &data->wildcard;
  1226. if(wc->state < CURLWC_INIT) {
  1227. result = Curl_wildcard_init(wc); /* init wildcard structures */
  1228. if(result)
  1229. return CURLE_OUT_OF_MEMORY;
  1230. }
  1231. }
  1232. #endif
  1233. result = Curl_hsts_loadcb(data, data->hsts);
  1234. }
  1235. /*
  1236. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  1237. * basically anything through an HTTP proxy we can't limit this based on
  1238. * protocol.
  1239. */
  1240. if(data->set.str[STRING_USERAGENT]) {
  1241. Curl_safefree(data->state.aptr.uagent);
  1242. data->state.aptr.uagent =
  1243. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  1244. if(!data->state.aptr.uagent)
  1245. return CURLE_OUT_OF_MEMORY;
  1246. }
  1247. if(!result)
  1248. result = Curl_setstropt(&data->state.aptr.user,
  1249. data->set.str[STRING_USERNAME]);
  1250. if(!result)
  1251. result = Curl_setstropt(&data->state.aptr.passwd,
  1252. data->set.str[STRING_PASSWORD]);
  1253. if(!result)
  1254. result = Curl_setstropt(&data->state.aptr.proxyuser,
  1255. data->set.str[STRING_PROXYUSERNAME]);
  1256. if(!result)
  1257. result = Curl_setstropt(&data->state.aptr.proxypasswd,
  1258. data->set.str[STRING_PROXYPASSWORD]);
  1259. data->req.headerbytecount = 0;
  1260. Curl_headers_cleanup(data);
  1261. return result;
  1262. }
  1263. /*
  1264. * Curl_posttransfer() is called immediately after a transfer ends
  1265. */
  1266. CURLcode Curl_posttransfer(struct Curl_easy *data)
  1267. {
  1268. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1269. /* restore the signal handler for SIGPIPE before we get back */
  1270. if(!data->set.no_signal)
  1271. signal(SIGPIPE, data->state.prev_signal);
  1272. #else
  1273. (void)data; /* unused parameter */
  1274. #endif
  1275. return CURLE_OK;
  1276. }
  1277. /*
  1278. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1279. * as given by the remote server and set up the new URL to request.
  1280. *
  1281. * This function DOES NOT FREE the given url.
  1282. */
  1283. CURLcode Curl_follow(struct Curl_easy *data,
  1284. char *newurl, /* the Location: string */
  1285. followtype type) /* see transfer.h */
  1286. {
  1287. #ifdef CURL_DISABLE_HTTP
  1288. (void)data;
  1289. (void)newurl;
  1290. (void)type;
  1291. /* Location: following will not happen when HTTP is disabled */
  1292. return CURLE_TOO_MANY_REDIRECTS;
  1293. #else
  1294. /* Location: redirect */
  1295. bool disallowport = FALSE;
  1296. bool reachedmax = FALSE;
  1297. CURLUcode uc;
  1298. DEBUGASSERT(type != FOLLOW_NONE);
  1299. if(type != FOLLOW_FAKE)
  1300. data->state.requests++; /* count all real follows */
  1301. if(type == FOLLOW_REDIR) {
  1302. if((data->set.maxredirs != -1) &&
  1303. (data->state.followlocation >= data->set.maxredirs)) {
  1304. reachedmax = TRUE;
  1305. type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
  1306. to URL */
  1307. }
  1308. else {
  1309. data->state.followlocation++; /* count redirect-followings, including
  1310. auth reloads */
  1311. if(data->set.http_auto_referer) {
  1312. CURLU *u;
  1313. char *referer = NULL;
  1314. /* We are asked to automatically set the previous URL as the referer
  1315. when we get the next URL. We pick the ->url field, which may or may
  1316. not be 100% correct */
  1317. if(data->state.referer_alloc) {
  1318. Curl_safefree(data->state.referer);
  1319. data->state.referer_alloc = FALSE;
  1320. }
  1321. /* Make a copy of the URL without credentials and fragment */
  1322. u = curl_url();
  1323. if(!u)
  1324. return CURLE_OUT_OF_MEMORY;
  1325. uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
  1326. if(!uc)
  1327. uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
  1328. if(!uc)
  1329. uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
  1330. if(!uc)
  1331. uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
  1332. if(!uc)
  1333. uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
  1334. curl_url_cleanup(u);
  1335. if(uc || !referer)
  1336. return CURLE_OUT_OF_MEMORY;
  1337. data->state.referer = referer;
  1338. data->state.referer_alloc = TRUE; /* yes, free this later */
  1339. }
  1340. }
  1341. }
  1342. if((type != FOLLOW_RETRY) &&
  1343. (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
  1344. Curl_is_absolute_url(newurl, NULL, 0, FALSE))
  1345. /* If this is not redirect due to a 401 or 407 response and an absolute
  1346. URL: don't allow a custom port number */
  1347. disallowport = TRUE;
  1348. DEBUGASSERT(data->state.uh);
  1349. uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
  1350. (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
  1351. ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
  1352. CURLU_ALLOW_SPACE |
  1353. (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
  1354. if(uc) {
  1355. if(type != FOLLOW_FAKE) {
  1356. failf(data, "The redirect target URL could not be parsed: %s",
  1357. curl_url_strerror(uc));
  1358. return Curl_uc_to_curlcode(uc);
  1359. }
  1360. /* the URL could not be parsed for some reason, but since this is FAKE
  1361. mode, just duplicate the field as-is */
  1362. newurl = strdup(newurl);
  1363. if(!newurl)
  1364. return CURLE_OUT_OF_MEMORY;
  1365. }
  1366. else {
  1367. uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
  1368. if(uc)
  1369. return Curl_uc_to_curlcode(uc);
  1370. /* Clear auth if this redirects to a different port number or protocol,
  1371. unless permitted */
  1372. if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
  1373. char *portnum;
  1374. int port;
  1375. bool clear = FALSE;
  1376. if(data->set.use_port && data->state.allow_port)
  1377. /* a custom port is used */
  1378. port = (int)data->set.use_port;
  1379. else {
  1380. uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
  1381. CURLU_DEFAULT_PORT);
  1382. if(uc) {
  1383. free(newurl);
  1384. return Curl_uc_to_curlcode(uc);
  1385. }
  1386. port = atoi(portnum);
  1387. free(portnum);
  1388. }
  1389. if(port != data->info.conn_remote_port) {
  1390. infof(data, "Clear auth, redirects to port from %u to %u",
  1391. data->info.conn_remote_port, port);
  1392. clear = TRUE;
  1393. }
  1394. else {
  1395. char *scheme;
  1396. const struct Curl_handler *p;
  1397. uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
  1398. if(uc) {
  1399. free(newurl);
  1400. return Curl_uc_to_curlcode(uc);
  1401. }
  1402. p = Curl_builtin_scheme(scheme, CURL_ZERO_TERMINATED);
  1403. if(p && (p->protocol != data->info.conn_protocol)) {
  1404. infof(data, "Clear auth, redirects scheme from %s to %s",
  1405. data->info.conn_scheme, scheme);
  1406. clear = TRUE;
  1407. }
  1408. free(scheme);
  1409. }
  1410. if(clear) {
  1411. Curl_safefree(data->state.aptr.user);
  1412. Curl_safefree(data->state.aptr.passwd);
  1413. }
  1414. }
  1415. }
  1416. if(type == FOLLOW_FAKE) {
  1417. /* we're only figuring out the new url if we would've followed locations
  1418. but now we're done so we can get out! */
  1419. data->info.wouldredirect = newurl;
  1420. if(reachedmax) {
  1421. failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
  1422. return CURLE_TOO_MANY_REDIRECTS;
  1423. }
  1424. return CURLE_OK;
  1425. }
  1426. if(disallowport)
  1427. data->state.allow_port = FALSE;
  1428. if(data->state.url_alloc)
  1429. Curl_safefree(data->state.url);
  1430. data->state.url = newurl;
  1431. data->state.url_alloc = TRUE;
  1432. infof(data, "Issue another request to this URL: '%s'", data->state.url);
  1433. /*
  1434. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1435. * differently based on exactly what return code there was.
  1436. *
  1437. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1438. * an HTTP (proxy-) authentication scheme other than Basic.
  1439. */
  1440. switch(data->info.httpcode) {
  1441. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1442. Authorization: XXXX header in the HTTP request code snippet */
  1443. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1444. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1445. /* 300 - Multiple Choices */
  1446. /* 306 - Not used */
  1447. /* 307 - Temporary Redirect */
  1448. default: /* for all above (and the unknown ones) */
  1449. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1450. * seem to be OK to POST to.
  1451. */
  1452. break;
  1453. case 301: /* Moved Permanently */
  1454. /* (quote from RFC7231, section 6.4.2)
  1455. *
  1456. * Note: For historical reasons, a user agent MAY change the request
  1457. * method from POST to GET for the subsequent request. If this
  1458. * behavior is undesired, the 307 (Temporary Redirect) status code
  1459. * can be used instead.
  1460. *
  1461. * ----
  1462. *
  1463. * Many webservers expect this, so these servers often answers to a POST
  1464. * request with an error page. To be sure that libcurl gets the page that
  1465. * most user agents would get, libcurl has to force GET.
  1466. *
  1467. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1468. * can be overridden with CURLOPT_POSTREDIR.
  1469. */
  1470. if((data->state.httpreq == HTTPREQ_POST
  1471. || data->state.httpreq == HTTPREQ_POST_FORM
  1472. || data->state.httpreq == HTTPREQ_POST_MIME)
  1473. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1474. infof(data, "Switch from POST to GET");
  1475. data->state.httpreq = HTTPREQ_GET;
  1476. }
  1477. break;
  1478. case 302: /* Found */
  1479. /* (quote from RFC7231, section 6.4.3)
  1480. *
  1481. * Note: For historical reasons, a user agent MAY change the request
  1482. * method from POST to GET for the subsequent request. If this
  1483. * behavior is undesired, the 307 (Temporary Redirect) status code
  1484. * can be used instead.
  1485. *
  1486. * ----
  1487. *
  1488. * Many webservers expect this, so these servers often answers to a POST
  1489. * request with an error page. To be sure that libcurl gets the page that
  1490. * most user agents would get, libcurl has to force GET.
  1491. *
  1492. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1493. * can be overridden with CURLOPT_POSTREDIR.
  1494. */
  1495. if((data->state.httpreq == HTTPREQ_POST
  1496. || data->state.httpreq == HTTPREQ_POST_FORM
  1497. || data->state.httpreq == HTTPREQ_POST_MIME)
  1498. && !(data->set.keep_post & CURL_REDIR_POST_302)) {
  1499. infof(data, "Switch from POST to GET");
  1500. data->state.httpreq = HTTPREQ_GET;
  1501. }
  1502. break;
  1503. case 303: /* See Other */
  1504. /* 'See Other' location is not the resource but a substitute for the
  1505. * resource. In this case we switch the method to GET/HEAD, unless the
  1506. * method is POST and the user specified to keep it as POST.
  1507. * https://github.com/curl/curl/issues/5237#issuecomment-614641049
  1508. */
  1509. if(data->state.httpreq != HTTPREQ_GET &&
  1510. ((data->state.httpreq != HTTPREQ_POST &&
  1511. data->state.httpreq != HTTPREQ_POST_FORM &&
  1512. data->state.httpreq != HTTPREQ_POST_MIME) ||
  1513. !(data->set.keep_post & CURL_REDIR_POST_303))) {
  1514. data->state.httpreq = HTTPREQ_GET;
  1515. data->set.upload = false;
  1516. infof(data, "Switch to %s",
  1517. data->req.no_body?"HEAD":"GET");
  1518. }
  1519. break;
  1520. case 304: /* Not Modified */
  1521. /* 304 means we did a conditional request and it was "Not modified".
  1522. * We shouldn't get any Location: header in this response!
  1523. */
  1524. break;
  1525. case 305: /* Use Proxy */
  1526. /* (quote from RFC2616, section 10.3.6):
  1527. * "The requested resource MUST be accessed through the proxy given
  1528. * by the Location field. The Location field gives the URI of the
  1529. * proxy. The recipient is expected to repeat this single request
  1530. * via the proxy. 305 responses MUST only be generated by origin
  1531. * servers."
  1532. */
  1533. break;
  1534. }
  1535. Curl_pgrsTime(data, TIMER_REDIRECT);
  1536. Curl_pgrsResetTransferSizes(data);
  1537. return CURLE_OK;
  1538. #endif /* CURL_DISABLE_HTTP */
  1539. }
  1540. /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
  1541. NOTE: that the *url is malloc()ed. */
  1542. CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
  1543. {
  1544. struct connectdata *conn = data->conn;
  1545. bool retry = FALSE;
  1546. *url = NULL;
  1547. /* if we're talking upload, we can't do the checks below, unless the protocol
  1548. is HTTP as when uploading over HTTP we will still get a response */
  1549. if(data->set.upload &&
  1550. !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
  1551. return CURLE_OK;
  1552. if((data->req.bytecount + data->req.headerbytecount == 0) &&
  1553. conn->bits.reuse &&
  1554. (!data->req.no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP))
  1555. #ifndef CURL_DISABLE_RTSP
  1556. && (data->set.rtspreq != RTSPREQ_RECEIVE)
  1557. #endif
  1558. )
  1559. /* We got no data, we attempted to re-use a connection. For HTTP this
  1560. can be a retry so we try again regardless if we expected a body.
  1561. For other protocols we only try again only if we expected a body.
  1562. This might happen if the connection was left alive when we were
  1563. done using it before, but that was closed when we wanted to read from
  1564. it again. Bad luck. Retry the same request on a fresh connect! */
  1565. retry = TRUE;
  1566. else if(data->state.refused_stream &&
  1567. (data->req.bytecount + data->req.headerbytecount == 0) ) {
  1568. /* This was sent on a refused stream, safe to rerun. A refused stream
  1569. error can typically only happen on HTTP/2 level if the stream is safe
  1570. to issue again, but the nghttp2 API can deliver the message to other
  1571. streams as well, which is why this adds the check the data counters
  1572. too. */
  1573. infof(data, "REFUSED_STREAM, retrying a fresh connect");
  1574. data->state.refused_stream = FALSE; /* clear again */
  1575. retry = TRUE;
  1576. }
  1577. if(retry) {
  1578. #define CONN_MAX_RETRIES 5
  1579. if(data->state.retrycount++ >= CONN_MAX_RETRIES) {
  1580. failf(data, "Connection died, tried %d times before giving up",
  1581. CONN_MAX_RETRIES);
  1582. data->state.retrycount = 0;
  1583. return CURLE_SEND_ERROR;
  1584. }
  1585. infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
  1586. data->state.retrycount);
  1587. *url = strdup(data->state.url);
  1588. if(!*url)
  1589. return CURLE_OUT_OF_MEMORY;
  1590. connclose(conn, "retry"); /* close this connection */
  1591. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1592. to retry. Marking it this way should
  1593. prevent i.e HTTP transfers to return
  1594. error just because nothing has been
  1595. transferred! */
  1596. if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1597. data->req.writebytecount) {
  1598. data->state.rewindbeforesend = TRUE;
  1599. infof(data, "state.rewindbeforesend = TRUE");
  1600. }
  1601. }
  1602. return CURLE_OK;
  1603. }
  1604. /*
  1605. * Curl_setup_transfer() is called to setup some basic properties for the
  1606. * upcoming transfer.
  1607. */
  1608. void
  1609. Curl_setup_transfer(
  1610. struct Curl_easy *data, /* transfer */
  1611. int sockindex, /* socket index to read from or -1 */
  1612. curl_off_t size, /* -1 if unknown at this point */
  1613. bool getheader, /* TRUE if header parsing is wanted */
  1614. int writesockindex /* socket index to write to, it may very well be
  1615. the same we read from. -1 disables */
  1616. )
  1617. {
  1618. struct SingleRequest *k = &data->req;
  1619. struct connectdata *conn = data->conn;
  1620. struct HTTP *http = data->req.p.http;
  1621. bool httpsending;
  1622. DEBUGASSERT(conn != NULL);
  1623. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  1624. httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1625. (http->sending == HTTPSEND_REQUEST));
  1626. if(conn->bits.multiplex || conn->httpversion >= 20 || httpsending) {
  1627. /* when multiplexing, the read/write sockets need to be the same! */
  1628. conn->sockfd = sockindex == -1 ?
  1629. ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) :
  1630. conn->sock[sockindex];
  1631. conn->writesockfd = conn->sockfd;
  1632. if(httpsending)
  1633. /* special and very HTTP-specific */
  1634. writesockindex = FIRSTSOCKET;
  1635. }
  1636. else {
  1637. conn->sockfd = sockindex == -1 ?
  1638. CURL_SOCKET_BAD : conn->sock[sockindex];
  1639. conn->writesockfd = writesockindex == -1 ?
  1640. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1641. }
  1642. k->getheader = getheader;
  1643. k->size = size;
  1644. /* The code sequence below is placed in this function just because all
  1645. necessary input is not always known in do_complete() as this function may
  1646. be called after that */
  1647. if(!k->getheader) {
  1648. k->header = FALSE;
  1649. if(size > 0)
  1650. Curl_pgrsSetDownloadSize(data, size);
  1651. }
  1652. /* we want header and/or body, if neither then don't do this! */
  1653. if(k->getheader || !data->req.no_body) {
  1654. if(sockindex != -1)
  1655. k->keepon |= KEEP_RECV;
  1656. if(writesockindex != -1) {
  1657. /* HTTP 1.1 magic:
  1658. Even if we require a 100-return code before uploading data, we might
  1659. need to write data before that since the REQUEST may not have been
  1660. finished sent off just yet.
  1661. Thus, we must check if the request has been sent before we set the
  1662. state info where we wait for the 100-return code
  1663. */
  1664. if((data->state.expect100header) &&
  1665. (conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1666. (http->sending == HTTPSEND_BODY)) {
  1667. /* wait with write until we either got 100-continue or a timeout */
  1668. k->exp100 = EXP100_AWAITING_CONTINUE;
  1669. k->start100 = Curl_now();
  1670. /* Set a timeout for the multi interface. Add the inaccuracy margin so
  1671. that we don't fire slightly too early and get denied to run. */
  1672. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  1673. }
  1674. else {
  1675. if(data->state.expect100header)
  1676. /* when we've sent off the rest of the headers, we must await a
  1677. 100-continue but first finish sending the request */
  1678. k->exp100 = EXP100_SENDING_REQUEST;
  1679. /* enable the write bit when we're not waiting for continue */
  1680. k->keepon |= KEEP_SEND;
  1681. }
  1682. } /* if(writesockindex != -1) */
  1683. } /* if(k->getheader || !data->req.no_body) */
  1684. }