transfer.c 63 KB

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