1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, 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 http://curl.haxx.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 ***************************************************************************/
25 #include "strtoofft.h"
29 #ifdef HAVE_SYS_SOCKET_H
30 #include <sys/socket.h>
32 #ifdef HAVE_NETINET_IN_H
33 #include <netinet/in.h>
41 #ifdef HAVE_ARPA_INET_H
42 #include <arpa/inet.h>
47 #ifdef HAVE_SYS_IOCTL_H
48 #include <sys/ioctl.h>
54 #ifdef HAVE_SYS_PARAM_H
55 #include <sys/param.h>
58 #ifdef HAVE_SYS_SELECT_H
59 #include <sys/select.h>
63 #error "We can't compile without socket() support!"
67 #include <curl/curl.h>
70 #include "content_encoding.h"
74 #include "speedcheck.h"
80 #include "http_digest.h"
81 #include "curl_ntlm.h"
82 #include "http_negotiate.h"
84 #include "curl_memory.h"
88 #include "non-ascii.h"
90 #define _MPRINTF_REPLACE /* use our functions only */
91 #include <curl/mprintf.h>
93 /* The last #include file should be: */
96 #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
99 * This function will call the read callback to fill our buffer with data
102 CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
104 struct SessionHandle *data = conn->data;
105 size_t buffersize = (size_t)bytes;
107 #ifdef CURL_DOES_CONVERSIONS
108 bool sending_http_headers = FALSE;
110 if((conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) &&
111 (data->state.proto.http->sending == HTTPSEND_REQUEST)) {
112 /* We're sending the HTTP request headers, not the data.
113 Remember that so we don't re-translate them into garbage. */
114 sending_http_headers = TRUE;
118 if(data->req.upload_chunky) {
119 /* if chunked Transfer-Encoding */
120 buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
121 data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
124 /* this function returns a size_t, so we typecast to int to prevent warnings
125 with picky compilers */
126 nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
127 buffersize, conn->fread_in);
129 if(nread == CURL_READFUNC_ABORT) {
130 failf(data, "operation aborted by callback");
132 return CURLE_ABORTED_BY_CALLBACK;
134 else if(nread == CURL_READFUNC_PAUSE) {
135 struct SingleRequest *k = &data->req;
136 /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
137 k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
138 if(data->req.upload_chunky) {
139 /* Back out the preallocation done above */
140 data->req.upload_fromhere -= (8 + 2);
143 return CURLE_OK; /* nothing was read */
145 else if((size_t)nread > buffersize) {
146 /* the read function returned a too large value */
148 failf(data, "read function returned funny value");
149 return CURLE_READ_ERROR;
152 if(!data->req.forbidchunk && data->req.upload_chunky) {
153 /* if chunked Transfer-Encoding
159 /* On non-ASCII platforms the <DATA> may or may not be
160 translated based on set.prefer_ascii while the protocol
161 portion must always be translated to the network encoding.
162 To further complicate matters, line end conversion might be
163 done later on, so we need to prevent CRLFs from becoming
164 CRCRLFs if that's the case. To do this we use bare LFs
165 here, knowing they'll become CRLFs later on.
169 const char *endofline_native;
170 const char *endofline_network;
174 #ifdef CURL_DO_LINEEND_CONV
175 (data->set.prefer_ascii) ||
178 /* \n will become \r\n later on */
179 endofline_native = "\n";
180 endofline_network = "\x0a";
183 endofline_native = "\r\n";
184 endofline_network = "\x0d\x0a";
186 hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
187 "%x%s", nread, endofline_native);
189 /* move buffer pointer */
190 data->req.upload_fromhere -= hexlen;
193 /* copy the prefix to the buffer, leaving out the NUL */
194 memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
196 /* always append ASCII CRLF to the data */
197 memcpy(data->req.upload_fromhere + nread,
199 strlen(endofline_network));
201 #ifdef CURL_DOES_CONVERSIONS
204 if(data->set.prefer_ascii) {
205 /* translate the protocol and data */
209 /* just translate the protocol portion */
210 length = strlen(hexbuffer);
212 res = Curl_convert_to_network(data, data->req.upload_fromhere, length);
213 /* Curl_convert_to_network calls failf if unsuccessful */
216 #endif /* CURL_DOES_CONVERSIONS */
218 if((nread - hexlen) == 0)
219 /* mark this as done once this chunk is transferred */
220 data->req.upload_done = TRUE;
222 nread+=(int)strlen(endofline_native); /* for the added end of line */
224 #ifdef CURL_DOES_CONVERSIONS
225 else if((data->set.prefer_ascii) && (!sending_http_headers)) {
227 res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
228 /* Curl_convert_to_network calls failf if unsuccessful */
232 #endif /* CURL_DOES_CONVERSIONS */
241 * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
242 * POST/PUT with multi-pass authentication when a sending was denied and a
243 * resend is necessary.
245 CURLcode Curl_readrewind(struct connectdata *conn)
247 struct SessionHandle *data = conn->data;
249 conn->bits.rewindaftersend = FALSE; /* we rewind now */
251 /* explicitly switch off sending data on this connection now since we are
252 about to restart a new transfer and thus we want to avoid inadvertently
253 sending more data on the existing connection until the next transfer
255 data->req.keepon &= ~KEEP_SEND;
257 /* We have sent away data. If not using CURLOPT_POSTFIELDS or
258 CURLOPT_HTTPPOST, call app to rewind
260 if(data->set.postfields ||
261 (data->set.httpreq == HTTPREQ_POST_FORM))
264 if(data->set.seek_func) {
267 err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
269 failf(data, "seek callback returned error %d", (int)err);
270 return CURLE_SEND_FAIL_REWIND;
273 else if(data->set.ioctl_func) {
276 err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
277 data->set.ioctl_client);
278 infof(data, "the ioctl callback returned %d\n", (int)err);
281 /* FIXME: convert to a human readable error message */
282 failf(data, "ioctl callback returned error %d", (int)err);
283 return CURLE_SEND_FAIL_REWIND;
287 /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
288 given FILE * stream and we can actually attempt to rewind that
289 ourselves with fseek() */
290 if(data->set.fread_func == (curl_read_callback)fread) {
291 if(-1 != fseek(data->set.in, 0, SEEK_SET))
292 /* successful rewind */
296 /* no callback set or failure above, makes us fail at once */
297 failf(data, "necessary data rewind wasn't possible");
298 return CURLE_SEND_FAIL_REWIND;
304 static int data_pending(const struct connectdata *conn)
306 /* in the case of libssh2, we can never be really sure that we have emptied
307 its internal buffers so we MUST always try until we get EAGAIN back */
308 return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
309 Curl_ssl_data_pending(conn, FIRSTSOCKET);
312 static void read_rewind(struct connectdata *conn,
315 DEBUGASSERT(conn->read_pos >= thismuch);
317 conn->read_pos -= thismuch;
318 conn->bits.stream_was_rewound = TRUE;
325 show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
326 if(conn->master_buffer) {
327 memcpy(buf, conn->master_buffer + conn->read_pos, show);
334 DEBUGF(infof(conn->data,
335 "Buffer after stream rewind (read_pos = %zu): [%s]\n",
336 conn->read_pos, buf));
342 * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
343 * remote document with the time provided by CURLOPT_TIMEVAL
345 bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc)
347 if((timeofdoc == 0) || (data->set.timevalue == 0))
350 switch(data->set.timecondition) {
351 case CURL_TIMECOND_IFMODSINCE:
353 if(timeofdoc <= data->set.timevalue) {
355 "The requested document is not new enough\n");
356 data->info.timecond = TRUE;
360 case CURL_TIMECOND_IFUNMODSINCE:
361 if(timeofdoc >= data->set.timevalue) {
363 "The requested document is not old enough\n");
364 data->info.timecond = TRUE;
374 * Go ahead and do a read if we have a readable socket or if
375 * the stream was rewound (in which case we have data in a
378 static CURLcode readwrite_data(struct SessionHandle *data,
379 struct connectdata *conn,
380 struct SingleRequest *k,
381 int *didwhat, bool *done)
383 CURLcode result = CURLE_OK;
384 ssize_t nread; /* number of bytes read */
385 size_t excess = 0; /* excess bytes read */
386 bool is_empty_data = FALSE;
387 bool readmore = FALSE; /* used by RTP to signal for more data */
391 /* This is where we loop until we have read everything there is to
392 read or we get a CURLE_AGAIN */
394 size_t buffersize = data->set.buffer_size?
395 data->set.buffer_size : BUFSIZE;
396 size_t bytestoread = buffersize;
398 if(k->size != -1 && !k->header) {
399 /* make sure we don't read "too much" if we can help it since we
400 might be pipelining and then someone else might want to read what
402 curl_off_t totalleft = k->size - k->bytecount;
403 if(totalleft < (curl_off_t)bytestoread)
404 bytestoread = (size_t)totalleft;
408 /* receive data from the network! */
409 result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
411 /* read would've blocked */
412 if(CURLE_AGAIN == result)
413 break; /* get out of loop */
419 /* read nothing but since we wanted nothing we consider this an OK
420 situation to proceed from */
424 if((k->bytecount == 0) && (k->writebytecount == 0)) {
425 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
426 if(k->exp100 > EXP100_SEND_DATA)
427 /* set time stamp to compare with when waiting for the 100 */
428 k->start100 = Curl_tvnow();
431 *didwhat |= KEEP_RECV;
432 /* indicates data of zero size, i.e. empty file */
433 is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
435 /* NUL terminate, allowing string ops to be used */
436 if(0 < nread || is_empty_data) {
439 else if(0 >= nread) {
440 /* if we receive 0 or less here, the server closed the connection
441 and we bail out from this! */
442 DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
443 k->keepon &= ~KEEP_RECV;
447 /* Default buffer to use when we write the buffer, it may be changed
448 in the flow below before the actual storing is done. */
451 if(conn->handler->readwrite) {
452 result = conn->handler->readwrite(data, conn, &nread, &readmore);
459 #ifndef CURL_DISABLE_HTTP
460 /* Since this is a two-state thing, we check if we are parsing
461 headers at the moment or not. */
463 /* we are in parse-the-header-mode */
464 bool stop_reading = FALSE;
465 result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
469 if(conn->handler->readwrite &&
470 (k->maxdownload <= 0 && nread > 0)) {
471 result = conn->handler->readwrite(data, conn, &nread, &readmore);
479 /* We've stopped dealing with input, get out of the do-while loop */
482 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
484 "Rewinding stream by : %zd"
485 " bytes on url %s (zero-length body)\n",
486 nread, data->state.path);
487 read_rewind(conn, (size_t)nread);
491 "Excess found in a non pipelined read:"
493 " url = %s (zero-length body)\n",
494 nread, data->state.path);
501 #endif /* CURL_DISABLE_HTTP */
504 /* This is not an 'else if' since it may be a rest from the header
505 parsing, where the beginning of the buffer is headers and the end
507 if(k->str && !k->header && (nread > 0 || is_empty_data)) {
509 #ifndef CURL_DISABLE_HTTP
510 if(0 == k->bodywrites && !is_empty_data) {
511 /* These checks are only made the first time we are about to
512 write a piece of the body */
513 if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
514 /* HTTP-only checks */
516 if(data->req.newurl) {
517 if(conn->bits.close) {
518 /* Abort after the headers if "follow Location" is set
519 and we're set to close anyway. */
520 k->keepon &= ~KEEP_RECV;
524 /* We have a new url to load, but since we want to be able
525 to re-use this connection properly, we read the full
526 response in "ignore more" */
527 k->ignorebody = TRUE;
528 infof(data, "Ignoring the response-body\n");
530 if(data->state.resume_from && !k->content_range &&
531 (data->set.httpreq==HTTPREQ_GET) &&
533 /* we wanted to resume a download, although the server doesn't
534 * seem to support this and we did this with a GET (if it
535 * wasn't a GET we did a POST or PUT resume) */
536 failf(data, "HTTP server doesn't seem to support "
537 "byte ranges. Cannot resume.");
538 return CURLE_RANGE_ERROR;
541 if(data->set.timecondition && !data->state.range) {
542 /* A time condition has been set AND no ranges have been
543 requested. This seems to be what chapter 13.3.4 of
544 RFC 2616 defines to be the correct action for a
547 if(!Curl_meets_timecondition(data, k->timeofdoc)) {
549 /* we abort the transfer before it is completed == we ruin the
550 re-use ability. Close the connection */
551 conn->bits.close = TRUE;
554 } /* we have a time condition */
556 } /* this is HTTP or RTSP */
557 } /* this is the first time we write a body part */
558 #endif /* CURL_DISABLE_HTTP */
562 /* pass data to the debug function before it gets "dechunked" */
563 if(data->set.verbose) {
565 Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
566 (size_t)k->hbuflen, conn);
567 if(k->badheader == HEADER_PARTHEADER)
568 Curl_debug(data, CURLINFO_DATA_IN,
569 k->str, (size_t)nread, conn);
572 Curl_debug(data, CURLINFO_DATA_IN,
573 k->str, (size_t)nread, conn);
576 #ifndef CURL_DISABLE_HTTP
579 * Here comes a chunked transfer flying and we need to decode this
580 * properly. While the name says read, this function both reads
581 * and writes away the data. The returned 'nread' holds the number
582 * of actual data it wrote to the client.
586 Curl_httpchunk_read(conn, k->str, nread, &nread);
588 if(CHUNKE_OK < res) {
589 if(CHUNKE_WRITE_ERROR == res) {
590 failf(data, "Failed writing data");
591 return CURLE_WRITE_ERROR;
593 failf(data, "Problem (%d) in the Chunked-Encoded data", (int)res);
594 return CURLE_RECV_ERROR;
596 else if(CHUNKE_STOP == res) {
598 /* we're done reading chunks! */
599 k->keepon &= ~KEEP_RECV; /* read no more */
601 /* There are now possibly N number of bytes at the end of the
602 str buffer that weren't written to the client.
604 We DO care about this data if we are pipelining.
605 Push it back to be read on the next pass. */
607 dataleft = conn->chunk.dataleft;
609 infof(conn->data, "Leftovers after chunking: %zu bytes\n",
611 if(conn->data->multi &&
612 Curl_multi_canPipeline(conn->data->multi)) {
613 /* only attempt the rewind if we truly are pipelining */
614 infof(conn->data, "Rewinding %zu bytes\n",dataleft);
615 read_rewind(conn, dataleft);
619 /* If it returned OK, we just keep going */
621 #endif /* CURL_DISABLE_HTTP */
623 /* Account for body content stored in the header buffer */
624 if(k->badheader && !k->ignorebody) {
625 DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
627 k->bytecount += k->hbuflen;
630 if((-1 != k->maxdownload) &&
631 (k->bytecount + nread >= k->maxdownload)) {
633 excess = (size_t)(k->bytecount + nread - k->maxdownload);
634 if(excess > 0 && !k->ignorebody) {
635 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
636 /* The 'excess' amount below can't be more than BUFSIZE which
637 always will fit in a size_t */
639 "Rewinding stream by : %zu"
640 " bytes on url %s (size = %" FORMAT_OFF_T
641 ", maxdownload = %" FORMAT_OFF_T
642 ", bytecount = %" FORMAT_OFF_T ", nread = %zd)\n",
643 excess, data->state.path,
644 k->size, k->maxdownload, k->bytecount, nread);
645 read_rewind(conn, excess);
649 "Excess found in a non pipelined read:"
651 ", size = %" FORMAT_OFF_T
652 ", maxdownload = %" FORMAT_OFF_T
653 ", bytecount = %" FORMAT_OFF_T "\n",
654 excess, k->size, k->maxdownload, k->bytecount);
658 nread = (ssize_t) (k->maxdownload - k->bytecount);
659 if(nread < 0 ) /* this should be unusual */
662 k->keepon &= ~KEEP_RECV; /* we're done reading */
665 k->bytecount += nread;
667 Curl_pgrsSetDownloadCounter(data, k->bytecount);
669 if(!k->chunk && (nread || k->badheader || is_empty_data)) {
670 /* If this is chunky transfer, it was already written */
672 if(k->badheader && !k->ignorebody) {
673 /* we parsed a piece of data wrongly assuming it was a header
674 and now we output it as body instead */
676 /* Don't let excess data pollute body writes */
677 if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
678 result = Curl_client_write(conn, CLIENTWRITE_BODY,
679 data->state.headerbuff,
682 result = Curl_client_write(conn, CLIENTWRITE_BODY,
683 data->state.headerbuff,
684 (size_t)k->maxdownload);
689 if(k->badheader < HEADER_ALLBAD) {
690 /* This switch handles various content encodings. If there's an
691 error here, be sure to check over the almost identical code
693 Make sure that ALL_CONTENT_ENCODINGS contains all the
694 encodings handled here. */
696 switch (conn->data->set.http_ce_skip ?
697 IDENTITY : k->auto_decoding) {
700 /* This is the default when the server sends no
701 Content-Encoding header. See Curl_readwrite_init; the
702 memset() call initializes k->auto_decoding to zero. */
705 #ifndef CURL_DISABLE_POP3
706 if(conn->handler->protocol&CURLPROTO_POP3)
707 result = Curl_pop3_write(conn, k->str, nread);
709 #endif /* CURL_DISABLE_POP3 */
711 result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
718 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
720 result = Curl_unencode_deflate_write(conn, k, nread);
724 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
726 result = Curl_unencode_gzip_write(conn, k, nread);
731 failf (data, "Unrecognized content encoding type. "
732 "libcurl understands `identity', `deflate' and `gzip' "
733 "content encodings.");
734 result = CURLE_BAD_CONTENT_ENCODING;
739 k->badheader = HEADER_NORMAL; /* taken care of now */
745 } /* if(! header and data to read ) */
747 if(conn->handler->readwrite &&
748 (excess > 0 && !conn->bits.stream_was_rewound)) {
749 /* Parse the excess data */
751 nread = (ssize_t)excess;
753 result = conn->handler->readwrite(data, conn, &nread, &readmore);
758 k->keepon |= KEEP_RECV; /* we're not done reading */
763 /* if we received nothing, the server closed the connection and we
765 k->keepon &= ~KEEP_RECV;
768 } while(data_pending(conn));
770 if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
772 /* When we've read the entire thing and the close bit is set, the server
773 may now close the connection. If there's now any kind of sending going
774 on from our side, we need to stop that immediately. */
775 infof(data, "we are done reading and this is set to close, stop send\n");
776 k->keepon &= ~KEEP_SEND; /* no writing anymore either */
783 * Send data to upload to the server, when the socket is writable.
785 static CURLcode readwrite_upload(struct SessionHandle *data,
786 struct connectdata *conn,
787 struct SingleRequest *k,
791 ssize_t bytes_written;
793 ssize_t nread; /* number of bytes read */
794 bool sending_http_headers = FALSE;
796 if((k->bytecount == 0) && (k->writebytecount == 0))
797 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
799 *didwhat |= KEEP_SEND;
802 * We loop here to do the READ and SEND loop until we run out of
803 * data to send or until we get EWOULDBLOCK back
805 * FIXME: above comment is misleading. Currently no looping is
806 * actually done in do-while loop below.
810 /* only read more data if there's no upload data already
811 present in the upload buffer */
812 if(0 == data->req.upload_present) {
813 /* init the "upload from here" pointer */
814 data->req.upload_fromhere = k->uploadbuf;
816 if(!k->upload_done) {
817 /* HTTP pollution, this should be written nicer to become more
818 protocol agnostic. */
821 if((k->exp100 == EXP100_SENDING_REQUEST) &&
822 (data->state.proto.http->sending == HTTPSEND_BODY)) {
823 /* If this call is to send body data, we must take some action:
824 We have sent off the full HTTP 1.1 request, and we shall now
825 go into the Expect: 100 state and await such a header */
826 k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
827 k->keepon &= ~KEEP_SEND; /* disable writing */
828 k->start100 = Curl_tvnow(); /* timeout count starts now */
829 *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
831 /* set a timeout for the multi interface */
832 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
836 if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
837 if(data->state.proto.http->sending == HTTPSEND_REQUEST)
838 /* We're sending the HTTP request headers, not the data.
839 Remember that so we don't change the line endings. */
840 sending_http_headers = TRUE;
842 sending_http_headers = FALSE;
845 result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
849 nread = (ssize_t)fillcount;
852 nread = 0; /* we're done uploading/reading */
854 if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
855 /* this is a paused transfer */
860 k->keepon &= ~KEEP_SEND; /* we're done writing */
862 if(conn->bits.rewindaftersend) {
863 result = Curl_readrewind(conn);
870 /* store number of bytes available for upload */
871 data->req.upload_present = nread;
873 #ifndef CURL_DISABLE_SMTP
874 if(conn->handler->protocol & CURLPROTO_SMTP) {
875 result = Curl_smtp_escape_eob(conn, nread);
880 #endif /* CURL_DISABLE_SMTP */
882 /* convert LF to CRLF if so asked */
883 if((!sending_http_headers) && (
884 #ifdef CURL_DO_LINEEND_CONV
885 /* always convert if we're FTPing in ASCII mode */
886 (data->set.prefer_ascii) ||
889 if(data->state.scratch == NULL)
890 data->state.scratch = malloc(2*BUFSIZE);
891 if(data->state.scratch == NULL) {
892 failf (data, "Failed to alloc scratch buffer!");
893 return CURLE_OUT_OF_MEMORY;
896 * ASCII/EBCDIC Note: This is presumably a text (not binary)
897 * transfer so the data should already be in ASCII.
898 * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
899 * must be used instead of the escape sequences \r & \n.
901 for(i = 0, si = 0; i < nread; i++, si++) {
902 if(data->req.upload_fromhere[i] == 0x0a) {
903 data->state.scratch[si++] = 0x0d;
904 data->state.scratch[si] = 0x0a;
905 if(!data->set.crlf) {
906 /* we're here only because FTP is in ASCII mode...
907 bump infilesize for the LF we just added */
908 data->set.infilesize++;
912 data->state.scratch[si] = data->req.upload_fromhere[i];
915 /* only perform the special operation if we really did replace
919 /* upload from the new (replaced) buffer instead */
920 data->req.upload_fromhere = data->state.scratch;
922 /* set the new amount too */
923 data->req.upload_present = nread;
926 } /* if 0 == data->req.upload_present */
928 /* We have a partial buffer left from a previous "round". Use
929 that instead of reading more data */
932 /* write to socket (send away data) */
933 result = Curl_write(conn,
934 conn->writesockfd, /* socket to send to */
935 data->req.upload_fromhere, /* buffer pointer */
936 data->req.upload_present, /* buffer size */
937 &bytes_written); /* actually sent */
942 if(data->set.verbose)
943 /* show the data before we change the pointer upload_fromhere */
944 Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
945 (size_t)bytes_written, conn);
947 k->writebytecount += bytes_written;
949 if(k->writebytecount == data->set.infilesize) {
950 /* we have sent all data we were supposed to */
951 k->upload_done = TRUE;
952 infof(data, "We are completely uploaded and fine\n");
955 if(data->req.upload_present != bytes_written) {
956 /* we only wrote a part of the buffer (if anything), deal with it! */
958 /* store the amount of bytes left in the buffer to write */
959 data->req.upload_present -= bytes_written;
961 /* advance the pointer where to find the buffer when the next send
963 data->req.upload_fromhere += bytes_written;
966 /* we've uploaded that buffer now */
967 data->req.upload_fromhere = k->uploadbuf;
968 data->req.upload_present = 0; /* no more bytes left */
971 /* switch off writing, we're done! */
972 k->keepon &= ~KEEP_SEND; /* we're done writing */
976 Curl_pgrsSetUploadCounter(data, k->writebytecount);
978 } WHILE_FALSE; /* just to break out from! */
984 * Curl_readwrite() is the low-level function to be called when data is to
985 * be read and written to/from the connection.
987 CURLcode Curl_readwrite(struct connectdata *conn,
990 struct SessionHandle *data = conn->data;
991 struct SingleRequest *k = &data->req;
995 curl_socket_t fd_read;
996 curl_socket_t fd_write;
997 int select_res = conn->cselect_bits;
999 conn->cselect_bits = 0;
1001 /* only use the proper socket if the *_HOLD bit is not set simultaneously as
1002 then we are in rate limiting state in that transfer direction */
1004 if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
1005 fd_read = conn->sockfd;
1007 fd_read = CURL_SOCKET_BAD;
1009 if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
1010 fd_write = conn->writesockfd;
1012 fd_write = CURL_SOCKET_BAD;
1014 if(!select_res) /* Call for select()/poll() only, if read/write/error
1015 status is not known. */
1016 select_res = Curl_socket_ready(fd_read, fd_write, 0);
1018 if(select_res == CURL_CSELECT_ERR) {
1019 failf(data, "select/poll returned error");
1020 return CURLE_SEND_ERROR;
1023 /* We go ahead and do a read if we have a readable socket or if
1024 the stream was rewound (in which case we have data in a
1026 if((k->keepon & KEEP_RECV) &&
1027 ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
1029 result = readwrite_data(data, conn, k, &didwhat, done);
1033 else if(k->keepon & KEEP_RECV) {
1034 DEBUGF(infof(data, "additional stuff not fine %s:%d: %d %d\n",
1036 select_res & CURL_CSELECT_IN,
1037 conn->bits.stream_was_rewound));
1040 /* If we still have writing to do, we check if we have a writable socket. */
1041 if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
1044 result = readwrite_upload(data, conn, k, &didwhat);
1049 k->now = Curl_tvnow();
1051 /* Update read/write counters */
1053 *k->bytecountp = k->bytecount; /* read count */
1054 if(k->writebytecountp)
1055 *k->writebytecountp = k->writebytecount; /* write count */
1058 /* no read no write, this is a timeout? */
1059 if(k->exp100 == EXP100_AWAITING_CONTINUE) {
1060 /* This should allow some time for the header to arrive, but only a
1061 very short time as otherwise it'll be too much wasted time too
1064 /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
1066 Therefore, when a client sends this header field to an origin server
1067 (possibly via a proxy) from which it has never seen a 100 (Continue)
1068 status, the client SHOULD NOT wait for an indefinite period before
1069 sending the request body.
1073 long ms = Curl_tvdiff(k->now, k->start100);
1074 if(ms > CURL_TIMEOUT_EXPECT_100) {
1075 /* we've waited long enough, continue anyway */
1076 k->exp100 = EXP100_SEND_DATA;
1077 k->keepon |= KEEP_SEND;
1078 infof(data, "Done waiting for 100-continue\n");
1083 if(Curl_pgrsUpdate(conn))
1084 result = CURLE_ABORTED_BY_CALLBACK;
1086 result = Curl_speedcheck(data, k->now);
1091 if(0 > Curl_timeleft(data, &k->now, FALSE)) {
1093 failf(data, "Operation timed out after %ld milliseconds with %"
1094 FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes received",
1095 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount,
1099 failf(data, "Operation timed out after %ld milliseconds with %"
1100 FORMAT_OFF_T " bytes received",
1101 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount);
1103 return CURLE_OPERATION_TIMEDOUT;
1108 * The transfer has been performed. Just make some general checks before
1112 if(!(data->set.opt_no_body) && (k->size != -1) &&
1113 (k->bytecount != k->size) &&
1114 #ifdef CURL_DO_LINEEND_CONV
1115 /* Most FTP servers don't adjust their file SIZE response for CRLFs,
1116 so we'll check to see if the discrepancy can be explained
1117 by the number of CRLFs we've changed to LFs.
1119 (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1120 #endif /* CURL_DO_LINEEND_CONV */
1121 !data->req.newurl) {
1122 failf(data, "transfer closed with %" FORMAT_OFF_T
1123 " bytes remaining to read",
1124 k->size - k->bytecount);
1125 return CURLE_PARTIAL_FILE;
1127 else if(!(data->set.opt_no_body) &&
1129 (conn->chunk.state != CHUNK_STOP)) {
1131 * In chunked mode, return an error if the connection is closed prior to
1132 * the empty (terminating) chunk is read.
1134 * The condition above used to check for
1135 * conn->proto.http->chunk.datasize != 0 which is true after reading
1136 * *any* chunk, not just the empty chunk.
1139 failf(data, "transfer closed with outstanding read data remaining");
1140 return CURLE_PARTIAL_FILE;
1142 if(Curl_pgrsUpdate(conn))
1143 return CURLE_ABORTED_BY_CALLBACK;
1146 /* Now update the "done" boolean we return */
1147 *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
1148 KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
1154 * Curl_single_getsock() gets called by the multi interface code when the app
1155 * has requested to get the sockets for the current connection. This function
1156 * will then be called once for every connection that the multi interface
1157 * keeps track of. This function will only be called for connections that are
1158 * in the proper state to have this information available.
1160 int Curl_single_getsock(const struct connectdata *conn,
1161 curl_socket_t *sock, /* points to numsocks number
1165 const struct SessionHandle *data = conn->data;
1166 int bitmap = GETSOCK_BLANK;
1167 unsigned sockindex = 0;
1169 if(conn->handler->perform_getsock)
1170 return conn->handler->perform_getsock(conn, sock, numsocks);
1173 /* simple check but we might need two slots */
1174 return GETSOCK_BLANK;
1176 /* don't include HOLD and PAUSE connections */
1177 if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
1179 DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1181 bitmap |= GETSOCK_READSOCK(sockindex);
1182 sock[sockindex] = conn->sockfd;
1185 /* don't include HOLD and PAUSE connections */
1186 if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
1188 if((conn->sockfd != conn->writesockfd) ||
1189 !(data->req.keepon & KEEP_RECV)) {
1190 /* only if they are not the same socket or we didn't have a readable
1191 one, we increase index */
1192 if(data->req.keepon & KEEP_RECV)
1193 sockindex++; /* increase index if we need two entries */
1195 DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1197 sock[sockindex] = conn->writesockfd;
1200 bitmap |= GETSOCK_WRITESOCK(sockindex);
1207 * Determine optimum sleep time based on configured rate, current rate,
1209 * Returns value in milliseconds.
1211 * The basic idea is to adjust the desired rate up/down in this method
1212 * based on whether we are running too slow or too fast. Then, calculate
1213 * how many milliseconds to wait for the next packet to achieve this new
1216 long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
1219 curl_off_t min_sleep = 0;
1225 /* If running faster than about .1% of the desired speed, slow
1226 * us down a bit. Use shift instead of division as the 0.1%
1227 * cutoff is arbitrary anyway.
1229 if(cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
1230 /* running too fast, decrease target rate by 1/64th of rate */
1231 rate_bps -= rate_bps >> 6;
1234 else if(cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
1235 /* running too slow, increase target rate by 1/64th of rate */
1236 rate_bps += rate_bps >> 6;
1239 /* Determine number of milliseconds to wait until we do
1240 * the next packet at the adjusted rate. We should wait
1241 * longer when using larger packets, for instance.
1243 rv = ((curl_off_t)((pkt_size * 8) * 1000) / rate_bps);
1245 /* Catch rounding errors and always slow down at least 1ms if
1246 * we are running too fast.
1251 /* Bound value to fit in 'long' on 32-bit platform. That's
1252 * plenty long enough anyway!
1264 * This function is what performs the actual transfer. It is capable of doing
1265 * both ways simultaneously. The transfer must already have been setup by a
1266 * call to Curl_setup_transfer().
1268 * Note that headers are created in a preallocated buffer of a default size.
1269 * That buffer can be enlarged on demand, but it is never shrunken again.
1274 Transfer(struct connectdata *conn)
1277 struct SessionHandle *data = conn->data;
1278 struct SingleRequest *k = &data->req;
1285 if((conn->sockfd == CURL_SOCKET_BAD) &&
1286 (conn->writesockfd == CURL_SOCKET_BAD))
1287 /* nothing to read, nothing to write, we're already OK! */
1290 /* we want header and/or body, if neither then don't do this! */
1291 if(!k->getheader && data->set.opt_no_body)
1295 curl_socket_t fd_read = conn->sockfd;
1296 curl_socket_t fd_write = conn->writesockfd;
1297 int keepon = k->keepon;
1301 /* if waitfor is set, get the RECV and SEND bits from that but keep the
1303 keepon &= ~ (KEEP_RECV|KEEP_SEND);
1304 keepon |= conn->waitfor & (KEEP_RECV|KEEP_SEND);
1307 /* limit-rate logic: if speed exceeds threshold, then do not include fd in
1308 select set. The current speed is recalculated in each Curl_readwrite()
1310 if((keepon & KEEP_SEND) &&
1311 (!data->set.max_send_speed ||
1312 (data->progress.ulspeed < data->set.max_send_speed) )) {
1313 k->keepon &= ~KEEP_SEND_HOLD;
1316 if(data->set.upload && data->set.max_send_speed &&
1317 (data->progress.ulspeed > data->set.max_send_speed) ) {
1318 /* calculate upload rate-limitation timeout. */
1319 buffersize = (int)(data->set.buffer_size ?
1320 data->set.buffer_size : BUFSIZE);
1321 totmp = Curl_sleep_time(data->set.max_send_speed,
1322 data->progress.ulspeed, buffersize);
1323 if(totmp < timeout_ms)
1326 fd_write = CURL_SOCKET_BAD;
1327 if(keepon & KEEP_SEND)
1328 k->keepon |= KEEP_SEND_HOLD; /* hold it */
1331 if((keepon & KEEP_RECV) &&
1332 (!data->set.max_recv_speed ||
1333 (data->progress.dlspeed < data->set.max_recv_speed)) ) {
1334 k->keepon &= ~KEEP_RECV_HOLD;
1337 if((!data->set.upload) && data->set.max_recv_speed &&
1338 (data->progress.dlspeed > data->set.max_recv_speed)) {
1339 /* Calculate download rate-limitation timeout. */
1340 buffersize = (int)(data->set.buffer_size ?
1341 data->set.buffer_size : BUFSIZE);
1342 totmp = Curl_sleep_time(data->set.max_recv_speed,
1343 data->progress.dlspeed, buffersize);
1344 if(totmp < timeout_ms)
1347 fd_read = CURL_SOCKET_BAD;
1348 if(keepon & KEEP_RECV)
1349 k->keepon |= KEEP_RECV_HOLD; /* hold it */
1352 /* pause logic. Don't check descriptors for paused connections */
1353 if(k->keepon & KEEP_RECV_PAUSE)
1354 fd_read = CURL_SOCKET_BAD;
1355 if(k->keepon & KEEP_SEND_PAUSE)
1356 fd_write = CURL_SOCKET_BAD;
1358 /* The *_HOLD and *_PAUSE logic is necessary since even though there might
1359 be no traffic during the select interval, we still call
1360 Curl_readwrite() for the timeout case and if we limit transfer speed we
1361 must make sure that this function doesn't transfer anything while in
1364 The no timeout for the first round is for the protocols for which data
1365 has already been slurped off the socket and thus waiting for action
1366 won't work since it'll wait even though there is already data present
1369 ((fd_read != CURL_SOCKET_BAD) || (fd_write != CURL_SOCKET_BAD)))
1370 /* if this is the first lap and one of the file descriptors is fine
1371 to work with, skip the timeout */
1374 totmp = Curl_timeleft(data, &k->now, FALSE);
1376 return CURLE_OPERATION_TIMEDOUT;
1380 if(totmp < timeout_ms)
1384 switch (Curl_socket_ready(fd_read, fd_write, timeout_ms)) {
1385 case -1: /* select() error, stop reading */
1387 /* The EINTR is not serious, and it seems you might get this more
1388 often when using the lib in a multi-threaded environment! */
1389 if(SOCKERRNO == EINTR)
1392 return CURLE_RECV_ERROR; /* indicate a network problem */
1393 case 0: /* timeout */
1394 default: /* readable descriptors */
1396 result = Curl_readwrite(conn, &done);
1397 /* "done" signals to us if the transfer(s) are ready */
1403 first = FALSE; /* not the first lap anymore */
1411 * Curl_pretransfer() is called immediately before a transfer starts.
1413 CURLcode Curl_pretransfer(struct SessionHandle *data)
1416 if(!data->change.url) {
1417 /* we can't do anything without URL */
1418 failf(data, "No URL set!");
1419 return CURLE_URL_MALFORMAT;
1422 /* Init the SSL session ID cache here. We do it here since we want to do it
1423 after the *_setopt() calls (that could specify the size of the cache) but
1424 before any transfer takes place. */
1425 res = Curl_ssl_initsessions(data, data->set.ssl.max_ssl_sessions);
1429 data->set.followlocation=0; /* reset the location-follow counter */
1430 data->state.this_is_a_follow = FALSE; /* reset this */
1431 data->state.errorbuf = FALSE; /* no error has occurred */
1432 data->state.httpversion = 0; /* don't assume any particular server version */
1434 data->state.ssl_connect_retry = FALSE;
1436 data->state.authproblem = FALSE;
1437 data->state.authhost.want = data->set.httpauth;
1438 data->state.authproxy.want = data->set.proxyauth;
1439 Curl_safefree(data->info.wouldredirect);
1440 data->info.wouldredirect = NULL;
1442 /* If there is a list of cookie files to read, do it now! */
1443 if(data->change.cookielist)
1444 Curl_cookie_loadfiles(data);
1446 /* If there is a list of host pairs to deal with */
1447 if(data->change.resolve)
1448 res = Curl_loadhostpairs(data);
1451 /* Allow data->set.use_port to set which port to use. This needs to be
1452 * disabled for example when we follow Location: headers to URLs using
1453 * different ports! */
1454 data->state.allow_port = TRUE;
1456 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1457 /*************************************************************
1458 * Tell signal handler to ignore SIGPIPE
1459 *************************************************************/
1460 if(!data->set.no_signal)
1461 data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
1464 Curl_initinfo(data); /* reset session-specific information "variables" */
1465 Curl_pgrsStartNow(data);
1467 if(data->set.timeout)
1468 Curl_expire(data, data->set.timeout);
1470 if(data->set.connecttimeout)
1471 Curl_expire(data, data->set.connecttimeout);
1478 * Curl_posttransfer() is called immediately after a transfer ends
1480 CURLcode Curl_posttransfer(struct SessionHandle *data)
1482 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1483 /* restore the signal handler for SIGPIPE before we get back */
1484 if(!data->set.no_signal)
1485 signal(SIGPIPE, data->state.prev_signal);
1487 (void)data; /* unused parameter */
1493 #ifndef CURL_DISABLE_HTTP
1495 * strlen_url() returns the length of the given URL if the spaces within the
1496 * URL were properly URL encoded.
1498 static size_t strlen_url(const char *url)
1502 bool left=TRUE; /* left side of the ? */
1504 for(ptr=url; *ptr; ptr++) {
1523 /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
1524 * the source URL accordingly.
1526 static void strcpy_url(char *output, const char *url)
1528 /* we must add this with whitespace-replacing */
1531 char *optr = output;
1532 for(iptr = url; /* read from here */
1533 *iptr; /* until zero byte */
1544 *optr++='%'; /* add a '%' */
1545 *optr++='2'; /* add a '2' */
1546 *optr++='0'; /* add a '0' */
1549 *optr++='+'; /* add a '+' here */
1553 *optr=0; /* zero terminate output buffer */
1558 * Returns true if the given URL is absolute (as opposed to relative)
1560 static bool is_absolute_url(const char *url)
1562 char prot[16]; /* URL protocol string storage */
1563 char letter; /* used for a silly sscanf */
1565 return (2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter)) ? TRUE : FALSE;
1569 * Concatenate a relative URL to a base URL making it absolute.
1570 * URL-encodes any spaces.
1571 * The returned pointer must be freed by the caller unless NULL
1572 * (returns NULL on out of memory).
1574 static char *concat_url(const char *base, const char *relurl)
1577 TRY to append this new path to the old URL
1578 to the right of the host part. Oh crap, this is doomed to cause
1579 problems in the future...
1586 const char *useurl = relurl;
1589 /* we must make our own copy of the URL to play with, as it may
1590 point to read-only data */
1591 char *url_clone=strdup(base);
1594 return NULL; /* skip out of this NOW */
1596 /* protsep points to the start of the host name */
1597 protsep=strstr(url_clone, "//");
1601 protsep+=2; /* pass the slashes */
1603 if('/' != relurl[0]) {
1606 /* First we need to find out if there's a ?-letter in the URL,
1607 and cut it and the right-side of that off */
1608 pathsep = strchr(protsep, '?');
1612 /* we have a relative path to append to the last slash if there's one
1613 available, or if the new URL is just a query string (starts with a
1614 '?') we append the new one at the end of the entire currently worked
1616 if(useurl[0] != '?') {
1617 pathsep = strrchr(protsep, '/');
1622 /* Check if there's any slash after the host name, and if so, remember
1623 that position instead */
1624 pathsep = strchr(protsep, '/');
1626 protsep = pathsep+1;
1630 /* now deal with one "./" or any amount of "../" in the newurl
1631 and act accordingly */
1633 if((useurl[0] == '.') && (useurl[1] == '/'))
1634 useurl+=2; /* just skip the "./" */
1636 while((useurl[0] == '.') &&
1637 (useurl[1] == '.') &&
1638 (useurl[2] == '/')) {
1640 useurl+=3; /* pass the "../" */
1645 /* cut off one more level from the right of the original URL */
1646 pathsep = strrchr(protsep, '/');
1657 /* We got a new absolute path for this server */
1659 if((relurl[0] == '/') && (relurl[1] == '/')) {
1660 /* the new URL starts with //, just keep the protocol part from the
1663 useurl = &relurl[2]; /* we keep the slashes from the original, so we
1664 skip the new ones */
1667 /* cut off the original URL from the first slash, or deal with URLs
1669 pathsep = strchr(protsep, '/');
1671 /* When people use badly formatted URLs, such as
1672 "http://www.url.com?dir=/home/daniel" we must not use the first
1673 slash, if there's a ?-letter before it! */
1674 char *sep = strchr(protsep, '?');
1675 if(sep && (sep < pathsep))
1680 /* There was no slash. Now, since we might be operating on a badly
1681 formatted URL, such as "http://www.url.com?id=2380" which doesn't
1682 use a slash separator as it is supposed to, we need to check for a
1683 ?-letter as well! */
1684 pathsep = strchr(protsep, '?');
1691 /* If the new part contains a space, this is a mighty stupid redirect
1692 but we still make an effort to do "right". To the left of a '?'
1693 letter we replace each space with %20 while it is replaced with '+'
1694 on the right side of the '?' letter.
1696 newlen = strlen_url(useurl);
1698 urllen = strlen(url_clone);
1700 newest = malloc(urllen + 1 + /* possible slash */
1701 newlen + 1 /* zero byte */);
1704 free(url_clone); /* don't leak this */
1708 /* copy over the root url part */
1709 memcpy(newest, url_clone, urllen);
1711 /* check if we need to append a slash */
1712 if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
1715 newest[urllen++]='/';
1717 /* then append the new piece on the right side */
1718 strcpy_url(&newest[urllen], useurl);
1724 #endif /* CURL_DISABLE_HTTP */
1727 * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
1728 * as given by the remote server and set up the new URL to request.
1730 CURLcode Curl_follow(struct SessionHandle *data,
1731 char *newurl, /* this 'newurl' is the Location: string,
1732 and it must be malloc()ed before passed
1734 followtype type) /* see transfer.h */
1736 #ifdef CURL_DISABLE_HTTP
1740 /* Location: following will not happen when HTTP is disabled */
1741 return CURLE_TOO_MANY_REDIRECTS;
1744 /* Location: redirect */
1745 bool disallowport = FALSE;
1747 if(type == FOLLOW_REDIR) {
1748 if((data->set.maxredirs != -1) &&
1749 (data->set.followlocation >= data->set.maxredirs)) {
1750 failf(data,"Maximum (%ld) redirects followed", data->set.maxredirs);
1751 return CURLE_TOO_MANY_REDIRECTS;
1754 /* mark the next request as a followed location: */
1755 data->state.this_is_a_follow = TRUE;
1757 data->set.followlocation++; /* count location-followers */
1759 if(data->set.http_auto_referer) {
1760 /* We are asked to automatically set the previous URL as the referer
1761 when we get the next URL. We pick the ->url field, which may or may
1762 not be 100% correct */
1764 if(data->change.referer_alloc) {
1765 Curl_safefree(data->change.referer);
1766 data->change.referer_alloc = FALSE;
1769 data->change.referer = strdup(data->change.url);
1770 if(!data->change.referer)
1771 return CURLE_OUT_OF_MEMORY;
1772 data->change.referer_alloc = TRUE; /* yes, free this later */
1776 if(!is_absolute_url(newurl)) {
1778 *DANG* this is an RFC 2068 violation. The URL is supposed
1779 to be absolute and this doesn't seem to be that!
1781 char *absolute = concat_url(data->change.url, newurl);
1783 return CURLE_OUT_OF_MEMORY;
1788 /* This is an absolute URL, don't allow the custom port number */
1789 disallowport = TRUE;
1791 if(strchr(newurl, ' ')) {
1792 /* This new URL contains at least one space, this is a mighty stupid
1793 redirect but we still make an effort to do "right". */
1795 size_t newlen = strlen_url(newurl);
1797 newest = malloc(newlen+1); /* get memory for this */
1799 return CURLE_OUT_OF_MEMORY;
1800 strcpy_url(newest, newurl); /* create a space-free URL */
1802 free(newurl); /* that was no good */
1803 newurl = newest; /* use this instead now */
1808 if(type == FOLLOW_FAKE) {
1809 /* we're only figuring out the new url if we would've followed locations
1810 but now we're done so we can get out! */
1811 data->info.wouldredirect = newurl;
1816 data->state.allow_port = FALSE;
1818 if(data->change.url_alloc) {
1819 Curl_safefree(data->change.url);
1820 data->change.url_alloc = FALSE;
1823 data->change.url = newurl;
1824 data->change.url_alloc = TRUE;
1825 newurl = NULL; /* don't free! */
1827 infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
1830 * We get here when the HTTP code is 300-399 (and 401). We need to perform
1831 * differently based on exactly what return code there was.
1833 * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
1834 * a HTTP (proxy-) authentication scheme other than Basic.
1836 switch(data->info.httpcode) {
1837 /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
1838 Authorization: XXXX header in the HTTP request code snippet */
1839 /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
1840 Proxy-Authorization: XXXX header in the HTTP request code snippet */
1841 /* 300 - Multiple Choices */
1842 /* 306 - Not used */
1843 /* 307 - Temporary Redirect */
1844 default: /* for all above (and the unknown ones) */
1845 /* Some codes are explicitly mentioned since I've checked RFC2616 and they
1846 * seem to be OK to POST to.
1849 case 301: /* Moved Permanently */
1850 /* (quote from RFC2616, section 10.3.2):
1852 * When automatically redirecting a POST request after receiving a 301
1853 * status code, some existing HTTP/1.0 user agents will erroneously change
1854 * it into a GET request.
1858 * As most of the important user agents do this obvious RFC2616 violation,
1859 * many webservers expect this. So these servers often answers to a POST
1860 * request with an error page. To be sure that libcurl gets the page that
1861 * most user agents would get, libcurl has to force GET.
1863 * This behavior can be overridden with CURLOPT_POSTREDIR.
1865 if((data->set.httpreq == HTTPREQ_POST
1866 || data->set.httpreq == HTTPREQ_POST_FORM)
1867 && !(data->set.keep_post & CURL_REDIR_POST_301)) {
1869 "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
1870 data->set.httpreq = HTTPREQ_GET;
1873 case 302: /* Found */
1876 Note: RFC 1945 and RFC 2068 specify that the client is not allowed
1877 to change the method on the redirected request. However, most
1878 existing user agent implementations treat 302 as if it were a 303
1879 response, performing a GET on the Location field-value regardless
1880 of the original request method. The status codes 303 and 307 have
1881 been added for servers that wish to make unambiguously clear which
1882 kind of reaction is expected of the client.
1886 Note: Many pre-HTTP/1.1 user agents do not understand the 303
1887 status. When interoperability with such clients is a concern, the
1888 302 status code may be used instead, since most user agents react
1889 to a 302 response as described here for 303.
1891 This behavior can be overridden with CURLOPT_POSTREDIR
1893 if((data->set.httpreq == HTTPREQ_POST
1894 || data->set.httpreq == HTTPREQ_POST_FORM)
1895 && !(data->set.keep_post & CURL_REDIR_POST_302)) {
1897 "Violate RFC 2616/10.3.3 and switch from POST to GET\n");
1898 data->set.httpreq = HTTPREQ_GET;
1902 case 303: /* See Other */
1903 /* Disable both types of POSTs, unless the user explicitely
1904 asks for POST after POST */
1905 if(data->set.httpreq != HTTPREQ_GET
1906 && !(data->set.keep_post & CURL_REDIR_POST_303)) {
1907 data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
1908 infof(data, "Disables POST, goes with %s\n",
1909 data->set.opt_no_body?"HEAD":"GET");
1912 case 304: /* Not Modified */
1913 /* 304 means we did a conditional request and it was "Not modified".
1914 * We shouldn't get any Location: header in this response!
1917 case 305: /* Use Proxy */
1918 /* (quote from RFC2616, section 10.3.6):
1919 * "The requested resource MUST be accessed through the proxy given
1920 * by the Location field. The Location field gives the URI of the
1921 * proxy. The recipient is expected to repeat this single request
1922 * via the proxy. 305 responses MUST only be generated by origin
1927 Curl_pgrsTime(data, TIMER_REDIRECT);
1928 Curl_pgrsResetTimesSizes(data);
1931 #endif /* CURL_DISABLE_HTTP */
1935 connect_host(struct SessionHandle *data,
1936 struct connectdata **conn)
1938 CURLcode res = CURLE_OK;
1941 bool protocol_done=TRUE; /* will be TRUE always since this is only used
1942 within the easy interface */
1943 Curl_pgrsTime(data, TIMER_STARTSINGLE);
1944 res = Curl_connect(data, conn, &async, &protocol_done);
1946 if((CURLE_OK == res) && async) {
1947 /* Now, if async is TRUE here, we need to wait for the name
1949 res = Curl_resolver_wait_resolv(*conn, NULL);
1950 if(CURLE_OK == res) {
1951 /* Resolved, continue with the connection */
1952 res = Curl_async_resolved(*conn, &protocol_done);
1957 /* if we can't resolve, we kill this "connection" now */
1958 (void)Curl_disconnect(*conn, /* dead_connection */ FALSE);
1967 Curl_reconnect_request(struct connectdata **connp)
1969 CURLcode result = CURLE_OK;
1970 struct connectdata *conn = *connp;
1971 struct SessionHandle *data = conn->data;
1973 /* This was a re-use of a connection and we got a write error in the
1974 * DO-phase. Then we DISCONNECT this connection and have another attempt to
1975 * CONNECT and then DO again! The retry cannot possibly find another
1976 * connection to re-use, since we only keep one possible connection for
1979 infof(data, "Re-used connection seems dead, get a new one\n");
1981 conn->bits.close = TRUE; /* enforce close of this connection */
1982 result = Curl_done(&conn, result, FALSE); /* we are so done with this */
1984 /* conn may no longer be a good pointer, clear it to avoid mistakes by
1989 * According to bug report #1330310. We need to check for CURLE_SEND_ERROR
1990 * here as well. I figure this could happen when the request failed on a FTP
1991 * connection and thus Curl_done() itself tried to use the connection
1992 * (again). Slight Lack of feedback in the report, but I don't think this
1993 * extra check can do much harm.
1995 if((CURLE_OK == result) || (CURLE_SEND_ERROR == result)) {
1997 bool protocol_done = TRUE;
1999 /* Now, redo the connect and get a new connection */
2000 result = Curl_connect(data, connp, &async, &protocol_done);
2001 if(CURLE_OK == result) {
2002 /* We have connected or sent away a name resolve query fine */
2004 conn = *connp; /* setup conn to again point to something nice */
2006 /* Now, if async is TRUE here, we need to wait for the name
2008 result = Curl_resolver_wait_resolv(conn, NULL);
2012 /* Resolved, continue with the connection */
2013 result = Curl_async_resolved(conn, &protocol_done);
2023 /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
2025 NOTE: that the *url is malloc()ed. */
2026 CURLcode Curl_retry_request(struct connectdata *conn,
2029 struct SessionHandle *data = conn->data;
2033 /* if we're talking upload, we can't do the checks below, unless the protocol
2034 is HTTP as when uploading over HTTP we will still get a response */
2035 if(data->set.upload &&
2036 !(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)))
2039 if(/* workaround for broken TLS servers */ data->state.ssl_connect_retry ||
2040 ((data->req.bytecount +
2041 data->req.headerbytecount == 0) &&
2043 !data->set.opt_no_body &&
2044 data->set.rtspreq != RTSPREQ_RECEIVE)) {
2045 /* We got no data, we attempted to re-use a connection and yet we want a
2046 "body". This might happen if the connection was left alive when we were
2047 done using it before, but that was closed when we wanted to read from
2048 it again. Bad luck. Retry the same request on a fresh connect! */
2049 infof(conn->data, "Connection died, retrying a fresh connect\n");
2050 *url = strdup(conn->data->change.url);
2052 return CURLE_OUT_OF_MEMORY;
2054 conn->bits.close = TRUE; /* close this connection */
2055 conn->bits.retry = TRUE; /* mark this as a connection we're about
2056 to retry. Marking it this way should
2057 prevent i.e HTTP transfers to return
2058 error just because nothing has been
2062 if((conn->handler->protocol&CURLPROTO_HTTP) &&
2063 data->state.proto.http->writebytecount)
2064 return Curl_readrewind(conn);
2069 static CURLcode Curl_do_perform(struct SessionHandle *data)
2073 struct connectdata *conn=NULL;
2074 char *newurl = NULL; /* possibly a new URL to follow to! */
2075 followtype follow = FOLLOW_NONE;
2077 data->state.used_interface = Curl_if_easy;
2079 res = Curl_pretransfer(data);
2084 * It is important that there is NO 'return' from this function at any other
2085 * place than falling down to the end of the function! This is because we
2086 * have cleanup stuff that must be done before we get back, and that is only
2087 * performed after this do-while loop.
2091 res = connect_host(data, &conn); /* primary connection */
2093 if(res == CURLE_OK) {
2095 if(data->set.connect_only) {
2096 /* keep connection open for application to use the socket */
2097 conn->bits.close = FALSE;
2098 res = Curl_done(&conn, CURLE_OK, FALSE);
2101 res = Curl_do(&conn, &do_done);
2103 if(res == CURLE_OK) {
2104 if(conn->data->set.wildcardmatch) {
2105 if(conn->data->wildcard.state == CURLWC_DONE ||
2106 conn->data->wildcard.state == CURLWC_SKIP) {
2107 /* keep connection open for application to use the socket */
2108 conn->bits.close = FALSE;
2109 res = Curl_done(&conn, CURLE_OK, FALSE);
2113 res = Transfer(conn); /* now fetch that URL please */
2114 if((res == CURLE_OK) || (res == CURLE_RECV_ERROR)) {
2116 CURLcode rc = Curl_retry_request(conn, &newurl);
2120 retry = (newurl?TRUE:FALSE);
2123 /* we know (newurl != NULL) at this point */
2125 follow = FOLLOW_RETRY;
2127 else if(res == CURLE_OK) {
2129 * We must duplicate the new URL here as the connection data may
2130 * be free()ed in the Curl_done() function. We prefer the newurl
2131 * one since that's used for redirects or just further requests
2132 * for retries or multi-stage HTTP auth methods etc.
2134 if(data->req.newurl) {
2135 follow = FOLLOW_REDIR;
2136 newurl = strdup(data->req.newurl);
2138 res = CURLE_OUT_OF_MEMORY;
2140 else if(data->req.location) {
2141 follow = FOLLOW_FAKE;
2142 newurl = strdup(data->req.location);
2144 res = CURLE_OUT_OF_MEMORY;
2148 /* in the above cases where 'newurl' gets assigned, we have a fresh
2149 * allocated memory pointed to */
2151 if(res != CURLE_OK) {
2152 /* The transfer phase returned error, we mark the connection to get
2153 * closed to prevent being re-used. This is because we can't
2154 * possibly know if the connection is in a good shape or not now. */
2155 conn->bits.close = TRUE;
2157 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
2158 /* if we failed anywhere, we must clean up the secondary socket if
2160 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2161 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
2165 /* Always run Curl_done(), even if some of the previous calls
2166 failed, but return the previous (original) error code */
2167 res2 = Curl_done(&conn, res, FALSE);
2173 /* Curl_do() failed, clean up left-overs in the done-call, but note
2174 that at some cases the conn pointer is NULL when Curl_do() failed
2175 and the connection cache is very small so only call Curl_done() if
2176 conn is still "alive". */
2177 /* ignore return code since we already have an error to return */
2178 (void)Curl_done(&conn, res, FALSE);
2181 * Important: 'conn' cannot be used here, since it may have been closed
2182 * in 'Curl_done' or other functions.
2185 if((res == CURLE_OK) && follow) {
2186 res = Curl_follow(data, newurl, follow);
2187 if(CURLE_OK == res) {
2188 /* if things went fine, Curl_follow() freed or otherwise took
2189 responsibility for the newurl pointer */
2191 if(follow >= FOLLOW_RETRY) {
2192 follow = FOLLOW_NONE;
2195 /* else we break out of the loop below */
2199 break; /* it only reaches here when this shouldn't loop */
2201 } /* loop if Location: */
2206 if(res && !data->state.errorbuf) {
2208 * As an extra precaution: if no error string has been set and there was
2209 * an error, use the strerror() string or if things are so bad that not
2210 * even that is good, set a bad string that mentions the error code.
2212 const char *str = curl_easy_strerror(res);
2214 failf(data, "unspecified error %d", (int)res);
2216 failf(data, "%s", str);
2219 /* run post-transfer unconditionally, but don't clobber the return code if
2220 we already have an error code recorder */
2221 res2 = Curl_posttransfer(data);
2229 * Curl_perform() is the internal high-level function that gets called by the
2230 * external curl_easy_perform() function. It inits, performs and cleans up a
2231 * single file transfer.
2233 CURLcode Curl_perform(struct SessionHandle *data)
2236 if(!data->set.wildcardmatch)
2237 return Curl_do_perform(data);
2239 /* init main wildcard structures */
2240 res = Curl_wildcard_init(&data->wildcard);
2244 res = Curl_do_perform(data);
2246 Curl_wildcard_dtor(&data->wildcard);
2251 while(!res && data->wildcard.state != CURLWC_DONE)
2252 res = Curl_do_perform(data);
2254 Curl_wildcard_dtor(&data->wildcard);
2256 /* wildcard download finished or failed */
2257 data->wildcard.state = CURLWC_INIT;
2262 * Curl_setup_transfer() is called to setup some basic properties for the
2263 * upcoming transfer.
2266 Curl_setup_transfer(
2267 struct connectdata *conn, /* connection data */
2268 int sockindex, /* socket index to read from or -1 */
2269 curl_off_t size, /* -1 if unknown at this point */
2270 bool getheader, /* TRUE if header parsing is wanted */
2271 curl_off_t *bytecountp, /* return number of bytes read or NULL */
2272 int writesockindex, /* socket index to write to, it may very well be
2273 the same we read from. -1 disables */
2274 curl_off_t *writecountp /* return number of bytes written or NULL */
2277 struct SessionHandle *data;
2278 struct SingleRequest *k;
2280 DEBUGASSERT(conn != NULL);
2285 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
2287 /* now copy all input parameters */
2288 conn->sockfd = sockindex == -1 ?
2289 CURL_SOCKET_BAD : conn->sock[sockindex];
2290 conn->writesockfd = writesockindex == -1 ?
2291 CURL_SOCKET_BAD:conn->sock[writesockindex];
2292 k->getheader = getheader;
2295 k->bytecountp = bytecountp;
2296 k->writebytecountp = writecountp;
2298 /* The code sequence below is placed in this function just because all
2299 necessary input is not always known in do_complete() as this function may
2300 be called after that */
2305 Curl_pgrsSetDownloadSize(data, size);
2307 /* we want header and/or body, if neither then don't do this! */
2308 if(k->getheader || !data->set.opt_no_body) {
2310 if(conn->sockfd != CURL_SOCKET_BAD)
2311 k->keepon |= KEEP_RECV;
2313 if(conn->writesockfd != CURL_SOCKET_BAD) {
2316 Even if we require a 100-return code before uploading data, we might
2317 need to write data before that since the REQUEST may not have been
2318 finished sent off just yet.
2320 Thus, we must check if the request has been sent before we set the
2321 state info where we wait for the 100-return code
2323 if((data->state.expect100header) &&
2324 (data->state.proto.http->sending == HTTPSEND_BODY)) {
2325 /* wait with write until we either got 100-continue or a timeout */
2326 k->exp100 = EXP100_AWAITING_CONTINUE;
2327 k->start100 = Curl_tvnow();
2329 /* set a timeout for the multi interface */
2330 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
2333 if(data->state.expect100header)
2334 /* when we've sent off the rest of the headers, we must await a
2335 100-continue but first finish sending the request */
2336 k->exp100 = EXP100_SENDING_REQUEST;
2338 /* enable the write bit when we're not waiting for continue */
2339 k->keepon |= KEEP_SEND;
2341 } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
2342 } /* if(k->getheader || !data->set.opt_no_body) */