1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
24 #include "strtoofft.h"
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
45 #ifdef HAVE_SYS_PARAM_H
46 #include <sys/param.h>
49 #ifdef HAVE_SYS_SELECT_H
50 #include <sys/select.h>
51 #elif defined(HAVE_UNISTD_H)
56 #error "We can't compile without socket() support!"
60 #include <curl/curl.h>
63 #include "content_encoding.h"
67 #include "speedcheck.h"
72 #include "vtls/vtls.h"
79 #include "urlapi-int.h"
84 /* The last 3 #include files should be in this order */
85 #include "curl_printf.h"
86 #include "curl_memory.h"
89 #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
90 !defined(CURL_DISABLE_IMAP)
92 * checkheaders() checks the linked list of custom headers for a
93 * particular header (prefix). Provide the prefix without colon!
95 * Returns a pointer to the first matching header or NULL if none matched.
97 char *Curl_checkheaders(const struct Curl_easy *data,
98 const char *thisheader,
101 struct curl_slist *head;
102 DEBUGASSERT(thislen);
103 DEBUGASSERT(thisheader[thislen-1] != ':');
105 for(head = data->set.headers; head; head = head->next) {
106 if(strncasecompare(head->data, thisheader, thislen) &&
107 Curl_headersep(head->data[thislen]) )
115 CURLcode Curl_get_upload_buffer(struct Curl_easy *data)
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;
125 #ifndef CURL_DISABLE_HTTP
127 * This function will be called to loop through the trailers buffer
128 * until no more data is available for sending.
130 static size_t trailers_read(char *buffer, size_t size, size_t nitems,
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;
140 Curl_dyn_ptr(trailers_buf) + data->state.trailers_bytes_sent,
142 data->state.trailers_bytes_sent += to_copy;
147 static size_t trailers_left(void *raw)
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;
156 * This function will call the read callback to fill our buffer with data
159 CURLcode Curl_fillreadbuffer(struct Curl_easy *data, size_t bytes,
162 size_t buffersize = bytes;
165 curl_read_callback readfunc = NULL;
166 void *extra_data = NULL;
168 #ifndef CURL_DISABLE_HTTP
169 if(data->state.trailers_state == TRAILERS_INITIALIZED) {
170 struct curl_slist *trailers = NULL;
172 int trailers_ret_code;
174 /* at this point we already verified that the callback exists
175 so we compile and store the trailers buffer, then proceed */
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);
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,
191 failf(data, "operation aborted by trailing headers callback");
193 result = CURLE_ABORTED_BY_CALLBACK;
196 Curl_dyn_free(&data->state.trailers_buf);
197 curl_slist_free_all(trailers);
200 infof(data, "Successfully compiled trailers.");
201 curl_slist_free_all(trailers);
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 */
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
222 readfunc = trailers_read;
223 extra_data = (void *)data;
228 readfunc = data->state.fread_func;
229 extra_data = data->state.in;
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);
237 if(nread == CURL_READFUNC_ABORT) {
238 failf(data, "operation aborted by callback");
240 return CURLE_ABORTED_BY_CALLBACK;
242 if(nread == CURL_READFUNC_PAUSE) {
243 struct SingleRequest *k = &data->req;
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;
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);
261 return CURLE_OK; /* nothing was read */
263 else if(nread > buffersize) {
264 /* the read function returned a too large value */
266 failf(data, "read function returned funny value");
267 return CURLE_READ_ERROR;
270 if(!data->req.forbidchunk && data->req.upload_chunky) {
271 /* if chunked Transfer-Encoding
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.
286 bool added_crlf = FALSE;
288 const char *endofline_native;
289 const char *endofline_network;
292 #ifdef CURL_DO_LINEEND_CONV
293 (data->state.prefer_ascii) ||
296 /* \n will become \r\n later on */
297 endofline_native = "\n";
298 endofline_network = "\x0a";
301 endofline_native = "\r\n";
302 endofline_network = "\x0d\x0a";
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);
311 /* move buffer pointer */
312 data->req.upload_fromhere -= hexlen;
315 /* copy the prefix to the buffer, leaving out the NUL */
316 memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
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;
329 memcpy(data->req.upload_fromhere + nread,
331 strlen(endofline_network));
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.");
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;
354 "Signaling end of chunked upload via terminating chunk.");
358 nread += strlen(endofline_network); /* for the added end of line */
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.
372 CURLcode Curl_readrewind(struct Curl_easy *data)
374 struct connectdata *conn = data->conn;
375 curl_mimepart *mimepart = &data->set.mimepost;
377 conn->bits.rewindaftersend = FALSE; /* we rewind now */
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
383 data->req.keepon &= ~KEEP_SEND;
385 /* We have sent away data. If not using CURLOPT_POSTFIELDS or
386 CURLOPT_HTTPPOST, call app to rewind
388 if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
389 struct HTTP *http = data->req.p.http;
392 mimepart = http->sendit;
394 if(data->set.postfields)
396 else if(data->state.httpreq == HTTPREQ_POST_MIME ||
397 data->state.httpreq == HTTPREQ_POST_FORM) {
398 CURLcode result = Curl_mime_rewind(mimepart);
400 failf(data, "Cannot rewind mime/post data");
405 if(data->set.seek_func) {
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);
412 failf(data, "seek callback returned error %d", (int)err);
413 return CURLE_SEND_FAIL_REWIND;
416 else if(data->set.ioctl_func) {
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);
426 failf(data, "ioctl callback returned error %d", (int)err);
427 return CURLE_SEND_FAIL_REWIND;
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 */
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;
448 static int data_pending(const struct Curl_easy *data)
450 struct connectdata *conn = data->conn;
453 if(conn->transport == TRNSPRT_QUIC)
454 return Curl_quic_data_pending(data);
457 if(conn->handler->protocol&PROTO_FAMILY_FTP)
458 return Curl_ssl_data_pending(conn, SECONDARYSOCKET);
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) ||
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) ||
473 Curl_ssl_data_pending(conn, FIRSTSOCKET);
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
480 bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
482 if((timeofdoc == 0) || (data->set.timevalue == 0))
485 switch(data->set.timecondition) {
486 case CURL_TIMECOND_IFMODSINCE:
488 if(timeofdoc <= data->set.timevalue) {
490 "The requested document is not new enough");
491 data->info.timecond = TRUE;
495 case CURL_TIMECOND_IFUNMODSINCE:
496 if(timeofdoc >= data->set.timevalue) {
498 "The requested document is not old enough");
499 data->info.timecond = TRUE;
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
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!
516 static CURLcode readwrite_data(struct Curl_easy *data,
517 struct connectdata *conn,
518 struct SingleRequest *k,
519 int *didwhat, bool *done,
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 */
527 char *buf = data->state.buffer;
533 /* This is where we loop until we have read everything there is to
534 read or we get a CURLE_AGAIN */
536 bool is_empty_data = FALSE;
537 size_t buffersize = data->set.buffer_size;
538 size_t bytestoread = buffersize;
540 bool is_http2 = ((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
541 (conn->httpversion == 20));
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. */
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;
561 /* receive data from the network! */
562 result = Curl_read(data, conn->sockfd, buf, bytestoread, &nread);
564 /* read would've blocked */
565 if(CURLE_AGAIN == result)
566 break; /* get out of loop */
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"));
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();
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;
589 if(0 < nread || is_empty_data) {
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! */
596 if(is_http2 && !nread)
597 DEBUGF(infof(data, "nread == 0, stream closed, bailing"));
600 DEBUGF(infof(data, "nread <= 0, server closed connection, bailing"));
601 k->keepon &= ~KEEP_RECV;
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. */
609 if(conn->handler->readwrite) {
610 result = conn->handler->readwrite(data, conn, &nread, &readmore);
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. */
621 /* we are in parse-the-header-mode */
622 bool stop_reading = FALSE;
623 result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
627 if(conn->handler->readwrite &&
628 (k->maxdownload <= 0 && nread > 0)) {
629 result = conn->handler->readwrite(data, conn, &nread, &readmore);
637 /* We've stopped dealing with input, get out of the do-while loop */
643 " url = %s (zero-length body)",
644 nread, data->state.up.path);
650 #endif /* CURL_DISABLE_HTTP */
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
656 if(!k->header && (nread > 0 || is_empty_data)) {
658 if(data->set.opt_no_body) {
659 /* data arrives although we want none, bail out */
660 streamclose(conn, "ignoring body");
662 return CURLE_WEIRD_SERVER_REPLY;
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);
675 } /* this is the first time we write a body part */
676 #endif /* CURL_DISABLE_HTTP */
680 /* pass data to the debug function before it gets "dechunked" */
681 if(data->set.verbose) {
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);
691 Curl_debug(data, CURLINFO_DATA_IN,
692 k->str, (size_t)nread);
695 #ifndef CURL_DISABLE_HTTP
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.
705 Curl_httpchunk_read(data, k->str, nread, &nread, &extra);
707 if(CHUNKE_OK < res) {
708 if(CHUNKE_PASSTHRU_ERROR == res) {
709 failf(data, "Failed reading the chunked-encoded stream");
712 failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res));
713 return CURLE_RECV_ERROR;
715 if(CHUNKE_STOP == res) {
716 /* we're done reading chunks! */
717 k->keepon &= ~KEEP_RECV; /* read no more */
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);
727 /* If it returned OK, we just keep going */
729 #endif /* CURL_DISABLE_HTTP */
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;
738 if((-1 != k->maxdownload) &&
739 (k->bytecount + nread >= k->maxdownload)) {
741 excess = (size_t)(k->bytecount + nread - k->maxdownload);
742 if(excess > 0 && !k->ignorebody) {
744 "Excess found in a read:"
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");
753 nread = (ssize_t) (k->maxdownload - k->bytecount);
754 if(nread < 0) /* this should be unusual */
757 k->keepon &= ~KEEP_RECV; /* we're done reading */
760 k->bytecount += nread;
762 Curl_pgrsSetDownloadCounter(data, k->bytecount);
764 if(!k->chunk && (nread || k->badheader || is_empty_data)) {
765 /* If this is chunky transfer, it was already written */
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);
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),
778 result = Curl_client_write(data, CLIENTWRITE_BODY,
779 Curl_dyn_ptr(&data->state.headerb),
780 (size_t)k->maxdownload);
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
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);
797 #endif /* CURL_DISABLE_POP3 */
798 result = Curl_client_write(data, CLIENTWRITE_BODY, k->str,
802 else if(!k->ignorebody && nread)
803 result = Curl_unencode_write(data, k->writer_stack, k->str, nread);
805 k->badheader = HEADER_NORMAL; /* taken care of now */
811 } /* if(!header and data to read) */
813 if(conn->handler->readwrite && excess) {
814 /* Parse the excess data */
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;
822 nread = (ssize_t)excess;
824 result = conn->handler->readwrite(data, conn, &nread, &readmore);
829 k->keepon |= KEEP_RECV; /* we're not done reading */
834 /* if we received nothing, the server closed the connection and we
836 k->keepon &= ~KEEP_RECV;
839 if(k->keepon & KEEP_RECV_PAUSE) {
840 /* this is a paused transfer */
844 } while(data_pending(data) && maxloops--);
847 /* we mark it as read-again-please */
848 conn->cselect_bits = CURL_CSELECT_IN;
852 if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
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 */
864 CURLcode Curl_done_sending(struct Curl_easy *data,
865 struct SingleRequest *k)
867 struct connectdata *conn = data->conn;
868 k->keepon &= ~KEEP_SEND; /* we're done writing */
870 /* These functions should be moved into the handler struct! */
871 Curl_http2_done_sending(data, conn);
872 Curl_quic_done_sending(data);
874 if(conn->bits.rewindaftersend) {
875 CURLcode result = Curl_readrewind(data);
882 #if defined(WIN32) && defined(USE_WINSOCK)
883 #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
884 #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
887 static void win_update_buffer_size(curl_socket_t sockfd)
892 result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
893 &ideal, sizeof(ideal), &ideallen, 0, 0);
895 setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
896 (const char *)&ideal, sizeof(ideal));
900 #define win_update_buffer_size(x)
904 * Send data to upload to the server, when the socket is writable.
906 static CURLcode readwrite_upload(struct Curl_easy *data,
907 struct connectdata *conn,
911 ssize_t bytes_written;
913 ssize_t nread; /* number of bytes read */
914 bool sending_http_headers = FALSE;
915 struct SingleRequest *k = &data->req;
917 if((k->bytecount == 0) && (k->writebytecount == 0))
918 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
920 *didwhat |= KEEP_SEND;
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);
931 /* init the "upload from here" pointer */
932 k->upload_fromhere = data->state.ulbuf;
934 if(!k->upload_done) {
935 /* HTTP pollution, this should be written nicer to become more
936 protocol agnostic. */
938 struct HTTP *http = k->p.http;
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);
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;
960 sending_http_headers = FALSE;
963 result = Curl_fillreadbuffer(data, data->set.upload_buffer_size,
971 nread = 0; /* we're done uploading/reading */
973 if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
974 /* this is a paused transfer */
978 result = Curl_done_sending(data, k);
984 /* store number of bytes available for upload */
985 k->upload_present = nread;
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) ||
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");
1000 return CURLE_OUT_OF_MEMORY;
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.
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++;
1022 data->state.scratch[si] = k->upload_fromhere[i];
1026 /* only perform the special operation if we really did replace
1030 /* upload from the new (replaced) buffer instead */
1031 k->upload_fromhere = data->state.scratch;
1033 /* set the new amount too */
1034 k->upload_present = nread;
1038 #ifndef CURL_DISABLE_SMTP
1039 if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
1040 result = Curl_smtp_escape_eob(data, nread);
1044 #endif /* CURL_DISABLE_SMTP */
1045 } /* if 0 == k->upload_present */
1047 /* We have a partial buffer left from a previous "round". Use
1048 that instead of reading more data */
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 */
1060 win_update_buffer_size(conn->writesockfd);
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 */
1071 nbody = bytes_written;
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],
1079 k->writebytecount += nbody;
1080 Curl_pgrsSetUploadCounter(data, k->writebytecount);
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");
1090 if(k->upload_present != bytes_written) {
1091 /* we only wrote a part of the buffer (if anything), deal with it! */
1093 /* store the amount of bytes left in the buffer to write */
1094 k->upload_present -= bytes_written;
1096 /* advance the pointer where to find the buffer when the next send
1098 k->upload_fromhere += bytes_written;
1101 /* we've uploaded that buffer now */
1102 result = Curl_get_upload_buffer(data);
1105 k->upload_fromhere = data->state.ulbuf;
1106 k->upload_present = 0; /* no more bytes left */
1108 if(k->upload_done) {
1109 result = Curl_done_sending(data, k);
1116 } while(0); /* just to break out from! */
1122 * Curl_readwrite() is the low-level function to be called when data is to
1123 * be read and written to/from the connection.
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!
1128 CURLcode Curl_readwrite(struct connectdata *conn,
1129 struct Curl_easy *data,
1133 struct SingleRequest *k = &data->req;
1137 curl_socket_t fd_read;
1138 curl_socket_t fd_write;
1139 int select_res = conn->cselect_bits;
1141 conn->cselect_bits = 0;
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 */
1146 if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
1147 fd_read = conn->sockfd;
1149 fd_read = CURL_SOCKET_BAD;
1151 if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
1152 fd_write = conn->writesockfd;
1154 fd_write = CURL_SOCKET_BAD;
1156 if(data->state.drain) {
1157 select_res |= CURL_CSELECT_IN;
1158 DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data"));
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);
1165 if(select_res == CURL_CSELECT_ERR) {
1166 failf(data, "select/poll returned error");
1167 return CURLE_SEND_ERROR;
1171 if(conn->datastream) {
1172 result = conn->datastream(data, conn, &didwhat, done, select_res);
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
1181 if((k->keepon & KEEP_RECV) && (select_res & CURL_CSELECT_IN)) {
1182 result = readwrite_data(data, conn, k, &didwhat, done, comeback);
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)) {
1191 result = readwrite_upload(data, conn, &didwhat);
1199 k->now = Curl_now();
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
1207 /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
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.
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");
1227 if(Curl_pgrsUpdate(data))
1228 result = CURLE_ABORTED_BY_CALLBACK;
1230 result = Curl_speedcheck(data, k->now);
1235 if(0 > Curl_timeleft(data, &k->now, FALSE)) {
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);
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),
1249 return CURLE_OPERATION_TIMEDOUT;
1254 * The transfer has been performed. Just make some general checks before
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.
1265 (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1266 #endif /* CURL_DO_LINEEND_CONV */
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;
1272 if(!(data->set.opt_no_body) && k->chunk &&
1273 (conn->chunk.state != CHUNK_STOP)) {
1275 * In chunked mode, return an error if the connection is closed prior to
1276 * the empty (terminating) chunk is read.
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.
1283 failf(data, "transfer closed with outstanding read data remaining");
1284 return CURLE_PARTIAL_FILE;
1286 if(Curl_pgrsUpdate(data))
1287 return CURLE_ABORTED_BY_CALLBACK;
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;
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.
1304 int Curl_single_getsock(struct Curl_easy *data,
1305 struct connectdata *conn,
1306 curl_socket_t *sock)
1308 int bitmap = GETSOCK_BLANK;
1309 unsigned sockindex = 0;
1311 if(conn->handler->perform_getsock)
1312 return conn->handler->perform_getsock(data, conn, sock);
1314 /* don't include HOLD and PAUSE connections */
1315 if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
1317 DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1319 bitmap |= GETSOCK_READSOCK(sockindex);
1320 sock[sockindex] = conn->sockfd;
1323 /* don't include HOLD and PAUSE connections */
1324 if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
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 */
1333 DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1335 sock[sockindex] = conn->writesockfd;
1338 bitmap |= GETSOCK_WRITESOCK(sockindex);
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 */
1346 void Curl_init_CONNECT(struct Curl_easy *data)
1348 data->state.fread_func = data->set.fread_func_set;
1349 data->state.in = data->set.in_set;
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.
1357 CURLcode Curl_pretransfer(struct Curl_easy *data)
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;
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;
1374 if(!data->state.url && data->set.uh) {
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);
1380 failf(data, "No URL set");
1381 return CURLE_URL_MALFORMAT;
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];
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);
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);
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);
1417 data->state.infilesize = 0;
1419 /* If there is a list of cookie files to read, do it now! */
1420 if(data->state.cookielist)
1421 Curl_cookie_loadfiles(data);
1423 /* If there is a list of host pairs to deal with */
1424 if(data->state.resolve)
1425 result = Curl_loadhostpairs(data);
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;
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);
1441 Curl_initinfo(data); /* reset session-specific information "variables" */
1442 Curl_pgrsResetTransferSizes(data);
1443 Curl_pgrsStartNow(data);
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;
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 */
1457 return CURLE_OUT_OF_MEMORY;
1461 Curl_http2_init_state(&data->state);
1462 result = Curl_hsts_loadcb(data, data->hsts);
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
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;
1479 result = Curl_setstropt(&data->state.aptr.user,
1480 data->set.str[STRING_USERNAME]);
1482 result = Curl_setstropt(&data->state.aptr.passwd,
1483 data->set.str[STRING_PASSWORD]);
1485 result = Curl_setstropt(&data->state.aptr.proxyuser,
1486 data->set.str[STRING_PROXYUSERNAME]);
1488 result = Curl_setstropt(&data->state.aptr.proxypasswd,
1489 data->set.str[STRING_PROXYPASSWORD]);
1491 data->req.headerbytecount = 0;
1492 Curl_headers_cleanup(data);
1497 * Curl_posttransfer() is called immediately after a transfer ends
1499 CURLcode Curl_posttransfer(struct Curl_easy *data)
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);
1506 (void)data; /* unused parameter */
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.
1516 * This function DOES NOT FREE the given url.
1518 CURLcode Curl_follow(struct Curl_easy *data,
1519 char *newurl, /* the Location: string */
1520 followtype type) /* see transfer.h */
1522 #ifdef CURL_DISABLE_HTTP
1526 /* Location: following will not happen when HTTP is disabled */
1527 return CURLE_TOO_MANY_REDIRECTS;
1530 /* Location: redirect */
1531 bool disallowport = FALSE;
1532 bool reachedmax = FALSE;
1535 DEBUGASSERT(type != FOLLOW_NONE);
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)) {
1543 type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
1547 /* mark the next request as a followed location: */
1548 data->state.this_is_a_follow = TRUE;
1550 data->state.followlocation++; /* count location-followers */
1552 if(data->set.http_auto_referer) {
1554 char *referer = NULL;
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 */
1560 if(data->state.referer_alloc) {
1561 Curl_safefree(data->state.referer);
1562 data->state.referer_alloc = FALSE;
1565 /* Make a copy of the URL without crenditals and fragment */
1568 return CURLE_OUT_OF_MEMORY;
1570 uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0);
1572 uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
1574 uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
1576 uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
1578 uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
1580 curl_url_cleanup(u);
1583 return CURLE_OUT_OF_MEMORY;
1585 data->state.referer = referer;
1586 data->state.referer_alloc = TRUE; /* yes, free this later */
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;
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) |
1604 if(type != FOLLOW_FAKE)
1605 return Curl_uc_to_curlcode(uc);
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);
1611 return CURLE_OUT_OF_MEMORY;
1614 uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
1616 return Curl_uc_to_curlcode(uc);
1618 /* Clear auth if this redirects to a different port number or protocol,
1620 if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
1625 if(data->set.use_port && data->state.allow_port)
1626 /* a custom port is used */
1627 port = (int)data->set.use_port;
1629 uc = curl_url_get(data->state.uh, CURLUPART_PORT, &portnum,
1630 CURLU_DEFAULT_PORT);
1633 return Curl_uc_to_curlcode(uc);
1635 port = atoi(portnum);
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);
1645 const struct Curl_handler *p;
1646 uc = curl_url_get(data->state.uh, CURLUPART_SCHEME, &scheme, 0);
1649 return Curl_uc_to_curlcode(uc);
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);
1661 Curl_safefree(data->state.aptr.user);
1662 Curl_safefree(data->state.aptr.passwd);
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;
1673 failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
1674 return CURLE_TOO_MANY_REDIRECTS;
1680 data->state.allow_port = FALSE;
1682 if(data->state.url_alloc)
1683 Curl_safefree(data->state.url);
1685 data->state.url = newurl;
1686 data->state.url_alloc = TRUE;
1688 infof(data, "Issue another request to this URL: '%s'", data->state.url);
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.
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.
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.
1710 case 301: /* Moved Permanently */
1711 /* (quote from RFC7231, section 6.4.2)
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.
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.
1724 * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1725 * can be overridden with CURLOPT_POSTREDIR.
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;
1735 case 302: /* Found */
1736 /* (quote from RFC7231, section 6.4.3)
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.
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.
1749 * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1750 * can be overridden with CURLOPT_POSTREDIR.
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;
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
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");
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!
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
1793 Curl_pgrsTime(data, TIMER_REDIRECT);
1794 Curl_pgrsResetTransferSizes(data);
1797 #endif /* CURL_DISABLE_HTTP */
1800 /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
1802 NOTE: that the *url is malloc()ed. */
1803 CURLcode Curl_retry_request(struct Curl_easy *data, char **url)
1805 struct connectdata *conn = data->conn;
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)))
1815 if((data->req.bytecount + data->req.headerbytecount == 0) &&
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.
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! */
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
1835 infof(data, "REFUSED_STREAM, retrying a fresh connect");
1836 data->state.refused_stream = FALSE; /* clear again */
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",
1844 data->state.retrycount = 0;
1845 return CURLE_SEND_ERROR;
1847 infof(data, "Connection died, retrying a fresh connect (retry count: %d)",
1848 data->state.retrycount);
1849 *url = strdup(data->state.url);
1851 return CURLE_OUT_OF_MEMORY;
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
1861 if(conn->handler->protocol&PROTO_FAMILY_HTTP) {
1862 if(data->req.writebytecount) {
1863 CURLcode result = Curl_readrewind(data);
1865 Curl_safefree(*url);
1875 * Curl_setup_transfer() is called to setup some basic properties for the
1876 * upcoming transfer.
1879 Curl_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 */
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));
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;
1903 /* special and very HTTP-specific */
1904 writesockindex = FIRSTSOCKET;
1907 conn->sockfd = sockindex == -1 ?
1908 CURL_SOCKET_BAD : conn->sock[sockindex];
1909 conn->writesockfd = writesockindex == -1 ?
1910 CURL_SOCKET_BAD:conn->sock[writesockindex];
1912 k->getheader = getheader;
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 */
1923 Curl_pgrsSetDownloadSize(data, size);
1925 /* we want header and/or body, if neither then don't do this! */
1926 if(k->getheader || !data->set.opt_no_body) {
1929 k->keepon |= KEEP_RECV;
1931 if(writesockindex != -1) {
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.
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
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();
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);
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;
1958 /* enable the write bit when we're not waiting for continue */
1959 k->keepon |= KEEP_SEND;
1961 } /* if(writesockindex != -1) */
1962 } /* if(k->getheader || !data->set.opt_no_body) */