transfer.c 55 KB

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