transfer.c 64 KB

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