transfer.c 65 KB

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