transfer.c 63 KB

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