VirtualBox

source: vbox/trunk/src/libs/curl-7.83.1/lib/transfer.c@ 97138

最後變更 在這個檔案從97138是 95312,由 vboxsync 提交於 3 年 前

libs/{curl,libxml2}: OSE export fixes, bugref:8515

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette