transfer.c 63 KB

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