transfer.c 63 KB

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