transfer.c 63 KB

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