1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, 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 /* -- WIN32 approved -- */
33 #include "strtoofft.h"
41 #ifdef HAVE_SYS_SOCKET_H
42 #include <sys/socket.h>
44 #ifdef HAVE_NETINET_IN_H
45 #include <netinet/in.h>
47 #ifdef HAVE_SYS_TIME_H
56 #ifdef HAVE_ARPA_INET_H
57 #include <arpa/inet.h>
62 #ifdef HAVE_SYS_IOCTL_H
63 #include <sys/ioctl.h>
69 #ifdef HAVE_SYS_PARAM_H
70 #include <sys/param.h>
73 #ifdef HAVE_SYS_SELECT_H
74 #include <sys/select.h>
78 #error "We can't compile without socket() support!"
84 #include <curl/curl.h>
87 #include "content_encoding.h"
91 #include "speedcheck.h"
97 #include "http_digest.h"
98 #include "http_ntlm.h"
99 #include "http_negotiate.h"
101 #include "curl_memory.h"
104 #include "easyif.h" /* for Curl_convert_to_network prototype */
108 #define _MPRINTF_REPLACE /* use our functions only */
109 #include <curl/mprintf.h>
111 /* The last #include file should be: */
112 #include "memdebug.h"
114 #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
117 * This function will call the read callback to fill our buffer with data
120 CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
122 struct SessionHandle *data = conn->data;
123 size_t buffersize = (size_t)bytes;
125 #ifdef CURL_DOES_CONVERSIONS
126 bool sending_http_headers = FALSE;
128 if((conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) &&
129 (data->state.proto.http->sending == HTTPSEND_REQUEST)) {
130 /* We're sending the HTTP request headers, not the data.
131 Remember that so we don't re-translate them into garbage. */
132 sending_http_headers = TRUE;
136 if(data->req.upload_chunky) {
137 /* if chunked Transfer-Encoding */
138 buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
139 data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
142 /* this function returns a size_t, so we typecast to int to prevent warnings
143 with picky compilers */
144 nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
145 buffersize, conn->fread_in);
147 if(nread == CURL_READFUNC_ABORT) {
148 failf(data, "operation aborted by callback");
150 return CURLE_ABORTED_BY_CALLBACK;
152 else if(nread == CURL_READFUNC_PAUSE) {
153 struct SingleRequest *k = &data->req;
154 /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
155 k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
156 if(data->req.upload_chunky) {
157 /* Back out the preallocation done above */
158 data->req.upload_fromhere -= (8 + 2);
161 return CURLE_OK; /* nothing was read */
163 else if((size_t)nread > buffersize) {
164 /* the read function returned a too large value */
166 failf(data, "read function returned funny value");
167 return CURLE_READ_ERROR;
170 if(!data->req.forbidchunk && data->req.upload_chunky) {
171 /* if chunked Transfer-Encoding
177 /* On non-ASCII platforms the <DATA> may or may not be
178 translated based on set.prefer_ascii while the protocol
179 portion must always be translated to the network encoding.
180 To further complicate matters, line end conversion might be
181 done later on, so we need to prevent CRLFs from becoming
182 CRCRLFs if that's the case. To do this we use bare LFs
183 here, knowing they'll become CRLFs later on.
187 const char *endofline_native;
188 const char *endofline_network;
190 #ifdef CURL_DO_LINEEND_CONV
191 if((data->set.crlf) || (data->set.prefer_ascii)) {
194 #endif /* CURL_DO_LINEEND_CONV */
195 /* \n will become \r\n later on */
196 endofline_native = "\n";
197 endofline_network = "\x0a";
200 endofline_native = "\r\n";
201 endofline_network = "\x0d\x0a";
203 hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
204 "%x%s", nread, endofline_native);
206 /* move buffer pointer */
207 data->req.upload_fromhere -= hexlen;
210 /* copy the prefix to the buffer, leaving out the NUL */
211 memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
213 /* always append ASCII CRLF to the data */
214 memcpy(data->req.upload_fromhere + nread,
216 strlen(endofline_network));
218 #ifdef CURL_DOES_CONVERSIONS
221 if(data->set.prefer_ascii) {
222 /* translate the protocol and data */
226 /* just translate the protocol portion */
227 length = strlen(hexbuffer);
229 res = Curl_convert_to_network(data, data->req.upload_fromhere, length);
230 /* Curl_convert_to_network calls failf if unsuccessful */
233 #endif /* CURL_DOES_CONVERSIONS */
235 if((nread - hexlen) == 0)
236 /* mark this as done once this chunk is transfered */
237 data->req.upload_done = TRUE;
239 nread+=(int)strlen(endofline_native); /* for the added end of line */
241 #ifdef CURL_DOES_CONVERSIONS
242 else if((data->set.prefer_ascii) && (!sending_http_headers)) {
244 res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
245 /* Curl_convert_to_network calls failf if unsuccessful */
249 #endif /* CURL_DOES_CONVERSIONS */
258 * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
259 * POST/PUT with multi-pass authentication when a sending was denied and a
260 * resend is necessary.
262 CURLcode Curl_readrewind(struct connectdata *conn)
264 struct SessionHandle *data = conn->data;
266 conn->bits.rewindaftersend = FALSE; /* we rewind now */
268 /* explicitly switch off sending data on this connection now since we are
269 about to restart a new transfer and thus we want to avoid inadvertently
270 sending more data on the existing connection until the next transfer
272 data->req.keepon &= ~KEEP_SEND;
274 /* We have sent away data. If not using CURLOPT_POSTFIELDS or
275 CURLOPT_HTTPPOST, call app to rewind
277 if(data->set.postfields ||
278 (data->set.httpreq == HTTPREQ_POST_FORM))
281 if(data->set.seek_func) {
284 err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
286 failf(data, "seek callback returned error %d", (int)err);
287 return CURLE_SEND_FAIL_REWIND;
290 else if(data->set.ioctl_func) {
293 err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
294 data->set.ioctl_client);
295 infof(data, "the ioctl callback returned %d\n", (int)err);
298 /* FIXME: convert to a human readable error message */
299 failf(data, "ioctl callback returned error %d", (int)err);
300 return CURLE_SEND_FAIL_REWIND;
304 /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
305 given FILE * stream and we can actually attempt to rewind that
306 ourself with fseek() */
307 if(data->set.fread_func == (curl_read_callback)fread) {
308 if(-1 != fseek(data->set.in, 0, SEEK_SET))
309 /* successful rewind */
313 /* no callback set or failure above, makes us fail at once */
314 failf(data, "necessary data rewind wasn't possible");
315 return CURLE_SEND_FAIL_REWIND;
321 static int data_pending(const struct connectdata *conn)
323 /* in the case of libssh2, we can never be really sure that we have emptied
324 its internal buffers so we MUST always try until we get EAGAIN back */
325 return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
326 Curl_ssl_data_pending(conn, FIRSTSOCKET);
329 static void read_rewind(struct connectdata *conn,
332 DEBUGASSERT(conn->read_pos >= thismuch);
334 conn->read_pos -= thismuch;
335 conn->bits.stream_was_rewound = TRUE;
342 show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
343 if(conn->master_buffer) {
344 memcpy(buf, conn->master_buffer + conn->read_pos, show);
351 DEBUGF(infof(conn->data,
352 "Buffer after stream rewind (read_pos = %zu): [%s]",
353 conn->read_pos, buf));
359 * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
360 * remote document with the time provided by CURLOPT_TIMEVAL
362 bool Curl_meets_timecondition(struct SessionHandle *data, time_t timeofdoc)
364 if((timeofdoc == 0) || (data->set.timevalue == 0))
367 switch(data->set.timecondition) {
368 case CURL_TIMECOND_IFMODSINCE:
370 if(timeofdoc <= data->set.timevalue) {
372 "The requested document is not new enough\n");
373 data->info.timecond = TRUE;
377 case CURL_TIMECOND_IFUNMODSINCE:
378 if(timeofdoc >= data->set.timevalue) {
380 "The requested document is not old enough\n");
381 data->info.timecond = TRUE;
391 * Go ahead and do a read if we have a readable socket or if
392 * the stream was rewound (in which case we have data in a
395 static CURLcode readwrite_data(struct SessionHandle *data,
396 struct connectdata *conn,
397 struct SingleRequest *k,
398 int *didwhat, bool *done)
400 CURLcode result = CURLE_OK;
401 ssize_t nread; /* number of bytes read */
402 size_t excess = 0; /* excess bytes read */
403 bool is_empty_data = FALSE;
404 #ifndef CURL_DISABLE_RTSP
405 bool readmore = FALSE; /* used by RTP to signal for more data */
410 /* This is where we loop until we have read everything there is to
411 read or we get a CURLE_AGAIN */
413 size_t buffersize = data->set.buffer_size?
414 data->set.buffer_size : BUFSIZE;
415 size_t bytestoread = buffersize;
417 if(k->size != -1 && !k->header) {
418 /* make sure we don't read "too much" if we can help it since we
419 might be pipelining and then someone else might want to read what
421 curl_off_t totalleft = k->size - k->bytecount;
422 if(totalleft < (curl_off_t)bytestoread)
423 bytestoread = (size_t)totalleft;
427 /* receive data from the network! */
428 result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
430 /* read would've blocked */
431 if(CURLE_AGAIN == result)
432 break; /* get out of loop */
438 /* read nothing but since we wanted nothing we consider this an OK
439 situation to proceed from */
443 if((k->bytecount == 0) && (k->writebytecount == 0)) {
444 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
445 if(k->exp100 > EXP100_SEND_DATA)
446 /* set time stamp to compare with when waiting for the 100 */
447 k->start100 = Curl_tvnow();
450 *didwhat |= KEEP_RECV;
451 /* indicates data of zero size, i.e. empty file */
452 is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
454 /* NUL terminate, allowing string ops to be used */
455 if(0 < nread || is_empty_data) {
458 else if(0 >= nread) {
459 /* if we receive 0 or less here, the server closed the connection
460 and we bail out from this! */
461 DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
462 k->keepon &= ~KEEP_RECV;
466 /* Default buffer to use when we write the buffer, it may be changed
467 in the flow below before the actual storing is done. */
470 #ifndef CURL_DISABLE_RTSP
471 /* Check for RTP at the beginning of the data */
472 if(conn->handler->protocol & CURLPROTO_RTSP) {
473 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
481 #ifndef CURL_DISABLE_HTTP
482 /* Since this is a two-state thing, we check if we are parsing
483 headers at the moment or not. */
485 /* we are in parse-the-header-mode */
486 bool stop_reading = FALSE;
487 result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
491 #ifndef CURL_DISABLE_RTSP
492 /* Check for RTP after the headers if there is no Content */
493 if(k->maxdownload <= 0 && nread > 0 &&
494 (conn->handler->protocol & CURLPROTO_RTSP)) {
495 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
504 /* We've stopped dealing with input, get out of the do-while loop */
507 #endif /* CURL_DISABLE_HTTP */
510 /* This is not an 'else if' since it may be a rest from the header
511 parsing, where the beginning of the buffer is headers and the end
513 if(k->str && !k->header && (nread > 0 || is_empty_data)) {
516 #ifndef CURL_DISABLE_HTTP
517 if(0 == k->bodywrites && !is_empty_data) {
518 /* These checks are only made the first time we are about to
519 write a piece of the body */
520 if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
521 /* HTTP-only checks */
523 if(data->req.newurl) {
524 if(conn->bits.close) {
525 /* Abort after the headers if "follow Location" is set
526 and we're set to close anyway. */
527 k->keepon &= ~KEEP_RECV;
531 /* We have a new url to load, but since we want to be able
532 to re-use this connection properly, we read the full
533 response in "ignore more" */
534 k->ignorebody = TRUE;
535 infof(data, "Ignoring the response-body\n");
537 if(data->state.resume_from && !k->content_range &&
538 (data->set.httpreq==HTTPREQ_GET) &&
540 /* we wanted to resume a download, although the server doesn't
541 * seem to support this and we did this with a GET (if it
542 * wasn't a GET we did a POST or PUT resume) */
543 failf(data, "HTTP server doesn't seem to support "
544 "byte ranges. Cannot resume.");
545 return CURLE_RANGE_ERROR;
548 if(data->set.timecondition && !data->state.range) {
549 /* A time condition has been set AND no ranges have been
550 requested. This seems to be what chapter 13.3.4 of
551 RFC 2616 defines to be the correct action for a
554 if(!Curl_meets_timecondition(data, k->timeofdoc)) {
558 } /* we have a time condition */
561 } /* this is the first time we write a body part */
562 #endif /* CURL_DISABLE_HTTP */
565 /* pass data to the debug function before it gets "dechunked" */
566 if(data->set.verbose) {
568 Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
569 (size_t)k->hbuflen, conn);
570 if(k->badheader == HEADER_PARTHEADER)
571 Curl_debug(data, CURLINFO_DATA_IN,
572 k->str, (size_t)nread, conn);
575 Curl_debug(data, CURLINFO_DATA_IN,
576 k->str, (size_t)nread, conn);
579 #ifndef CURL_DISABLE_HTTP
582 * Here comes a chunked transfer flying and we need to decode this
583 * properly. While the name says read, this function both reads
584 * and writes away the data. The returned 'nread' holds the number
585 * of actual data it wrote to the client.
589 Curl_httpchunk_read(conn, k->str, nread, &nread);
591 if(CHUNKE_OK < res) {
592 if(CHUNKE_WRITE_ERROR == res) {
593 failf(data, "Failed writing data");
594 return CURLE_WRITE_ERROR;
596 failf(data, "Received problem %d in the chunky parser", (int)res);
597 return CURLE_RECV_ERROR;
599 else if(CHUNKE_STOP == res) {
601 /* we're done reading chunks! */
602 k->keepon &= ~KEEP_RECV; /* read no more */
604 /* There are now possibly N number of bytes at the end of the
605 str buffer that weren't written to the client.
607 We DO care about this data if we are pipelining.
608 Push it back to be read on the next pass. */
610 dataleft = conn->chunk.dataleft;
612 infof(conn->data, "Leftovers after chunking: %zu bytes", dataleft);
613 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
614 /* only attempt the rewind if we truly are pipelining */
615 infof(conn->data, "Rewinding %zu bytes\n",dataleft);
616 read_rewind(conn, dataleft);
620 /* If it returned OK, we just keep going */
622 #endif /* CURL_DISABLE_HTTP */
624 /* Account for body content stored in the header buffer */
625 if(k->badheader && !k->ignorebody) {
626 DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
628 k->bytecount += k->hbuflen;
631 if((-1 != k->maxdownload) &&
632 (k->bytecount + nread >= k->maxdownload)) {
634 excess = (size_t)(k->bytecount + nread - k->maxdownload);
635 if(excess > 0 && !k->ignorebody) {
636 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
637 /* The 'excess' amount below can't be more than BUFSIZE which
638 always will fit in a size_t */
640 "Rewinding stream by : %zu"
641 " bytes on url %s (size = %" FORMAT_OFF_T
642 ", maxdownload = %" FORMAT_OFF_T
643 ", bytecount = %" FORMAT_OFF_T ", nread = %zd)\n",
644 excess, data->state.path,
645 k->size, k->maxdownload, k->bytecount, nread);
646 read_rewind(conn, excess);
650 "Excess found in a non pipelined read:"
652 ", size = %" FORMAT_OFF_T
653 ", maxdownload = %" FORMAT_OFF_T
654 ", bytecount = %" FORMAT_OFF_T "\n",
655 excess, k->size, k->maxdownload, k->bytecount);
659 nread = (ssize_t) (k->maxdownload - k->bytecount);
660 if(nread < 0 ) /* this should be unusual */
663 k->keepon &= ~KEEP_RECV; /* we're done reading */
666 k->bytecount += nread;
668 Curl_pgrsSetDownloadCounter(data, k->bytecount);
670 if(!k->chunk && (nread || k->badheader || is_empty_data)) {
671 /* If this is chunky transfer, it was already written */
673 if(k->badheader && !k->ignorebody) {
674 /* we parsed a piece of data wrongly assuming it was a header
675 and now we output it as body instead */
677 /* Don't let excess data pollute body writes */
678 if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
679 result = Curl_client_write(conn, CLIENTWRITE_BODY,
680 data->state.headerbuff,
683 result = Curl_client_write(conn, CLIENTWRITE_BODY,
684 data->state.headerbuff,
685 (size_t)k->maxdownload);
690 if(k->badheader < HEADER_ALLBAD) {
691 /* This switch handles various content encodings. If there's an
692 error here, be sure to check over the almost identical code
694 Make sure that ALL_CONTENT_ENCODINGS contains all the
695 encodings handled here. */
697 switch (conn->data->set.http_ce_skip ?
698 IDENTITY : k->content_encoding) {
701 /* This is the default when the server sends no
702 Content-Encoding header. See Curl_readwrite_init; the
703 memset() call initializes k->content_encoding to zero. */
706 #ifndef CURL_DISABLE_POP3
707 if(conn->handler->protocol&CURLPROTO_POP3)
708 result = Curl_pop3_write(conn, k->str, nread);
710 #endif /* CURL_DISABLE_POP3 */
712 result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
719 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
721 result = Curl_unencode_deflate_write(conn, k, nread);
725 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
727 result = Curl_unencode_gzip_write(conn, k, nread);
732 failf (data, "Unrecognized content encoding type. "
733 "libcurl understands `identity', `deflate' and `gzip' "
734 "content encodings.");
735 result = CURLE_BAD_CONTENT_ENCODING;
740 k->badheader = HEADER_NORMAL; /* taken care of now */
746 } /* if(! header and data to read ) */
748 #ifndef CURL_DISABLE_RTSP
749 if(excess > 0 && !conn->bits.stream_was_rewound &&
750 (conn->handler->protocol & CURLPROTO_RTSP)) {
751 /* Check for RTP after the content if there is unrewound excess */
753 /* Parse the excess data */
755 nread = (ssize_t)excess;
757 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
762 k->keepon |= KEEP_RECV; /* we're not done reading */
768 /* if we received nothing, the server closed the connection and we
770 k->keepon &= ~KEEP_RECV;
773 } while(data_pending(conn));
775 if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
777 /* When we've read the entire thing and the close bit is set, the server
778 may now close the connection. If there's now any kind of sending going
779 on from our side, we need to stop that immediately. */
780 infof(data, "we are done reading and this is set to close, stop send\n");
781 k->keepon &= ~KEEP_SEND; /* no writing anymore either */
788 * Send data to upload to the server, when the socket is writable.
790 static CURLcode readwrite_upload(struct SessionHandle *data,
791 struct connectdata *conn,
792 struct SingleRequest *k,
796 ssize_t bytes_written;
798 ssize_t nread; /* number of bytes read */
799 bool sending_http_headers = FALSE;
801 if((k->bytecount == 0) && (k->writebytecount == 0))
802 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
804 *didwhat |= KEEP_SEND;
807 * We loop here to do the READ and SEND loop until we run out of
808 * data to send or until we get EWOULDBLOCK back
812 /* only read more data if there's no upload data already
813 present in the upload buffer */
814 if(0 == data->req.upload_present) {
815 /* init the "upload from here" pointer */
816 data->req.upload_fromhere = k->uploadbuf;
818 if(!k->upload_done) {
819 /* HTTP pollution, this should be written nicer to become more
820 protocol agnostic. */
823 if((k->exp100 == EXP100_SENDING_REQUEST) &&
824 (data->state.proto.http->sending == HTTPSEND_BODY)) {
825 /* If this call is to send body data, we must take some action:
826 We have sent off the full HTTP 1.1 request, and we shall now
827 go into the Expect: 100 state and await such a header */
828 k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
829 k->keepon &= ~KEEP_SEND; /* disable writing */
830 k->start100 = Curl_tvnow(); /* timeout count starts now */
831 *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
833 /* set a timeout for the multi interface */
834 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
838 if(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)) {
839 if(data->state.proto.http->sending == HTTPSEND_REQUEST)
840 /* We're sending the HTTP request headers, not the data.
841 Remember that so we don't change the line endings. */
842 sending_http_headers = TRUE;
844 sending_http_headers = FALSE;
847 result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
851 nread = (ssize_t)fillcount;
854 nread = 0; /* we're done uploading/reading */
856 if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
857 /* this is a paused transfer */
862 k->keepon &= ~KEEP_SEND; /* we're done writing */
864 if(conn->bits.rewindaftersend) {
865 result = Curl_readrewind(conn);
872 /* store number of bytes available for upload */
873 data->req.upload_present = nread;
875 #ifndef CURL_DISABLE_SMTP
876 if(conn->handler->protocol & CURLPROTO_SMTP) {
877 result = Curl_smtp_escape_eob(conn, nread);
882 #endif /* CURL_DISABLE_SMTP */
884 /* convert LF to CRLF if so asked */
885 if((!sending_http_headers) &&
886 #ifdef CURL_DO_LINEEND_CONV
887 /* always convert if we're FTPing in ASCII mode */
888 ((data->set.crlf) || (data->set.prefer_ascii))) {
892 if(data->state.scratch == NULL)
893 data->state.scratch = malloc(2*BUFSIZE);
894 if(data->state.scratch == NULL) {
895 failf (data, "Failed to alloc scratch buffer!");
896 return CURLE_OUT_OF_MEMORY;
899 * ASCII/EBCDIC Note: This is presumably a text (not binary)
900 * transfer so the data should already be in ASCII.
901 * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
902 * must be used instead of the escape sequences \r & \n.
904 for(i = 0, si = 0; i < nread; i++, si++) {
905 if(data->req.upload_fromhere[i] == 0x0a) {
906 data->state.scratch[si++] = 0x0d;
907 data->state.scratch[si] = 0x0a;
908 if(!data->set.crlf) {
909 /* we're here only because FTP is in ASCII mode...
910 bump infilesize for the LF we just added */
911 data->set.infilesize++;
915 data->state.scratch[si] = data->req.upload_fromhere[i];
918 /* only perform the special operation if we really did replace
922 /* upload from the new (replaced) buffer instead */
923 data->req.upload_fromhere = data->state.scratch;
925 /* set the new amount too */
926 data->req.upload_present = nread;
929 } /* if 0 == data->req.upload_present */
931 /* We have a partial buffer left from a previous "round". Use
932 that instead of reading more data */
935 /* write to socket (send away data) */
936 result = Curl_write(conn,
937 conn->writesockfd, /* socket to send to */
938 data->req.upload_fromhere, /* buffer pointer */
939 data->req.upload_present, /* buffer size */
940 &bytes_written); /* actually sent */
945 if(data->set.verbose)
946 /* show the data before we change the pointer upload_fromhere */
947 Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
948 (size_t)bytes_written, conn);
950 k->writebytecount += bytes_written;
952 if(k->writebytecount == data->set.infilesize) {
953 /* we have sent all data we were supposed to */
954 k->upload_done = TRUE;
955 infof(data, "We are completely uploaded and fine\n");
958 if(data->req.upload_present != bytes_written) {
959 /* we only wrote a part of the buffer (if anything), deal with it! */
961 /* store the amount of bytes left in the buffer to write */
962 data->req.upload_present -= bytes_written;
964 /* advance the pointer where to find the buffer when the next send
966 data->req.upload_fromhere += bytes_written;
969 /* we've uploaded that buffer now */
970 data->req.upload_fromhere = k->uploadbuf;
971 data->req.upload_present = 0; /* no more bytes left */
974 /* switch off writing, we're done! */
975 k->keepon &= ~KEEP_SEND; /* we're done writing */
979 Curl_pgrsSetUploadCounter(data, k->writebytecount);
981 } while(0); /* just to break out from! */
987 * Curl_readwrite() is the low-level function to be called when data is to
988 * be read and written to/from the connection.
990 CURLcode Curl_readwrite(struct connectdata *conn,
993 struct SessionHandle *data = conn->data;
994 struct SingleRequest *k = &data->req;
998 curl_socket_t fd_read;
999 curl_socket_t fd_write;
1000 int select_res = conn->cselect_bits;
1002 conn->cselect_bits = 0;
1004 /* only use the proper socket if the *_HOLD bit is not set simultaneously as
1005 then we are in rate limiting state in that transfer direction */
1007 if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
1008 fd_read = conn->sockfd;
1010 fd_read = CURL_SOCKET_BAD;
1012 if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
1013 fd_write = conn->writesockfd;
1015 fd_write = CURL_SOCKET_BAD;
1017 if(!select_res) /* Call for select()/poll() only, if read/write/error
1018 status is not known. */
1019 select_res = Curl_socket_ready(fd_read, fd_write, 0);
1021 if(select_res == CURL_CSELECT_ERR) {
1022 failf(data, "select/poll returned error");
1023 return CURLE_SEND_ERROR;
1026 /* We go ahead and do a read if we have a readable socket or if
1027 the stream was rewound (in which case we have data in a
1029 if((k->keepon & KEEP_RECV) &&
1030 ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
1032 result = readwrite_data(data, conn, k, &didwhat, done);
1037 /* If we still have writing to do, we check if we have a writable socket. */
1038 if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
1041 result = readwrite_upload(data, conn, k, &didwhat);
1046 k->now = Curl_tvnow();
1048 /* Update read/write counters */
1050 *k->bytecountp = k->bytecount; /* read count */
1051 if(k->writebytecountp)
1052 *k->writebytecountp = k->writebytecount; /* write count */
1055 /* no read no write, this is a timeout? */
1056 if(k->exp100 == EXP100_AWAITING_CONTINUE) {
1057 /* This should allow some time for the header to arrive, but only a
1058 very short time as otherwise it'll be too much wasted time too
1061 /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
1063 Therefore, when a client sends this header field to an origin server
1064 (possibly via a proxy) from which it has never seen a 100 (Continue)
1065 status, the client SHOULD NOT wait for an indefinite period before
1066 sending the request body.
1070 long ms = Curl_tvdiff(k->now, k->start100);
1071 if(ms > CURL_TIMEOUT_EXPECT_100) {
1072 /* we've waited long enough, continue anyway */
1073 k->exp100 = EXP100_SEND_DATA;
1074 k->keepon |= KEEP_SEND;
1075 infof(data, "Done waiting for 100-continue\n");
1080 if(Curl_pgrsUpdate(conn))
1081 result = CURLE_ABORTED_BY_CALLBACK;
1083 result = Curl_speedcheck(data, k->now);
1088 if(0 > Curl_timeleft(data, &k->now, FALSE)) {
1090 failf(data, "Operation timed out after %ld milliseconds with %"
1091 FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes received",
1092 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount,
1096 failf(data, "Operation timed out after %ld milliseconds with %"
1097 FORMAT_OFF_T " bytes received",
1098 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount);
1100 return CURLE_OPERATION_TIMEDOUT;
1105 * The transfer has been performed. Just make some general checks before
1109 if(!(data->set.opt_no_body) && (k->size != -1) &&
1110 (k->bytecount != k->size) &&
1111 #ifdef CURL_DO_LINEEND_CONV
1112 /* Most FTP servers don't adjust their file SIZE response for CRLFs,
1113 so we'll check to see if the discrepancy can be explained
1114 by the number of CRLFs we've changed to LFs.
1116 (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1117 #endif /* CURL_DO_LINEEND_CONV */
1118 !data->req.newurl) {
1119 failf(data, "transfer closed with %" FORMAT_OFF_T
1120 " bytes remaining to read",
1121 k->size - k->bytecount);
1122 return CURLE_PARTIAL_FILE;
1124 else if(!(data->set.opt_no_body) &&
1126 (conn->chunk.state != CHUNK_STOP)) {
1128 * In chunked mode, return an error if the connection is closed prior to
1129 * the empty (terminiating) chunk is read.
1131 * The condition above used to check for
1132 * conn->proto.http->chunk.datasize != 0 which is true after reading
1133 * *any* chunk, not just the empty chunk.
1136 failf(data, "transfer closed with outstanding read data remaining");
1137 return CURLE_PARTIAL_FILE;
1139 if(Curl_pgrsUpdate(conn))
1140 return CURLE_ABORTED_BY_CALLBACK;
1143 /* Now update the "done" boolean we return */
1144 *done = (bool)(0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
1145 KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)));
1151 * Curl_single_getsock() gets called by the multi interface code when the app
1152 * has requested to get the sockets for the current connection. This function
1153 * will then be called once for every connection that the multi interface
1154 * keeps track of. This function will only be called for connections that are
1155 * in the proper state to have this information available.
1157 int Curl_single_getsock(const struct connectdata *conn,
1158 curl_socket_t *sock, /* points to numsocks number
1162 const struct SessionHandle *data = conn->data;
1163 int bitmap = GETSOCK_BLANK;
1164 unsigned sockindex = 0;
1166 if(conn->handler->perform_getsock)
1167 return conn->handler->perform_getsock(conn, sock, numsocks);
1170 /* simple check but we might need two slots */
1171 return GETSOCK_BLANK;
1173 /* don't include HOLD and PAUSE connections */
1174 if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
1176 DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1178 bitmap |= GETSOCK_READSOCK(sockindex);
1179 sock[sockindex] = conn->sockfd;
1182 /* don't include HOLD and PAUSE connections */
1183 if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
1185 if((conn->sockfd != conn->writesockfd) ||
1186 !(data->req.keepon & KEEP_RECV)) {
1187 /* only if they are not the same socket or we didn't have a readable
1188 one, we increase index */
1189 if(data->req.keepon & KEEP_RECV)
1190 sockindex++; /* increase index if we need two entries */
1192 DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1194 sock[sockindex] = conn->writesockfd;
1197 bitmap |= GETSOCK_WRITESOCK(sockindex);
1204 * Determine optimum sleep time based on configured rate, current rate,
1206 * Returns value in mili-seconds.
1208 * The basic idea is to adjust the desired rate up/down in this method
1209 * based on whether we are running too slow or too fast. Then, calculate
1210 * how many miliseconds to wait for the next packet to achieve this new
1213 long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
1216 curl_off_t min_sleep = 0;
1222 /* If running faster than about .1% of the desired speed, slow
1223 * us down a bit. Use shift instead of division as the 0.1%
1224 * cutoff is arbitrary anyway.
1226 if (cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
1227 /* running too fast, decrease target rate by 1/64th of rate */
1228 rate_bps -= rate_bps >> 6;
1231 else if (cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
1232 /* running too slow, increase target rate by 1/64th of rate */
1233 rate_bps += rate_bps >> 6;
1236 /* Determine number of miliseconds to wait until we do
1237 * the next packet at the adjusted rate. We should wait
1238 * longer when using larger packets, for instance.
1240 rv = ((curl_off_t)((pkt_size * 8) * 1000) / rate_bps);
1242 /* Catch rounding errors and always slow down at least 1ms if
1243 * we are running too fast.
1248 /* Bound value to fit in 'long' on 32-bit platform. That's
1249 * plenty long enough anyway!
1261 * This function is what performs the actual transfer. It is capable of doing
1262 * both ways simultaneously. The transfer must already have been setup by a
1263 * call to Curl_setup_transfer().
1265 * Note that headers are created in a preallocated buffer of a default size.
1266 * That buffer can be enlarged on demand, but it is never shrunken again.
1271 Transfer(struct connectdata *conn)
1274 struct SessionHandle *data = conn->data;
1275 struct SingleRequest *k = &data->req;
1282 if((conn->sockfd == CURL_SOCKET_BAD) &&
1283 (conn->writesockfd == CURL_SOCKET_BAD))
1284 /* nothing to read, nothing to write, we're already OK! */
1287 /* we want header and/or body, if neither then don't do this! */
1288 if(!k->getheader && data->set.opt_no_body)
1292 curl_socket_t fd_read = conn->sockfd;
1293 curl_socket_t fd_write = conn->writesockfd;
1294 int keepon = k->keepon;
1298 /* if waitfor is set, get the RECV and SEND bits from that but keep the
1300 keepon &= ~ (KEEP_RECV|KEEP_SEND);
1301 keepon |= conn->waitfor & (KEEP_RECV|KEEP_SEND);
1304 /* limit-rate logic: if speed exceeds threshold, then do not include fd in
1305 select set. The current speed is recalculated in each Curl_readwrite()
1307 if((keepon & KEEP_SEND) &&
1308 (!data->set.max_send_speed ||
1309 (data->progress.ulspeed < data->set.max_send_speed) )) {
1310 k->keepon &= ~KEEP_SEND_HOLD;
1313 if (data->set.upload && data->set.max_send_speed &&
1314 (data->progress.ulspeed > data->set.max_send_speed) ) {
1315 /* calculate upload rate-limitation timeout. */
1316 buffersize = (int)(data->set.buffer_size ?
1317 data->set.buffer_size : BUFSIZE);
1318 totmp = (int)Curl_sleep_time(data->set.max_send_speed,
1319 data->progress.ulspeed, buffersize);
1320 if (totmp < timeout_ms)
1323 fd_write = CURL_SOCKET_BAD;
1324 if(keepon & KEEP_SEND)
1325 k->keepon |= KEEP_SEND_HOLD; /* hold it */
1328 if((keepon & KEEP_RECV) &&
1329 (!data->set.max_recv_speed ||
1330 (data->progress.dlspeed < data->set.max_recv_speed)) ) {
1331 k->keepon &= ~KEEP_RECV_HOLD;
1334 if ((!data->set.upload) && data->set.max_recv_speed &&
1335 (data->progress.dlspeed > data->set.max_recv_speed)) {
1336 /* Calculate download rate-limitation timeout. */
1337 buffersize = (int)(data->set.buffer_size ?
1338 data->set.buffer_size : BUFSIZE);
1339 totmp = (int)Curl_sleep_time(data->set.max_recv_speed,
1340 data->progress.dlspeed, buffersize);
1341 if (totmp < timeout_ms)
1344 fd_read = CURL_SOCKET_BAD;
1345 if(keepon & KEEP_RECV)
1346 k->keepon |= KEEP_RECV_HOLD; /* hold it */
1349 /* pause logic. Don't check descriptors for paused connections */
1350 if(k->keepon & KEEP_RECV_PAUSE)
1351 fd_read = CURL_SOCKET_BAD;
1352 if(k->keepon & KEEP_SEND_PAUSE)
1353 fd_write = CURL_SOCKET_BAD;
1355 /* The *_HOLD and *_PAUSE logic is necessary since even though there might
1356 be no traffic during the select interval, we still call
1357 Curl_readwrite() for the timeout case and if we limit transfer speed we
1358 must make sure that this function doesn't transfer anything while in
1361 The no timeout for the first round is for the protocols for which data
1362 has already been slurped off the socket and thus waiting for action
1363 won't work since it'll wait even though there is already data present
1366 ((fd_read != CURL_SOCKET_BAD) || (fd_write != CURL_SOCKET_BAD)))
1367 /* if this is the first lap and one of the file descriptors is fine
1368 to work with, skip the timeout */
1371 totmp = Curl_timeleft(data, &k->now, FALSE);
1373 return CURLE_OPERATION_TIMEDOUT;
1377 if (totmp < timeout_ms)
1381 switch (Curl_socket_ready(fd_read, fd_write, timeout_ms)) {
1382 case -1: /* select() error, stop reading */
1384 /* The EINTR is not serious, and it seems you might get this more
1385 often when using the lib in a multi-threaded environment! */
1386 if(SOCKERRNO == EINTR)
1389 return CURLE_RECV_ERROR; /* indicate a network problem */
1390 case 0: /* timeout */
1391 default: /* readable descriptors */
1393 result = Curl_readwrite(conn, &done);
1394 /* "done" signals to us if the transfer(s) are ready */
1400 first = FALSE; /* not the first lap anymore */
1406 static CURLcode loadhostpairs(struct SessionHandle *data)
1408 struct curl_slist *hostp;
1413 for(hostp = data->change.resolve; hostp; hostp = hostp->next ) {
1416 if(hostp->data[0] == '-') {
1417 /* TODO: mark an entry for removal */
1419 else if(3 == sscanf(hostp->data, "%255[^:]:%d:%255s", hostname, &port,
1421 struct Curl_dns_entry *dns;
1422 Curl_addrinfo *addr;
1424 addr = Curl_str2addr(address, port);
1426 infof(data, "Resolve %s found illegal!\n", hostp->data);
1429 infof(data, "Added %s:%d:%s to DNS cache\n",
1430 hostname, port, address);
1433 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1435 /* put this host in the cache */
1436 dns = Curl_cache_addr(data, addr, hostname, port);
1439 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1442 return CURLE_OUT_OF_MEMORY;
1445 data->change.resolve = NULL; /* dealt with now */
1452 * Curl_pretransfer() is called immediately before a transfer starts.
1454 CURLcode Curl_pretransfer(struct SessionHandle *data)
1457 if(!data->change.url) {
1458 /* we can't do anything without URL */
1459 failf(data, "No URL set!");
1460 return CURLE_URL_MALFORMAT;
1463 /* Init the SSL session ID cache here. We do it here since we want to do it
1464 after the *_setopt() calls (that could change the size of the cache) but
1465 before any transfer takes place. */
1466 res = Curl_ssl_initsessions(data, data->set.ssl.numsessions);
1470 data->set.followlocation=0; /* reset the location-follow counter */
1471 data->state.this_is_a_follow = FALSE; /* reset this */
1472 data->state.errorbuf = FALSE; /* no error has occurred */
1473 data->state.httpversion = 0; /* don't assume any particular server version */
1475 data->state.ssl_connect_retry = FALSE;
1477 data->state.authproblem = FALSE;
1478 data->state.authhost.want = data->set.httpauth;
1479 data->state.authproxy.want = data->set.proxyauth;
1480 Curl_safefree(data->info.wouldredirect);
1481 data->info.wouldredirect = NULL;
1483 /* If there is a list of cookie files to read, do it now! */
1484 if(data->change.cookielist)
1485 Curl_cookie_loadfiles(data);
1487 /* If there is a list of host pairs to deal with */
1488 if(data->change.resolve)
1489 res = loadhostpairs(data);
1492 /* Allow data->set.use_port to set which port to use. This needs to be
1493 * disabled for example when we follow Location: headers to URLs using
1494 * different ports! */
1495 data->state.allow_port = TRUE;
1497 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1498 /*************************************************************
1499 * Tell signal handler to ignore SIGPIPE
1500 *************************************************************/
1501 if(!data->set.no_signal)
1502 data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
1505 Curl_initinfo(data); /* reset session-specific information "variables" */
1506 Curl_pgrsStartNow(data);
1508 if(data->set.timeout)
1509 Curl_expire(data, data->set.timeout);
1511 if(data->set.connecttimeout)
1512 Curl_expire(data, data->set.connecttimeout);
1519 * Curl_posttransfer() is called immediately after a transfer ends
1521 CURLcode Curl_posttransfer(struct SessionHandle *data)
1523 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1524 /* restore the signal handler for SIGPIPE before we get back */
1525 if(!data->set.no_signal)
1526 signal(SIGPIPE, data->state.prev_signal);
1528 (void)data; /* unused parameter */
1534 #ifndef CURL_DISABLE_HTTP
1536 * strlen_url() returns the length of the given URL if the spaces within the
1537 * URL were properly URL encoded.
1539 static size_t strlen_url(const char *url)
1543 bool left=TRUE; /* left side of the ? */
1545 for(ptr=url; *ptr; ptr++) {
1564 /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
1565 * the source URL accordingly.
1567 static void strcpy_url(char *output, const char *url)
1569 /* we must add this with whitespace-replacing */
1572 char *optr = output;
1573 for(iptr = url; /* read from here */
1574 *iptr; /* until zero byte */
1585 *optr++='%'; /* add a '%' */
1586 *optr++='2'; /* add a '2' */
1587 *optr++='0'; /* add a '0' */
1590 *optr++='+'; /* add a '+' here */
1594 *optr=0; /* zero terminate output buffer */
1599 * Returns true if the given URL is absolute (as opposed to relative)
1601 static bool is_absolute_url(const char *url)
1603 char prot[16]; /* URL protocol string storage */
1604 char letter; /* used for a silly sscanf */
1606 return (bool)(2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter));
1610 * Concatenate a relative URL to a base URL making it absolute.
1611 * URL-encodes any spaces.
1612 * The returned pointer must be freed by the caller unless NULL
1613 * (returns NULL on out of memory).
1615 static char *concat_url(const char *base, const char *relurl)
1618 TRY to append this new path to the old URL
1619 to the right of the host part. Oh crap, this is doomed to cause
1620 problems in the future...
1627 const char *useurl = relurl;
1630 /* we must make our own copy of the URL to play with, as it may
1631 point to read-only data */
1632 char *url_clone=strdup(base);
1635 return NULL; /* skip out of this NOW */
1637 /* protsep points to the start of the host name */
1638 protsep=strstr(url_clone, "//");
1642 protsep+=2; /* pass the slashes */
1644 if('/' != relurl[0]) {
1647 /* First we need to find out if there's a ?-letter in the URL,
1648 and cut it and the right-side of that off */
1649 pathsep = strchr(protsep, '?');
1653 /* we have a relative path to append to the last slash if there's one
1654 available, or if the new URL is just a query string (starts with a
1655 '?') we append the new one at the end of the entire currently worked
1657 if(useurl[0] != '?') {
1658 pathsep = strrchr(protsep, '/');
1663 /* Check if there's any slash after the host name, and if so, remember
1664 that position instead */
1665 pathsep = strchr(protsep, '/');
1667 protsep = pathsep+1;
1671 /* now deal with one "./" or any amount of "../" in the newurl
1672 and act accordingly */
1674 if((useurl[0] == '.') && (useurl[1] == '/'))
1675 useurl+=2; /* just skip the "./" */
1677 while((useurl[0] == '.') &&
1678 (useurl[1] == '.') &&
1679 (useurl[2] == '/')) {
1681 useurl+=3; /* pass the "../" */
1686 /* cut off one more level from the right of the original URL */
1687 pathsep = strrchr(protsep, '/');
1698 /* We got a new absolute path for this server, cut off from the
1700 pathsep = strchr(protsep, '/');
1702 /* When people use badly formatted URLs, such as
1703 "http://www.url.com?dir=/home/daniel" we must not use the first
1704 slash, if there's a ?-letter before it! */
1705 char *sep = strchr(protsep, '?');
1706 if(sep && (sep < pathsep))
1711 /* There was no slash. Now, since we might be operating on a badly
1712 formatted URL, such as "http://www.url.com?id=2380" which doesn't
1713 use a slash separator as it is supposed to, we need to check for a
1714 ?-letter as well! */
1715 pathsep = strchr(protsep, '?');
1721 /* If the new part contains a space, this is a mighty stupid redirect
1722 but we still make an effort to do "right". To the left of a '?'
1723 letter we replace each space with %20 while it is replaced with '+'
1724 on the right side of the '?' letter.
1726 newlen = strlen_url(useurl);
1728 urllen = strlen(url_clone);
1730 newest = malloc( urllen + 1 + /* possible slash */
1731 newlen + 1 /* zero byte */);
1734 free(url_clone); /* don't leak this */
1738 /* copy over the root url part */
1739 memcpy(newest, url_clone, urllen);
1741 /* check if we need to append a slash */
1742 if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
1745 newest[urllen++]='/';
1747 /* then append the new piece on the right side */
1748 strcpy_url(&newest[urllen], useurl);
1754 #endif /* CURL_DISABLE_HTTP */
1757 * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
1758 * as given by the remote server and set up the new URL to request.
1760 CURLcode Curl_follow(struct SessionHandle *data,
1761 char *newurl, /* this 'newurl' is the Location: string,
1762 and it must be malloc()ed before passed
1764 followtype type) /* see transfer.h */
1766 #ifdef CURL_DISABLE_HTTP
1770 /* Location: following will not happen when HTTP is disabled */
1771 return CURLE_TOO_MANY_REDIRECTS;
1774 /* Location: redirect */
1775 bool disallowport = FALSE;
1777 if(type == FOLLOW_REDIR) {
1778 if((data->set.maxredirs != -1) &&
1779 (data->set.followlocation >= data->set.maxredirs)) {
1780 failf(data,"Maximum (%ld) redirects followed", data->set.maxredirs);
1781 return CURLE_TOO_MANY_REDIRECTS;
1784 /* mark the next request as a followed location: */
1785 data->state.this_is_a_follow = TRUE;
1787 data->set.followlocation++; /* count location-followers */
1789 if(data->set.http_auto_referer) {
1790 /* We are asked to automatically set the previous URL as the referer
1791 when we get the next URL. We pick the ->url field, which may or may
1792 not be 100% correct */
1794 if(data->change.referer_alloc)
1795 /* If we already have an allocated referer, free this first */
1796 free(data->change.referer);
1798 data->change.referer = strdup(data->change.url);
1799 if (!data->change.referer) {
1800 data->change.referer_alloc = FALSE;
1801 return CURLE_OUT_OF_MEMORY;
1803 data->change.referer_alloc = TRUE; /* yes, free this later */
1807 if(!is_absolute_url(newurl)) {
1809 *DANG* this is an RFC 2068 violation. The URL is supposed
1810 to be absolute and this doesn't seem to be that!
1812 char *absolute = concat_url(data->change.url, newurl);
1814 return CURLE_OUT_OF_MEMORY;
1819 /* This is an absolute URL, don't allow the custom port number */
1820 disallowport = TRUE;
1822 if(strchr(newurl, ' ')) {
1823 /* This new URL contains at least one space, this is a mighty stupid
1824 redirect but we still make an effort to do "right". */
1826 size_t newlen = strlen_url(newurl);
1828 newest = malloc(newlen+1); /* get memory for this */
1830 return CURLE_OUT_OF_MEMORY;
1831 strcpy_url(newest, newurl); /* create a space-free URL */
1833 free(newurl); /* that was no good */
1834 newurl = newest; /* use this instead now */
1839 if(type == FOLLOW_FAKE) {
1840 /* we're only figuring out the new url if we would've followed locations
1841 but now we're done so we can get out! */
1842 data->info.wouldredirect = newurl;
1847 data->state.allow_port = FALSE;
1849 if(data->change.url_alloc)
1850 free(data->change.url);
1852 data->change.url_alloc = TRUE; /* the URL is allocated */
1854 data->change.url = newurl;
1855 newurl = NULL; /* don't free! */
1857 infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
1860 * We get here when the HTTP code is 300-399 (and 401). We need to perform
1861 * differently based on exactly what return code there was.
1863 * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
1864 * a HTTP (proxy-) authentication scheme other than Basic.
1866 switch(data->info.httpcode) {
1867 /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
1868 Authorization: XXXX header in the HTTP request code snippet */
1869 /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
1870 Proxy-Authorization: XXXX header in the HTTP request code snippet */
1871 /* 300 - Multiple Choices */
1872 /* 306 - Not used */
1873 /* 307 - Temporary Redirect */
1874 default: /* for all above (and the unknown ones) */
1875 /* Some codes are explicitly mentioned since I've checked RFC2616 and they
1876 * seem to be OK to POST to.
1879 case 301: /* Moved Permanently */
1880 /* (quote from RFC2616, section 10.3.2):
1882 * Note: When automatically redirecting a POST request after receiving a
1883 * 301 status code, some existing HTTP/1.0 user agents will erroneously
1884 * change it into a GET request.
1888 * Warning: Because most of importants user agents do this obvious RFC2616
1889 * violation, many webservers expect this misbehavior. So these servers
1890 * often answers to a POST request with an error page. To be sure that
1891 * libcurl gets the page that most user agents would get, libcurl has to
1894 * This behaviour can be overridden with CURLOPT_POSTREDIR.
1896 if( (data->set.httpreq == HTTPREQ_POST
1897 || data->set.httpreq == HTTPREQ_POST_FORM)
1898 && !data->set.post301) {
1900 "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
1901 data->set.httpreq = HTTPREQ_GET;
1904 case 302: /* Found */
1907 Note: RFC 1945 and RFC 2068 specify that the client is not allowed
1908 to change the method on the redirected request. However, most
1909 existing user agent implementations treat 302 as if it were a 303
1910 response, performing a GET on the Location field-value regardless
1911 of the original request method. The status codes 303 and 307 have
1912 been added for servers that wish to make unambiguously clear which
1913 kind of reaction is expected of the client.
1917 Note: Many pre-HTTP/1.1 user agents do not understand the 303
1918 status. When interoperability with such clients is a concern, the
1919 302 status code may be used instead, since most user agents react
1920 to a 302 response as described here for 303.
1922 This behaviour can be overriden with CURLOPT_POSTREDIR
1924 if( (data->set.httpreq == HTTPREQ_POST
1925 || data->set.httpreq == HTTPREQ_POST_FORM)
1926 && !data->set.post302) {
1928 "Violate RFC 2616/10.3.3 and switch from POST to GET\n");
1929 data->set.httpreq = HTTPREQ_GET;
1933 case 303: /* See Other */
1934 /* Disable both types of POSTs, since doing a second POST when
1935 * following isn't what anyone would want! */
1936 if(data->set.httpreq != HTTPREQ_GET) {
1937 data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
1938 infof(data, "Disables POST, goes with %s\n",
1939 data->set.opt_no_body?"HEAD":"GET");
1942 case 304: /* Not Modified */
1943 /* 304 means we did a conditional request and it was "Not modified".
1944 * We shouldn't get any Location: header in this response!
1947 case 305: /* Use Proxy */
1948 /* (quote from RFC2616, section 10.3.6):
1949 * "The requested resource MUST be accessed through the proxy given
1950 * by the Location field. The Location field gives the URI of the
1951 * proxy. The recipient is expected to repeat this single request
1952 * via the proxy. 305 responses MUST only be generated by origin
1957 Curl_pgrsTime(data, TIMER_REDIRECT);
1958 Curl_pgrsResetTimes(data);
1961 #endif /* CURL_DISABLE_HTTP */
1965 connect_host(struct SessionHandle *data,
1966 struct connectdata **conn)
1968 CURLcode res = CURLE_OK;
1971 bool protocol_done=TRUE; /* will be TRUE always since this is only used
1972 within the easy interface */
1973 Curl_pgrsTime(data, TIMER_STARTSINGLE);
1974 res = Curl_connect(data, conn, &async, &protocol_done);
1976 if((CURLE_OK == res) && async) {
1977 /* Now, if async is TRUE here, we need to wait for the name
1979 res = Curl_wait_for_resolv(*conn, NULL);
1981 /* Resolved, continue with the connection */
1982 res = Curl_async_resolved(*conn, &protocol_done);
1984 /* if we can't resolve, we kill this "connection" now */
1985 (void)Curl_disconnect(*conn, /* dead_connection */ FALSE);
1992 Curl_reconnect_request(struct connectdata **connp)
1994 CURLcode result = CURLE_OK;
1995 struct connectdata *conn = *connp;
1996 struct SessionHandle *data = conn->data;
1998 /* This was a re-use of a connection and we got a write error in the
1999 * DO-phase. Then we DISCONNECT this connection and have another attempt to
2000 * CONNECT and then DO again! The retry cannot possibly find another
2001 * connection to re-use, since we only keep one possible connection for
2004 infof(data, "Re-used connection seems dead, get a new one\n");
2006 conn->bits.close = TRUE; /* enforce close of this connection */
2007 result = Curl_done(&conn, result, FALSE); /* we are so done with this */
2009 /* conn may no longer be a good pointer */
2012 * According to bug report #1330310. We need to check for CURLE_SEND_ERROR
2013 * here as well. I figure this could happen when the request failed on a FTP
2014 * connection and thus Curl_done() itself tried to use the connection
2015 * (again). Slight Lack of feedback in the report, but I don't think this
2016 * extra check can do much harm.
2018 if((CURLE_OK == result) || (CURLE_SEND_ERROR == result)) {
2020 bool protocol_done = TRUE;
2022 /* Now, redo the connect and get a new connection */
2023 result = Curl_connect(data, connp, &async, &protocol_done);
2024 if(CURLE_OK == result) {
2025 /* We have connected or sent away a name resolve query fine */
2027 conn = *connp; /* setup conn to again point to something nice */
2029 /* Now, if async is TRUE here, we need to wait for the name
2031 result = Curl_wait_for_resolv(conn, NULL);
2035 /* Resolved, continue with the connection */
2036 result = Curl_async_resolved(conn, &protocol_done);
2046 /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
2048 NOTE: that the *url is malloc()ed. */
2049 CURLcode Curl_retry_request(struct connectdata *conn,
2052 struct SessionHandle *data = conn->data;
2056 /* if we're talking upload, we can't do the checks below, unless the protocol
2057 is HTTP as when uploading over HTTP we will still get a response */
2058 if(data->set.upload &&
2059 !(conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_RTSP)))
2062 if(/* workaround for broken TLS servers */ data->state.ssl_connect_retry ||
2063 ((data->req.bytecount +
2064 data->req.headerbytecount == 0) &&
2066 !data->set.opt_no_body &&
2067 data->set.rtspreq != RTSPREQ_RECEIVE)) {
2068 /* We got no data, we attempted to re-use a connection and yet we want a
2069 "body". This might happen if the connection was left alive when we were
2070 done using it before, but that was closed when we wanted to read from
2071 it again. Bad luck. Retry the same request on a fresh connect! */
2072 infof(conn->data, "Connection died, retrying a fresh connect\n");
2073 *url = strdup(conn->data->change.url);
2075 return CURLE_OUT_OF_MEMORY;
2077 conn->bits.close = TRUE; /* close this connection */
2078 conn->bits.retry = TRUE; /* mark this as a connection we're about
2079 to retry. Marking it this way should
2080 prevent i.e HTTP transfers to return
2081 error just because nothing has been
2084 if(data->state.proto.http->writebytecount)
2085 Curl_readrewind(conn);
2090 static CURLcode Curl_do_perform(struct SessionHandle *data)
2094 struct connectdata *conn=NULL;
2095 char *newurl = NULL; /* possibly a new URL to follow to! */
2096 followtype follow = FOLLOW_NONE;
2098 data->state.used_interface = Curl_if_easy;
2100 res = Curl_pretransfer(data);
2105 * It is important that there is NO 'return' from this function at any other
2106 * place than falling down to the end of the function! This is because we
2107 * have cleanup stuff that must be done before we get back, and that is only
2108 * performed after this do-while loop.
2112 res = connect_host(data, &conn); /* primary connection */
2114 if(res == CURLE_OK) {
2116 if(data->set.connect_only) {
2117 /* keep connection open for application to use the socket */
2118 conn->bits.close = FALSE;
2119 res = Curl_done(&conn, CURLE_OK, FALSE);
2122 res = Curl_do(&conn, &do_done);
2124 if(res == CURLE_OK) {
2125 if(conn->data->set.wildcardmatch) {
2126 if(conn->data->wildcard.state == CURLWC_DONE ||
2127 conn->data->wildcard.state == CURLWC_SKIP) {
2128 /* keep connection open for application to use the socket */
2129 conn->bits.close = FALSE;
2130 res = Curl_done(&conn, CURLE_OK, FALSE);
2134 res = Transfer(conn); /* now fetch that URL please */
2135 if((res == CURLE_OK) || (res == CURLE_RECV_ERROR)) {
2137 CURLcode rc = Curl_retry_request(conn, &newurl);
2141 retry = (newurl?TRUE:FALSE);
2144 /* we know (newurl != NULL) at this point */
2146 follow = FOLLOW_RETRY;
2148 else if (res == CURLE_OK) {
2150 * We must duplicate the new URL here as the connection data may
2151 * be free()ed in the Curl_done() function. We prefer the newurl
2152 * one since that's used for redirects or just further requests
2153 * for retries or multi-stage HTTP auth methods etc.
2155 if(data->req.newurl) {
2156 follow = FOLLOW_REDIR;
2157 newurl = strdup(data->req.newurl);
2159 res = CURLE_OUT_OF_MEMORY;
2161 else if(data->req.location) {
2162 follow = FOLLOW_FAKE;
2163 newurl = strdup(data->req.location);
2165 res = CURLE_OUT_OF_MEMORY;
2169 /* in the above cases where 'newurl' gets assigned, we have a fresh
2170 * allocated memory pointed to */
2172 if(res != CURLE_OK) {
2173 /* The transfer phase returned error, we mark the connection to get
2174 * closed to prevent being re-used. This is because we can't
2175 * possibly know if the connection is in a good shape or not now. */
2176 conn->bits.close = TRUE;
2178 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
2179 /* if we failed anywhere, we must clean up the secondary socket if
2181 sclose(conn->sock[SECONDARYSOCKET]);
2182 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
2186 /* Always run Curl_done(), even if some of the previous calls
2187 failed, but return the previous (original) error code */
2188 res2 = Curl_done(&conn, res, FALSE);
2194 /* Curl_do() failed, clean up left-overs in the done-call, but note
2195 that at some cases the conn pointer is NULL when Curl_do() failed
2196 and the connection cache is very small so only call Curl_done() if
2197 conn is still "alive". */
2198 /* ignore return code since we already have an error to return */
2199 (void)Curl_done(&conn, res, FALSE);
2202 * Important: 'conn' cannot be used here, since it may have been closed
2203 * in 'Curl_done' or other functions.
2206 if((res == CURLE_OK) && follow) {
2207 res = Curl_follow(data, newurl, follow);
2208 if(CURLE_OK == res) {
2209 /* if things went fine, Curl_follow() freed or otherwise took
2210 responsibility for the newurl pointer */
2212 if(follow >= FOLLOW_RETRY) {
2213 follow = FOLLOW_NONE;
2216 /* else we break out of the loop below */
2220 break; /* it only reaches here when this shouldn't loop */
2222 } /* loop if Location: */
2227 if(res && !data->state.errorbuf) {
2229 * As an extra precaution: if no error string has been set and there was
2230 * an error, use the strerror() string or if things are so bad that not
2231 * even that is good, set a bad string that mentions the error code.
2233 const char *str = curl_easy_strerror(res);
2235 failf(data, "unspecified error %d", (int)res);
2237 failf(data, "%s", str);
2240 /* run post-transfer unconditionally, but don't clobber the return code if
2241 we already have an error code recorder */
2242 res2 = Curl_posttransfer(data);
2250 * Curl_perform() is the internal high-level function that gets called by the
2251 * external curl_easy_perform() function. It inits, performs and cleans up a
2252 * single file transfer.
2254 CURLcode Curl_perform(struct SessionHandle *data)
2257 if(!data->set.wildcardmatch)
2258 return Curl_do_perform(data);
2260 /* init main wildcard structures */
2261 res = Curl_wildcard_init(&data->wildcard);
2265 res = Curl_do_perform(data);
2267 Curl_wildcard_dtor(&data->wildcard);
2272 while(!res && data->wildcard.state != CURLWC_DONE)
2273 res = Curl_do_perform(data);
2275 Curl_wildcard_dtor(&data->wildcard);
2277 /* wildcard download finished or failed */
2278 data->wildcard.state = CURLWC_INIT;
2283 * Curl_setup_transfer() is called to setup some basic properties for the
2284 * upcoming transfer.
2287 Curl_setup_transfer(
2288 struct connectdata *conn, /* connection data */
2289 int sockindex, /* socket index to read from or -1 */
2290 curl_off_t size, /* -1 if unknown at this point */
2291 bool getheader, /* TRUE if header parsing is wanted */
2292 curl_off_t *bytecountp, /* return number of bytes read or NULL */
2293 int writesockindex, /* socket index to write to, it may very well be
2294 the same we read from. -1 disables */
2295 curl_off_t *writecountp /* return number of bytes written or NULL */
2298 struct SessionHandle *data;
2299 struct SingleRequest *k;
2301 DEBUGASSERT(conn != NULL);
2306 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
2308 /* now copy all input parameters */
2309 conn->sockfd = sockindex == -1 ?
2310 CURL_SOCKET_BAD : conn->sock[sockindex];
2311 conn->writesockfd = writesockindex == -1 ?
2312 CURL_SOCKET_BAD:conn->sock[writesockindex];
2313 k->getheader = getheader;
2316 k->bytecountp = bytecountp;
2317 k->writebytecountp = writecountp;
2319 /* The code sequence below is placed in this function just because all
2320 necessary input is not always known in do_complete() as this function may
2321 be called after that */
2326 Curl_pgrsSetDownloadSize(data, size);
2328 /* we want header and/or body, if neither then don't do this! */
2329 if(k->getheader || !data->set.opt_no_body) {
2331 if(conn->sockfd != CURL_SOCKET_BAD)
2332 k->keepon |= KEEP_RECV;
2334 if(conn->writesockfd != CURL_SOCKET_BAD) {
2337 Even if we require a 100-return code before uploading data, we might
2338 need to write data before that since the REQUEST may not have been
2339 finished sent off just yet.
2341 Thus, we must check if the request has been sent before we set the
2342 state info where we wait for the 100-return code
2344 if((data->state.expect100header) &&
2345 (data->state.proto.http->sending == HTTPSEND_BODY)) {
2346 /* wait with write until we either got 100-continue or a timeout */
2347 k->exp100 = EXP100_AWAITING_CONTINUE;
2348 k->start100 = k->start;
2350 /* set a timeout for the multi interface */
2351 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
2354 if(data->state.expect100header)
2355 /* when we've sent off the rest of the headers, we must await a
2356 100-continue but first finish sending the request */
2357 k->exp100 = EXP100_SENDING_REQUEST;
2359 /* enable the write bit when we're not waiting for continue */
2360 k->keepon |= KEEP_SEND;
2362 } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
2363 } /* if(k->getheader || !data->set.opt_no_body) */