transfer.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  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. curl_off_t max_recv = data->set.max_recv_speed?
  388. data->set.max_recv_speed : CURL_OFF_T_MAX;
  389. char *buf = data->state.buffer;
  390. bool data_eof_handled = FALSE;
  391. DEBUGASSERT(buf);
  392. *done = FALSE;
  393. *comeback = FALSE;
  394. /* This is where we loop until we have read everything there is to
  395. read or we get a CURLE_AGAIN */
  396. do {
  397. bool is_empty_data = FALSE;
  398. size_t buffersize = data->set.buffer_size;
  399. size_t bytestoread = buffersize;
  400. /* For HTTP/2 and HTTP/3, read data without caring about the content
  401. length. This is safe because body in HTTP/2 is always segmented
  402. thanks to its framing layer. Meanwhile, we have to call Curl_read
  403. to ensure that http2_handle_stream_close is called when we read all
  404. incoming bytes for a particular stream. */
  405. bool is_http3 = Curl_conn_is_http3(data, conn, FIRSTSOCKET);
  406. data_eof_handled = is_http3 || Curl_conn_is_http2(data, conn, FIRSTSOCKET);
  407. if(!data_eof_handled && k->size != -1 && !k->header) {
  408. /* make sure we don't read too much */
  409. curl_off_t totalleft = k->size - k->bytecount;
  410. if(totalleft < (curl_off_t)bytestoread)
  411. bytestoread = (size_t)totalleft;
  412. }
  413. if(bytestoread) {
  414. /* receive data from the network! */
  415. result = Curl_read(data, conn->sockfd, buf, bytestoread, &nread);
  416. /* read would've blocked */
  417. if(CURLE_AGAIN == result) {
  418. result = CURLE_OK;
  419. break; /* get out of loop */
  420. }
  421. if(result>0)
  422. goto out;
  423. }
  424. else {
  425. /* read nothing but since we wanted nothing we consider this an OK
  426. situation to proceed from */
  427. DEBUGF(infof(data, "readwrite_data: we're done"));
  428. nread = 0;
  429. }
  430. if(!k->bytecount) {
  431. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  432. if(k->exp100 > EXP100_SEND_DATA)
  433. /* set time stamp to compare with when waiting for the 100 */
  434. k->start100 = Curl_now();
  435. }
  436. *didwhat |= KEEP_RECV;
  437. /* indicates data of zero size, i.e. empty file */
  438. is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
  439. if(0 < nread || is_empty_data) {
  440. buf[nread] = 0;
  441. }
  442. if(!nread) {
  443. /* if we receive 0 or less here, either the data transfer is done or the
  444. server closed the connection and we bail out from this! */
  445. if(data_eof_handled)
  446. DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
  447. else
  448. DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
  449. k->keepon = 0; /* stop sending as well */
  450. if(!is_empty_data)
  451. break;
  452. }
  453. /* Default buffer to use when we write the buffer, it may be changed
  454. in the flow below before the actual storing is done. */
  455. k->str = buf;
  456. if(conn->handler->readwrite) {
  457. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  458. if(result)
  459. goto out;
  460. if(readmore)
  461. break;
  462. }
  463. #ifndef CURL_DISABLE_HTTP
  464. /* Since this is a two-state thing, we check if we are parsing
  465. headers at the moment or not. */
  466. if(k->header) {
  467. /* we are in parse-the-header-mode */
  468. bool stop_reading = FALSE;
  469. result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
  470. if(result)
  471. goto out;
  472. if(conn->handler->readwrite &&
  473. (k->maxdownload <= 0 && nread > 0)) {
  474. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  475. if(result)
  476. goto out;
  477. if(readmore)
  478. break;
  479. }
  480. if(stop_reading) {
  481. /* We've stopped dealing with input, get out of the do-while loop */
  482. if(nread > 0) {
  483. infof(data,
  484. "Excess found:"
  485. " excess = %zd"
  486. " url = %s (zero-length body)",
  487. nread, data->state.up.path);
  488. }
  489. break;
  490. }
  491. }
  492. #endif /* CURL_DISABLE_HTTP */
  493. /* This is not an 'else if' since it may be a rest from the header
  494. parsing, where the beginning of the buffer is headers and the end
  495. is non-headers. */
  496. if(!k->header && (nread > 0 || is_empty_data)) {
  497. if(data->req.no_body) {
  498. /* data arrives although we want none, bail out */
  499. streamclose(conn, "ignoring body");
  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. if(excess > 0 && !k->ignorebody) {
  576. infof(data,
  577. "Excess found in a read:"
  578. " excess = %zu"
  579. ", size = %" CURL_FORMAT_CURL_OFF_T
  580. ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
  581. ", bytecount = %" CURL_FORMAT_CURL_OFF_T,
  582. excess, k->size, k->maxdownload, k->bytecount);
  583. connclose(conn, "excess found in a read");
  584. }
  585. nread = (ssize_t) (k->maxdownload - k->bytecount);
  586. if(nread < 0) /* this should be unusual */
  587. nread = 0;
  588. /* HTTP/3 over QUIC should keep reading until QUIC connection
  589. is closed. In contrast to HTTP/2 which can stop reading
  590. from TCP connection, HTTP/3 over QUIC needs ACK from server
  591. to ensure stream closure. It should keep reading. */
  592. if(!is_http3) {
  593. k->keepon &= ~KEEP_RECV; /* we're done reading */
  594. }
  595. }
  596. k->bytecount += nread;
  597. max_recv -= nread;
  598. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  599. if(!k->chunk && (nread || k->badheader || is_empty_data)) {
  600. /* If this is chunky transfer, it was already written */
  601. if(k->badheader && !k->ignorebody) {
  602. /* we parsed a piece of data wrongly assuming it was a header
  603. and now we output it as body instead */
  604. size_t headlen = Curl_dyn_len(&data->state.headerb);
  605. /* Don't let excess data pollute body writes */
  606. if(k->maxdownload == -1 || (curl_off_t)headlen <= k->maxdownload)
  607. result = Curl_client_write(data, CLIENTWRITE_BODY,
  608. Curl_dyn_ptr(&data->state.headerb),
  609. headlen);
  610. else
  611. result = Curl_client_write(data, CLIENTWRITE_BODY,
  612. Curl_dyn_ptr(&data->state.headerb),
  613. (size_t)k->maxdownload);
  614. if(result)
  615. goto out;
  616. }
  617. if(k->badheader < HEADER_ALLBAD) {
  618. /* This switch handles various content encodings. If there's an
  619. error here, be sure to check over the almost identical code
  620. in http_chunks.c.
  621. Make sure that ALL_CONTENT_ENCODINGS contains all the
  622. encodings handled here. */
  623. if(data->set.http_ce_skip || !k->writer_stack) {
  624. if(!k->ignorebody && nread) {
  625. #ifndef CURL_DISABLE_POP3
  626. if(conn->handler->protocol & PROTO_FAMILY_POP3)
  627. result = Curl_pop3_write(data, k->str, nread);
  628. else
  629. #endif /* CURL_DISABLE_POP3 */
  630. result = Curl_client_write(data, CLIENTWRITE_BODY, k->str,
  631. nread);
  632. }
  633. }
  634. else if(!k->ignorebody && nread)
  635. result = Curl_unencode_write(data, k->writer_stack, k->str, nread);
  636. }
  637. k->badheader = HEADER_NORMAL; /* taken care of now */
  638. if(result)
  639. goto out;
  640. }
  641. } /* if(!header and data to read) */
  642. if(conn->handler->readwrite && excess) {
  643. /* Parse the excess data */
  644. k->str += nread;
  645. if(&k->str[excess] > &buf[data->set.buffer_size]) {
  646. /* the excess amount was too excessive(!), make sure
  647. it doesn't read out of buffer */
  648. excess = &buf[data->set.buffer_size] - k->str;
  649. }
  650. nread = (ssize_t)excess;
  651. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  652. if(result)
  653. goto out;
  654. if(readmore)
  655. k->keepon |= KEEP_RECV; /* we're not done reading */
  656. break;
  657. }
  658. if(is_empty_data) {
  659. /* if we received nothing, the server closed the connection and we
  660. are done */
  661. k->keepon &= ~KEEP_RECV;
  662. }
  663. if((k->keepon & KEEP_RECV_PAUSE) || !(k->keepon & KEEP_RECV)) {
  664. /* this is a paused or stopped transfer */
  665. break;
  666. }
  667. } while((max_recv > 0) && data_pending(data) && maxloops--);
  668. if(maxloops <= 0 || max_recv <= 0) {
  669. /* we mark it as read-again-please */
  670. data->state.dselect_bits = CURL_CSELECT_IN;
  671. *comeback = TRUE;
  672. }
  673. if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
  674. (conn->bits.close || data_eof_handled)) {
  675. /* When we've read the entire thing and the close bit is set, the server
  676. may now close the connection. If there's now any kind of sending going
  677. on from our side, we need to stop that immediately. */
  678. infof(data, "we are done reading and this is set to close, stop send");
  679. k->keepon &= ~KEEP_SEND; /* no writing anymore either */
  680. }
  681. out:
  682. if(result)
  683. DEBUGF(infof(data, "readwrite_data() -> %d", result));
  684. return result;
  685. }
  686. CURLcode Curl_done_sending(struct Curl_easy *data,
  687. struct SingleRequest *k)
  688. {
  689. k->keepon &= ~KEEP_SEND; /* we're done writing */
  690. /* These functions should be moved into the handler struct! */
  691. Curl_conn_ev_data_done_send(data);
  692. return CURLE_OK;
  693. }
  694. #if defined(WIN32) && defined(USE_WINSOCK)
  695. #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
  696. #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
  697. #endif
  698. static void win_update_buffer_size(curl_socket_t sockfd)
  699. {
  700. int result;
  701. ULONG ideal;
  702. DWORD ideallen;
  703. result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
  704. &ideal, sizeof(ideal), &ideallen, 0, 0);
  705. if(result == 0) {
  706. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
  707. (const char *)&ideal, sizeof(ideal));
  708. }
  709. }
  710. #else
  711. #define win_update_buffer_size(x)
  712. #endif
  713. #define curl_upload_refill_watermark(data) \
  714. ((ssize_t)((data)->set.upload_buffer_size >> 5))
  715. /*
  716. * Send data to upload to the server, when the socket is writable.
  717. */
  718. static CURLcode readwrite_upload(struct Curl_easy *data,
  719. struct connectdata *conn,
  720. int *didwhat)
  721. {
  722. ssize_t i, si;
  723. ssize_t bytes_written;
  724. CURLcode result;
  725. ssize_t nread; /* number of bytes read */
  726. bool sending_http_headers = FALSE;
  727. struct SingleRequest *k = &data->req;
  728. *didwhat |= KEEP_SEND;
  729. do {
  730. curl_off_t nbody;
  731. ssize_t offset = 0;
  732. if(0 != k->upload_present &&
  733. k->upload_present < curl_upload_refill_watermark(data) &&
  734. !k->upload_chunky &&/*(variable sized chunked header; append not safe)*/
  735. !k->upload_done && /*!(k->upload_done once k->upload_present sent)*/
  736. !(k->writebytecount + k->upload_present - k->pendingheader ==
  737. data->state.infilesize)) {
  738. offset = k->upload_present;
  739. }
  740. /* only read more data if there's no upload data already
  741. present in the upload buffer, or if appending to upload buffer */
  742. if(0 == k->upload_present || offset) {
  743. result = Curl_get_upload_buffer(data);
  744. if(result)
  745. return result;
  746. if(offset && k->upload_fromhere != data->state.ulbuf)
  747. memmove(data->state.ulbuf, k->upload_fromhere, offset);
  748. /* init the "upload from here" pointer */
  749. k->upload_fromhere = data->state.ulbuf;
  750. if(!k->upload_done) {
  751. /* HTTP pollution, this should be written nicer to become more
  752. protocol agnostic. */
  753. size_t fillcount;
  754. struct HTTP *http = k->p.http;
  755. if((k->exp100 == EXP100_SENDING_REQUEST) &&
  756. (http->sending == HTTPSEND_BODY)) {
  757. /* If this call is to send body data, we must take some action:
  758. We have sent off the full HTTP 1.1 request, and we shall now
  759. go into the Expect: 100 state and await such a header */
  760. k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
  761. k->keepon &= ~KEEP_SEND; /* disable writing */
  762. k->start100 = Curl_now(); /* timeout count starts now */
  763. *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
  764. /* set a timeout for the multi interface */
  765. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  766. break;
  767. }
  768. if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
  769. if(http->sending == HTTPSEND_REQUEST)
  770. /* We're sending the HTTP request headers, not the data.
  771. Remember that so we don't change the line endings. */
  772. sending_http_headers = TRUE;
  773. else
  774. sending_http_headers = FALSE;
  775. }
  776. k->upload_fromhere += offset;
  777. result = Curl_fillreadbuffer(data, data->set.upload_buffer_size-offset,
  778. &fillcount);
  779. k->upload_fromhere -= offset;
  780. if(result)
  781. return result;
  782. nread = offset + fillcount;
  783. }
  784. else
  785. nread = 0; /* we're done uploading/reading */
  786. if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
  787. /* this is a paused transfer */
  788. break;
  789. }
  790. if(nread <= 0) {
  791. result = Curl_done_sending(data, k);
  792. if(result)
  793. return result;
  794. break;
  795. }
  796. /* store number of bytes available for upload */
  797. k->upload_present = nread;
  798. /* convert LF to CRLF if so asked */
  799. if((!sending_http_headers) && (
  800. #ifdef CURL_DO_LINEEND_CONV
  801. /* always convert if we're FTPing in ASCII mode */
  802. (data->state.prefer_ascii) ||
  803. #endif
  804. (data->set.crlf))) {
  805. /* Do we need to allocate a scratch buffer? */
  806. if(!data->state.scratch) {
  807. data->state.scratch = malloc(2 * data->set.upload_buffer_size);
  808. if(!data->state.scratch) {
  809. failf(data, "Failed to alloc scratch buffer");
  810. return CURLE_OUT_OF_MEMORY;
  811. }
  812. }
  813. /*
  814. * ASCII/EBCDIC Note: This is presumably a text (not binary)
  815. * transfer so the data should already be in ASCII.
  816. * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
  817. * must be used instead of the escape sequences \r & \n.
  818. */
  819. if(offset)
  820. memcpy(data->state.scratch, k->upload_fromhere, offset);
  821. for(i = offset, si = offset; i < nread; i++, si++) {
  822. if(k->upload_fromhere[i] == 0x0a) {
  823. data->state.scratch[si++] = 0x0d;
  824. data->state.scratch[si] = 0x0a;
  825. if(!data->set.crlf) {
  826. /* we're here only because FTP is in ASCII mode...
  827. bump infilesize for the LF we just added */
  828. if(data->state.infilesize != -1)
  829. data->state.infilesize++;
  830. }
  831. }
  832. else
  833. data->state.scratch[si] = k->upload_fromhere[i];
  834. }
  835. if(si != nread) {
  836. /* only perform the special operation if we really did replace
  837. anything */
  838. nread = si;
  839. /* upload from the new (replaced) buffer instead */
  840. k->upload_fromhere = data->state.scratch;
  841. /* set the new amount too */
  842. k->upload_present = nread;
  843. }
  844. }
  845. #ifndef CURL_DISABLE_SMTP
  846. if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
  847. result = Curl_smtp_escape_eob(data, nread, offset);
  848. if(result)
  849. return result;
  850. }
  851. #endif /* CURL_DISABLE_SMTP */
  852. } /* if 0 == k->upload_present or appended to upload buffer */
  853. else {
  854. /* We have a partial buffer left from a previous "round". Use
  855. that instead of reading more data */
  856. }
  857. /* write to socket (send away data) */
  858. result = Curl_write(data,
  859. conn->writesockfd, /* socket to send to */
  860. k->upload_fromhere, /* buffer pointer */
  861. k->upload_present, /* buffer size */
  862. &bytes_written); /* actually sent */
  863. if(result)
  864. return result;
  865. #if defined(WIN32) && defined(USE_WINSOCK)
  866. {
  867. struct curltime n = Curl_now();
  868. if(Curl_timediff(n, k->last_sndbuf_update) > 1000) {
  869. win_update_buffer_size(conn->writesockfd);
  870. k->last_sndbuf_update = n;
  871. }
  872. }
  873. #endif
  874. if(k->pendingheader) {
  875. /* parts of what was sent was header */
  876. curl_off_t n = CURLMIN(k->pendingheader, bytes_written);
  877. /* show the data before we change the pointer upload_fromhere */
  878. Curl_debug(data, CURLINFO_HEADER_OUT, k->upload_fromhere, (size_t)n);
  879. k->pendingheader -= n;
  880. nbody = bytes_written - n; /* size of the written body part */
  881. }
  882. else
  883. nbody = bytes_written;
  884. if(nbody) {
  885. /* show the data before we change the pointer upload_fromhere */
  886. Curl_debug(data, CURLINFO_DATA_OUT,
  887. &k->upload_fromhere[bytes_written - nbody],
  888. (size_t)nbody);
  889. k->writebytecount += nbody;
  890. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  891. }
  892. if((!k->upload_chunky || k->forbidchunk) &&
  893. (k->writebytecount == data->state.infilesize)) {
  894. /* we have sent all data we were supposed to */
  895. k->upload_done = TRUE;
  896. infof(data, "We are completely uploaded and fine");
  897. }
  898. if(k->upload_present != bytes_written) {
  899. /* we only wrote a part of the buffer (if anything), deal with it! */
  900. /* store the amount of bytes left in the buffer to write */
  901. k->upload_present -= bytes_written;
  902. /* advance the pointer where to find the buffer when the next send
  903. is to happen */
  904. k->upload_fromhere += bytes_written;
  905. }
  906. else {
  907. /* we've uploaded that buffer now */
  908. result = Curl_get_upload_buffer(data);
  909. if(result)
  910. return result;
  911. k->upload_fromhere = data->state.ulbuf;
  912. k->upload_present = 0; /* no more bytes left */
  913. if(k->upload_done) {
  914. result = Curl_done_sending(data, k);
  915. if(result)
  916. return result;
  917. }
  918. }
  919. } while(0); /* just to break out from! */
  920. return CURLE_OK;
  921. }
  922. /*
  923. * Curl_readwrite() is the low-level function to be called when data is to
  924. * be read and written to/from the connection.
  925. *
  926. * return '*comeback' TRUE if we didn't properly drain the socket so this
  927. * function should get called again without select() or similar in between!
  928. */
  929. CURLcode Curl_readwrite(struct connectdata *conn,
  930. struct Curl_easy *data,
  931. bool *done,
  932. bool *comeback)
  933. {
  934. struct SingleRequest *k = &data->req;
  935. CURLcode result;
  936. struct curltime now;
  937. int didwhat = 0;
  938. int select_bits;
  939. if(data->state.dselect_bits) {
  940. select_bits = data->state.dselect_bits;
  941. data->state.dselect_bits = 0;
  942. }
  943. else if(conn->cselect_bits) {
  944. select_bits = conn->cselect_bits;
  945. conn->cselect_bits = 0;
  946. }
  947. else {
  948. curl_socket_t fd_read;
  949. curl_socket_t fd_write;
  950. /* only use the proper socket if the *_HOLD bit is not set simultaneously
  951. as then we are in rate limiting state in that transfer direction */
  952. if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
  953. fd_read = conn->sockfd;
  954. else
  955. fd_read = CURL_SOCKET_BAD;
  956. if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
  957. fd_write = conn->writesockfd;
  958. else
  959. fd_write = CURL_SOCKET_BAD;
  960. select_bits = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
  961. }
  962. if(select_bits == CURL_CSELECT_ERR) {
  963. failf(data, "select/poll returned error");
  964. result = CURLE_SEND_ERROR;
  965. goto out;
  966. }
  967. #ifdef USE_HYPER
  968. if(conn->datastream) {
  969. result = conn->datastream(data, conn, &didwhat, done, select_bits);
  970. if(result || *done)
  971. goto out;
  972. }
  973. else {
  974. #endif
  975. /* We go ahead and do a read if we have a readable socket or if
  976. the stream was rewound (in which case we have data in a
  977. buffer) */
  978. if((k->keepon & KEEP_RECV) && (select_bits & CURL_CSELECT_IN)) {
  979. result = readwrite_data(data, conn, k, &didwhat, done, comeback);
  980. if(result || *done)
  981. goto out;
  982. }
  983. /* If we still have writing to do, we check if we have a writable socket. */
  984. if((k->keepon & KEEP_SEND) && (select_bits & CURL_CSELECT_OUT)) {
  985. /* write */
  986. result = readwrite_upload(data, conn, &didwhat);
  987. if(result)
  988. goto out;
  989. }
  990. #ifdef USE_HYPER
  991. }
  992. #endif
  993. now = Curl_now();
  994. if(!didwhat) {
  995. /* no read no write, this is a timeout? */
  996. if(k->exp100 == EXP100_AWAITING_CONTINUE) {
  997. /* This should allow some time for the header to arrive, but only a
  998. very short time as otherwise it'll be too much wasted time too
  999. often. */
  1000. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  1001. Therefore, when a client sends this header field to an origin server
  1002. (possibly via a proxy) from which it has never seen a 100 (Continue)
  1003. status, the client SHOULD NOT wait for an indefinite period before
  1004. sending the request body.
  1005. */
  1006. timediff_t ms = Curl_timediff(now, k->start100);
  1007. if(ms >= data->set.expect_100_timeout) {
  1008. /* we've waited long enough, continue anyway */
  1009. k->exp100 = EXP100_SEND_DATA;
  1010. k->keepon |= KEEP_SEND;
  1011. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  1012. infof(data, "Done waiting for 100-continue");
  1013. }
  1014. }
  1015. result = Curl_conn_ev_data_idle(data);
  1016. if(result)
  1017. goto out;
  1018. }
  1019. if(Curl_pgrsUpdate(data))
  1020. result = CURLE_ABORTED_BY_CALLBACK;
  1021. else
  1022. result = Curl_speedcheck(data, now);
  1023. if(result)
  1024. goto out;
  1025. if(k->keepon) {
  1026. if(0 > Curl_timeleft(data, &now, FALSE)) {
  1027. if(k->size != -1) {
  1028. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1029. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
  1030. CURL_FORMAT_CURL_OFF_T " bytes received",
  1031. Curl_timediff(now, data->progress.t_startsingle),
  1032. k->bytecount, k->size);
  1033. }
  1034. else {
  1035. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1036. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received",
  1037. Curl_timediff(now, data->progress.t_startsingle),
  1038. k->bytecount);
  1039. }
  1040. result = CURLE_OPERATION_TIMEDOUT;
  1041. goto out;
  1042. }
  1043. }
  1044. else {
  1045. /*
  1046. * The transfer has been performed. Just make some general checks before
  1047. * returning.
  1048. */
  1049. if(!(data->req.no_body) && (k->size != -1) &&
  1050. (k->bytecount != k->size) &&
  1051. #ifdef CURL_DO_LINEEND_CONV
  1052. /* Most FTP servers don't adjust their file SIZE response for CRLFs,
  1053. so we'll check to see if the discrepancy can be explained
  1054. by the number of CRLFs we've changed to LFs.
  1055. */
  1056. (k->bytecount != (k->size + data->state.crlf_conversions)) &&
  1057. #endif /* CURL_DO_LINEEND_CONV */
  1058. !k->newurl) {
  1059. failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
  1060. " bytes remaining to read", k->size - k->bytecount);
  1061. result = CURLE_PARTIAL_FILE;
  1062. goto out;
  1063. }
  1064. if(!(data->req.no_body) && k->chunk &&
  1065. (conn->chunk.state != CHUNK_STOP)) {
  1066. /*
  1067. * In chunked mode, return an error if the connection is closed prior to
  1068. * the empty (terminating) chunk is read.
  1069. *
  1070. * The condition above used to check for
  1071. * conn->proto.http->chunk.datasize != 0 which is true after reading
  1072. * *any* chunk, not just the empty chunk.
  1073. *
  1074. */
  1075. failf(data, "transfer closed with outstanding read data remaining");
  1076. result = CURLE_PARTIAL_FILE;
  1077. goto out;
  1078. }
  1079. if(Curl_pgrsUpdate(data)) {
  1080. result = CURLE_ABORTED_BY_CALLBACK;
  1081. goto out;
  1082. }
  1083. }
  1084. /* Now update the "done" boolean we return */
  1085. *done = (0 == (k->keepon&(KEEP_RECVBITS|KEEP_SENDBITS))) ? TRUE : FALSE;
  1086. out:
  1087. if(result)
  1088. DEBUGF(infof(data, "Curl_readwrite() -> %d", result));
  1089. return result;
  1090. }
  1091. /*
  1092. * Curl_single_getsock() gets called by the multi interface code when the app
  1093. * has requested to get the sockets for the current connection. This function
  1094. * will then be called once for every connection that the multi interface
  1095. * keeps track of. This function will only be called for connections that are
  1096. * in the proper state to have this information available.
  1097. */
  1098. int Curl_single_getsock(struct Curl_easy *data,
  1099. struct connectdata *conn,
  1100. curl_socket_t *sock)
  1101. {
  1102. int bitmap = GETSOCK_BLANK;
  1103. unsigned sockindex = 0;
  1104. if(conn->handler->perform_getsock)
  1105. return conn->handler->perform_getsock(data, conn, sock);
  1106. /* don't include HOLD and PAUSE connections */
  1107. if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
  1108. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1109. bitmap |= GETSOCK_READSOCK(sockindex);
  1110. sock[sockindex] = conn->sockfd;
  1111. }
  1112. /* don't include HOLD and PAUSE connections */
  1113. if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
  1114. if((conn->sockfd != conn->writesockfd) ||
  1115. bitmap == GETSOCK_BLANK) {
  1116. /* only if they are not the same socket and we have a readable
  1117. one, we increase index */
  1118. if(bitmap != GETSOCK_BLANK)
  1119. sockindex++; /* increase index if we need two entries */
  1120. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1121. sock[sockindex] = conn->writesockfd;
  1122. }
  1123. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1124. }
  1125. return bitmap;
  1126. }
  1127. /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
  1128. which means this gets called once for each subsequent redirect etc */
  1129. void Curl_init_CONNECT(struct Curl_easy *data)
  1130. {
  1131. data->state.fread_func = data->set.fread_func_set;
  1132. data->state.in = data->set.in_set;
  1133. data->state.upload = (data->state.httpreq == HTTPREQ_PUT);
  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. if(data->set.postfields && data->set.set_resume_from) {
  1165. /* we can't */
  1166. failf(data, "cannot mix POSTFIELDS with RESUME_FROM");
  1167. return CURLE_BAD_FUNCTION_ARGUMENT;
  1168. }
  1169. data->state.prefer_ascii = data->set.prefer_ascii;
  1170. #ifdef CURL_LIST_ONLY_PROTOCOL
  1171. data->state.list_only = data->set.list_only;
  1172. #endif
  1173. data->state.httpreq = data->set.method;
  1174. data->state.url = data->set.str[STRING_SET_URL];
  1175. /* Init the SSL session ID cache here. We do it here since we want to do it
  1176. after the *_setopt() calls (that could specify the size of the cache) but
  1177. before any transfer takes place. */
  1178. result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
  1179. if(result)
  1180. return result;
  1181. data->state.requests = 0;
  1182. data->state.followlocation = 0; /* reset the location-follow counter */
  1183. data->state.this_is_a_follow = FALSE; /* reset this */
  1184. data->state.errorbuf = FALSE; /* no error has occurred */
  1185. data->state.httpwant = data->set.httpwant;
  1186. data->state.httpversion = 0;
  1187. data->state.authproblem = FALSE;
  1188. data->state.authhost.want = data->set.httpauth;
  1189. data->state.authproxy.want = data->set.proxyauth;
  1190. Curl_safefree(data->info.wouldredirect);
  1191. Curl_data_priority_clear_state(data);
  1192. if(data->state.httpreq == HTTPREQ_PUT)
  1193. data->state.infilesize = data->set.filesize;
  1194. else if((data->state.httpreq != HTTPREQ_GET) &&
  1195. (data->state.httpreq != HTTPREQ_HEAD)) {
  1196. data->state.infilesize = data->set.postfieldsize;
  1197. if(data->set.postfields && (data->state.infilesize == -1))
  1198. data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
  1199. }
  1200. else
  1201. data->state.infilesize = 0;
  1202. /* If there is a list of cookie files to read, do it now! */
  1203. Curl_cookie_loadfiles(data);
  1204. /* If there is a list of host pairs to deal with */
  1205. if(data->state.resolve)
  1206. result = Curl_loadhostpairs(data);
  1207. /* If there is a list of hsts files to read */
  1208. Curl_hsts_loadfiles(data);
  1209. if(!result) {
  1210. /* Allow data->set.use_port to set which port to use. This needs to be
  1211. * disabled for example when we follow Location: headers to URLs using
  1212. * different ports! */
  1213. data->state.allow_port = TRUE;
  1214. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1215. /*************************************************************
  1216. * Tell signal handler to ignore SIGPIPE
  1217. *************************************************************/
  1218. if(!data->set.no_signal)
  1219. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1220. #endif
  1221. Curl_initinfo(data); /* reset session-specific information "variables" */
  1222. Curl_pgrsResetTransferSizes(data);
  1223. Curl_pgrsStartNow(data);
  1224. /* In case the handle is reused and an authentication method was picked
  1225. in the session we need to make sure we only use the one(s) we now
  1226. consider to be fine */
  1227. data->state.authhost.picked &= data->state.authhost.want;
  1228. data->state.authproxy.picked &= data->state.authproxy.want;
  1229. #ifndef CURL_DISABLE_FTP
  1230. data->state.wildcardmatch = data->set.wildcard_enabled;
  1231. if(data->state.wildcardmatch) {
  1232. struct WildcardData *wc;
  1233. if(!data->wildcard) {
  1234. data->wildcard = calloc(1, sizeof(struct WildcardData));
  1235. if(!data->wildcard)
  1236. return CURLE_OUT_OF_MEMORY;
  1237. }
  1238. wc = data->wildcard;
  1239. if((wc->state < CURLWC_INIT) ||
  1240. (wc->state >= CURLWC_CLEAN)) {
  1241. if(wc->ftpwc)
  1242. wc->dtor(wc->ftpwc);
  1243. Curl_safefree(wc->pattern);
  1244. Curl_safefree(wc->path);
  1245. result = Curl_wildcard_init(wc); /* init wildcard structures */
  1246. if(result)
  1247. return CURLE_OUT_OF_MEMORY;
  1248. }
  1249. }
  1250. #endif
  1251. result = Curl_hsts_loadcb(data, data->hsts);
  1252. }
  1253. /*
  1254. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  1255. * basically anything through an HTTP proxy we can't limit this based on
  1256. * protocol.
  1257. */
  1258. if(data->set.str[STRING_USERAGENT]) {
  1259. Curl_safefree(data->state.aptr.uagent);
  1260. data->state.aptr.uagent =
  1261. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  1262. if(!data->state.aptr.uagent)
  1263. return CURLE_OUT_OF_MEMORY;
  1264. }
  1265. if(!result)
  1266. result = Curl_setstropt(&data->state.aptr.user,
  1267. data->set.str[STRING_USERNAME]);
  1268. if(!result)
  1269. result = Curl_setstropt(&data->state.aptr.passwd,
  1270. data->set.str[STRING_PASSWORD]);
  1271. if(!result)
  1272. result = Curl_setstropt(&data->state.aptr.proxyuser,
  1273. data->set.str[STRING_PROXYUSERNAME]);
  1274. if(!result)
  1275. result = Curl_setstropt(&data->state.aptr.proxypasswd,
  1276. data->set.str[STRING_PROXYPASSWORD]);
  1277. data->req.headerbytecount = 0;
  1278. Curl_headers_cleanup(data);
  1279. return result;
  1280. }
  1281. /*
  1282. * Curl_posttransfer() is called immediately after a transfer ends
  1283. */
  1284. CURLcode Curl_posttransfer(struct Curl_easy *data)
  1285. {
  1286. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1287. /* restore the signal handler for SIGPIPE before we get back */
  1288. if(!data->set.no_signal)
  1289. signal(SIGPIPE, data->state.prev_signal);
  1290. #else
  1291. (void)data; /* unused parameter */
  1292. #endif
  1293. return CURLE_OK;
  1294. }
  1295. /*
  1296. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1297. * as given by the remote server and set up the new URL to request.
  1298. *
  1299. * This function DOES NOT FREE the given url.
  1300. */
  1301. CURLcode Curl_follow(struct Curl_easy *data,
  1302. char *newurl, /* the Location: string */
  1303. followtype type) /* see transfer.h */
  1304. {
  1305. #ifdef CURL_DISABLE_HTTP
  1306. (void)data;
  1307. (void)newurl;
  1308. (void)type;
  1309. /* Location: following will not happen when HTTP is disabled */
  1310. return CURLE_TOO_MANY_REDIRECTS;
  1311. #else
  1312. /* Location: redirect */
  1313. bool disallowport = FALSE;
  1314. bool reachedmax = FALSE;
  1315. CURLUcode uc;
  1316. DEBUGASSERT(type != FOLLOW_NONE);
  1317. if(type != FOLLOW_FAKE)
  1318. data->state.requests++; /* count all real follows */
  1319. if(type == FOLLOW_REDIR) {
  1320. if((data->set.maxredirs != -1) &&
  1321. (data->state.followlocation >= data->set.maxredirs)) {
  1322. reachedmax = TRUE;
  1323. type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
  1324. to URL */
  1325. }
  1326. else {
  1327. data->state.followlocation++; /* count redirect-followings, including
  1328. auth reloads */
  1329. if(data->set.http_auto_referer) {
  1330. CURLU *u;
  1331. char *referer = NULL;
  1332. /* We are asked to automatically set the previous URL as the referer
  1333. when we get the next URL. We pick the ->url field, which may or may
  1334. not be 100% correct */
  1335. if(data->state.referer_alloc) {
  1336. Curl_safefree(data->state.referer);
  1337. data->state.referer_alloc = FALSE;
  1338. }
  1339. /* Make a copy of the URL without credentials and fragment */
  1340. u = curl_url();
  1341. if(!u)
  1342. return CURLE_OUT_OF_MEMORY;
  1343. uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
  1344. if(!uc)
  1345. uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
  1346. if(!uc)
  1347. uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
  1348. if(!uc)
  1349. uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
  1350. if(!uc)
  1351. uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
  1352. curl_url_cleanup(u);
  1353. if(uc || !referer)
  1354. return CURLE_OUT_OF_MEMORY;
  1355. data->state.referer = referer;
  1356. data->state.referer_alloc = TRUE; /* yes, free this later */
  1357. }
  1358. }
  1359. }
  1360. if((type != FOLLOW_RETRY) &&
  1361. (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
  1362. Curl_is_absolute_url(newurl, NULL, 0, FALSE)) {
  1363. /* If this is not redirect due to a 401 or 407 response and an absolute
  1364. URL: don't allow a custom port number */
  1365. disallowport = TRUE;
  1366. }
  1367. DEBUGASSERT(data->state.uh);
  1368. uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
  1369. (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
  1370. ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
  1371. CURLU_ALLOW_SPACE |
  1372. (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
  1373. if(uc) {
  1374. if(type != FOLLOW_FAKE) {
  1375. failf(data, "The redirect target URL could not be parsed: %s",
  1376. curl_url_strerror(uc));
  1377. return Curl_uc_to_curlcode(uc);
  1378. }
  1379. /* the URL could not be parsed for some reason, but since this is FAKE
  1380. mode, just duplicate the field as-is */
  1381. newurl = strdup(newurl);
  1382. if(!newurl)
  1383. return CURLE_OUT_OF_MEMORY;
  1384. }
  1385. else {
  1386. uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
  1387. if(uc)
  1388. return Curl_uc_to_curlcode(uc);
  1389. /* Clear auth if this redirects to a different port number or protocol,
  1390. unless permitted */
  1391. if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
  1392. char *portnum;
  1393. int port;
  1394. bool clear = FALSE;
  1395. if(data->set.use_port && data->state.allow_port)
  1396. /* a custom port is used */
  1397. port = (int)data->set.use_port;
  1398. else {
  1399. uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
  1400. CURLU_DEFAULT_PORT);
  1401. if(uc) {
  1402. free(newurl);
  1403. return Curl_uc_to_curlcode(uc);
  1404. }
  1405. port = atoi(portnum);
  1406. free(portnum);
  1407. }
  1408. if(port != data->info.conn_remote_port) {
  1409. infof(data, "Clear auth, redirects to port from %u to %u",
  1410. data->info.conn_remote_port, port);
  1411. clear = TRUE;
  1412. }
  1413. else {
  1414. char *scheme;
  1415. const struct Curl_handler *p;
  1416. uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
  1417. if(uc) {
  1418. free(newurl);
  1419. return Curl_uc_to_curlcode(uc);
  1420. }
  1421. p = Curl_builtin_scheme(scheme, CURL_ZERO_TERMINATED);
  1422. if(p && (p->protocol != data->info.conn_protocol)) {
  1423. infof(data, "Clear auth, redirects scheme from %s to %s",
  1424. data->info.conn_scheme, scheme);
  1425. clear = TRUE;
  1426. }
  1427. free(scheme);
  1428. }
  1429. if(clear) {
  1430. Curl_safefree(data->state.aptr.user);
  1431. Curl_safefree(data->state.aptr.passwd);
  1432. }
  1433. }
  1434. }
  1435. if(type == FOLLOW_FAKE) {
  1436. /* we're only figuring out the new url if we would've followed locations
  1437. but now we're done so we can get out! */
  1438. data->info.wouldredirect = newurl;
  1439. if(reachedmax) {
  1440. failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
  1441. return CURLE_TOO_MANY_REDIRECTS;
  1442. }
  1443. return CURLE_OK;
  1444. }
  1445. if(disallowport)
  1446. data->state.allow_port = FALSE;
  1447. if(data->state.url_alloc)
  1448. Curl_safefree(data->state.url);
  1449. data->state.url = newurl;
  1450. data->state.url_alloc = TRUE;
  1451. infof(data, "Issue another request to this URL: '%s'", data->state.url);
  1452. /*
  1453. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1454. * differently based on exactly what return code there was.
  1455. *
  1456. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1457. * an HTTP (proxy-) authentication scheme other than Basic.
  1458. */
  1459. switch(data->info.httpcode) {
  1460. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1461. Authorization: XXXX header in the HTTP request code snippet */
  1462. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1463. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1464. /* 300 - Multiple Choices */
  1465. /* 306 - Not used */
  1466. /* 307 - Temporary Redirect */
  1467. default: /* for all above (and the unknown ones) */
  1468. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1469. * seem to be OK to POST to.
  1470. */
  1471. break;
  1472. case 301: /* Moved Permanently */
  1473. /* (quote from RFC7231, section 6.4.2)
  1474. *
  1475. * Note: For historical reasons, a user agent MAY change the request
  1476. * method from POST to GET for the subsequent request. If this
  1477. * behavior is undesired, the 307 (Temporary Redirect) status code
  1478. * can be used instead.
  1479. *
  1480. * ----
  1481. *
  1482. * Many webservers expect this, so these servers often answers to a POST
  1483. * request with an error page. To be sure that libcurl gets the page that
  1484. * most user agents would get, libcurl has to force GET.
  1485. *
  1486. * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
  1487. * can be overridden with CURLOPT_POSTREDIR.
  1488. */
  1489. if((data->state.httpreq == HTTPREQ_POST
  1490. || data->state.httpreq == HTTPREQ_POST_FORM
  1491. || data->state.httpreq == HTTPREQ_POST_MIME)
  1492. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1493. infof(data, "Switch from POST to GET");
  1494. data->state.httpreq = HTTPREQ_GET;
  1495. }
  1496. break;
  1497. case 302: /* Found */
  1498. /* (quote from RFC7231, section 6.4.3)
  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_302)) {
  1518. infof(data, "Switch from POST to GET");
  1519. data->state.httpreq = HTTPREQ_GET;
  1520. }
  1521. break;
  1522. case 303: /* See Other */
  1523. /* 'See Other' location is not the resource but a substitute for the
  1524. * resource. In this case we switch the method to GET/HEAD, unless the
  1525. * method is POST and the user specified to keep it as POST.
  1526. * https://github.com/curl/curl/issues/5237#issuecomment-614641049
  1527. */
  1528. if(data->state.httpreq != HTTPREQ_GET &&
  1529. ((data->state.httpreq != HTTPREQ_POST &&
  1530. data->state.httpreq != HTTPREQ_POST_FORM &&
  1531. data->state.httpreq != HTTPREQ_POST_MIME) ||
  1532. !(data->set.keep_post & CURL_REDIR_POST_303))) {
  1533. data->state.httpreq = HTTPREQ_GET;
  1534. infof(data, "Switch to %s",
  1535. data->req.no_body?"HEAD":"GET");
  1536. }
  1537. break;
  1538. case 304: /* Not Modified */
  1539. /* 304 means we did a conditional request and it was "Not modified".
  1540. * We shouldn't get any Location: header in this response!
  1541. */
  1542. break;
  1543. case 305: /* Use Proxy */
  1544. /* (quote from RFC2616, section 10.3.6):
  1545. * "The requested resource MUST be accessed through the proxy given
  1546. * by the Location field. The Location field gives the URI of the
  1547. * proxy. The recipient is expected to repeat this single request
  1548. * via the proxy. 305 responses MUST only be generated by origin
  1549. * servers."
  1550. */
  1551. break;
  1552. }
  1553. Curl_pgrsTime(data, TIMER_REDIRECT);
  1554. Curl_pgrsResetTransferSizes(data);
  1555. return CURLE_OK;
  1556. #endif /* CURL_DISABLE_HTTP */
  1557. }
  1558. /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
  1559. NOTE: that the *url is malloc()ed. */
  1560. CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
  1561. {
  1562. struct connectdata *conn = data->conn;
  1563. bool retry = FALSE;
  1564. *url = NULL;
  1565. /* if we're talking upload, we can't do the checks below, unless the protocol
  1566. is HTTP as when uploading over HTTP we will still get a response */
  1567. if(data->state.upload &&
  1568. !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
  1569. return CURLE_OK;
  1570. if((data->req.bytecount + data->req.headerbytecount == 0) &&
  1571. conn->bits.reuse &&
  1572. (!data->req.no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP))
  1573. #ifndef CURL_DISABLE_RTSP
  1574. && (data->set.rtspreq != RTSPREQ_RECEIVE)
  1575. #endif
  1576. )
  1577. /* We got no data, we attempted to reuse a connection. For HTTP this
  1578. can be a retry so we try again regardless if we expected a body.
  1579. For other protocols we only try again only if we expected a body.
  1580. This might happen if the connection was left alive when we were
  1581. done using it before, but that was closed when we wanted to read from
  1582. it again. Bad luck. Retry the same request on a fresh connect! */
  1583. retry = TRUE;
  1584. else if(data->state.refused_stream &&
  1585. (data->req.bytecount + data->req.headerbytecount == 0) ) {
  1586. /* This was sent on a refused stream, safe to rerun. A refused stream
  1587. error can typically only happen on HTTP/2 level if the stream is safe
  1588. to issue again, but the nghttp2 API can deliver the message to other
  1589. streams as well, which is why this adds the check the data counters
  1590. too. */
  1591. infof(data, "REFUSED_STREAM, retrying a fresh connect");
  1592. data->state.refused_stream = FALSE; /* clear again */
  1593. retry = TRUE;
  1594. }
  1595. if(retry) {
  1596. #define CONN_MAX_RETRIES 5
  1597. if(data->state.retrycount++ >= CONN_MAX_RETRIES) {
  1598. failf(data, "Connection died, tried %d times before giving up",
  1599. CONN_MAX_RETRIES);
  1600. data->state.retrycount = 0;
  1601. return CURLE_SEND_ERROR;
  1602. }
  1603. infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
  1604. data->state.retrycount);
  1605. *url = strdup(data->state.url);
  1606. if(!*url)
  1607. return CURLE_OUT_OF_MEMORY;
  1608. connclose(conn, "retry"); /* close this connection */
  1609. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1610. to retry. Marking it this way should
  1611. prevent i.e HTTP transfers to return
  1612. error just because nothing has been
  1613. transferred! */
  1614. if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1615. data->req.writebytecount) {
  1616. data->state.rewindbeforesend = TRUE;
  1617. infof(data, "state.rewindbeforesend = TRUE");
  1618. }
  1619. }
  1620. return CURLE_OK;
  1621. }
  1622. /*
  1623. * Curl_setup_transfer() is called to setup some basic properties for the
  1624. * upcoming transfer.
  1625. */
  1626. void
  1627. Curl_setup_transfer(
  1628. struct Curl_easy *data, /* transfer */
  1629. int sockindex, /* socket index to read from or -1 */
  1630. curl_off_t size, /* -1 if unknown at this point */
  1631. bool getheader, /* TRUE if header parsing is wanted */
  1632. int writesockindex /* socket index to write to, it may very well be
  1633. the same we read from. -1 disables */
  1634. )
  1635. {
  1636. struct SingleRequest *k = &data->req;
  1637. struct connectdata *conn = data->conn;
  1638. struct HTTP *http = data->req.p.http;
  1639. bool httpsending;
  1640. DEBUGASSERT(conn != NULL);
  1641. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  1642. httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1643. (http->sending == HTTPSEND_REQUEST));
  1644. if(conn->bits.multiplex || conn->httpversion >= 20 || httpsending) {
  1645. /* when multiplexing, the read/write sockets need to be the same! */
  1646. conn->sockfd = sockindex == -1 ?
  1647. ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) :
  1648. conn->sock[sockindex];
  1649. conn->writesockfd = conn->sockfd;
  1650. if(httpsending)
  1651. /* special and very HTTP-specific */
  1652. writesockindex = FIRSTSOCKET;
  1653. }
  1654. else {
  1655. conn->sockfd = sockindex == -1 ?
  1656. CURL_SOCKET_BAD : conn->sock[sockindex];
  1657. conn->writesockfd = writesockindex == -1 ?
  1658. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1659. }
  1660. k->getheader = getheader;
  1661. k->size = size;
  1662. /* The code sequence below is placed in this function just because all
  1663. necessary input is not always known in do_complete() as this function may
  1664. be called after that */
  1665. if(!k->getheader) {
  1666. k->header = FALSE;
  1667. if(size > 0)
  1668. Curl_pgrsSetDownloadSize(data, size);
  1669. }
  1670. /* we want header and/or body, if neither then don't do this! */
  1671. if(k->getheader || !data->req.no_body) {
  1672. if(sockindex != -1)
  1673. k->keepon |= KEEP_RECV;
  1674. if(writesockindex != -1) {
  1675. /* HTTP 1.1 magic:
  1676. Even if we require a 100-return code before uploading data, we might
  1677. need to write data before that since the REQUEST may not have been
  1678. finished sent off just yet.
  1679. Thus, we must check if the request has been sent before we set the
  1680. state info where we wait for the 100-return code
  1681. */
  1682. if((data->state.expect100header) &&
  1683. (conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1684. (http->sending == HTTPSEND_BODY)) {
  1685. /* wait with write until we either got 100-continue or a timeout */
  1686. k->exp100 = EXP100_AWAITING_CONTINUE;
  1687. k->start100 = Curl_now();
  1688. /* Set a timeout for the multi interface. Add the inaccuracy margin so
  1689. that we don't fire slightly too early and get denied to run. */
  1690. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  1691. }
  1692. else {
  1693. if(data->state.expect100header)
  1694. /* when we've sent off the rest of the headers, we must await a
  1695. 100-continue but first finish sending the request */
  1696. k->exp100 = EXP100_SENDING_REQUEST;
  1697. /* enable the write bit when we're not waiting for continue */
  1698. k->keepon |= KEEP_SEND;
  1699. }
  1700. } /* if(writesockindex != -1) */
  1701. } /* if(k->getheader || !data->req.no_body) */
  1702. }