transfer.c 61 KB

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