1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, 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.
22 ***************************************************************************/
26 /* -- WIN32 approved -- */
34 #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>
67 #ifdef HAVE_SYS_PARAM_H
68 #include <sys/param.h>
71 #ifdef HAVE_SYS_SELECT_H
72 #include <sys/select.h>
76 #error "We can't compile without socket() support!"
82 #include <curl/curl.h>
85 #include "content_encoding.h"
89 #include "speedcheck.h"
95 #include "http_digest.h"
96 #include "http_ntlm.h"
97 #include "http_negotiate.h"
102 #include "easyif.h" /* for Curl_convert_to_network prototype */
104 #define _MPRINTF_REPLACE /* use our functions only */
105 #include <curl/mprintf.h>
107 /* The last #include file should be: */
108 #include "memdebug.h"
110 #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
113 static CURLcode readwrite_headers(struct SessionHandle *data,
114 struct connectdata *conn,
115 struct SingleRequest *k,
120 * This function will call the read callback to fill our buffer with data
123 CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
125 struct SessionHandle *data = conn->data;
126 size_t buffersize = (size_t)bytes;
129 if(data->req.upload_chunky) {
130 /* if chunked Transfer-Encoding */
131 buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
132 data->req.upload_fromhere += 10; /* 32bit hex + CRLF */
135 /* this function returns a size_t, so we typecast to int to prevent warnings
136 with picky compilers */
137 nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
138 buffersize, conn->fread_in);
140 if(nread == CURL_READFUNC_ABORT) {
141 failf(data, "operation aborted by callback");
143 return CURLE_ABORTED_BY_CALLBACK;
145 else if(nread == CURL_READFUNC_PAUSE) {
146 struct SingleRequest *k = &data->req;
147 /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
148 k->keepon |= KEEP_WRITE_PAUSE; /* mark socket send as paused */
150 return CURLE_OK; /* nothing was read */
152 else if((size_t)nread > buffersize) {
153 /* the read function returned a too large value */
155 return CURLE_READ_ERROR;
158 if(!data->req.forbidchunk && data->req.upload_chunky) {
159 /* if chunked Transfer-Encoding */
161 int hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
163 /* move buffer pointer */
164 data->req.upload_fromhere -= hexlen;
167 /* copy the prefix to the buffer */
168 memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
170 /* always append CRLF to the data */
171 memcpy(data->req.upload_fromhere + nread, "\r\n", 2);
173 if((nread - hexlen) == 0) {
174 /* mark this as done once this chunk is transfered */
175 data->req.upload_done = TRUE;
178 nread+=2; /* for the added CRLF */
183 #ifdef CURL_DOES_CONVERSIONS
184 if(data->set.prefer_ascii) {
186 res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
187 /* Curl_convert_to_network calls failf if unsuccessful */
188 if(res != CURLE_OK) {
192 #endif /* CURL_DOES_CONVERSIONS */
200 * Returns TRUE if member of the list matches prefix of string
203 checkhttpprefix(struct SessionHandle *data,
206 struct curl_slist *head = data->set.http200aliases;
208 #ifdef CURL_DOES_CONVERSIONS
209 /* convert from the network encoding using a scratch area */
210 char *scratch = calloc(1, strlen(s)+1);
211 if(NULL == scratch) {
212 failf (data, "Failed to calloc memory for conversion!");
213 return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
216 if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
217 /* Curl_convert_from_network calls failf if unsuccessful */
219 return FALSE; /* can't return CURLE_foobar so return FALSE */
222 #endif /* CURL_DOES_CONVERSIONS */
225 if(checkprefix(head->data, s)) {
232 if((rc != TRUE) && (checkprefix("HTTP/", s))) {
236 #ifdef CURL_DOES_CONVERSIONS
238 #endif /* CURL_DOES_CONVERSIONS */
243 * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
244 * POST/PUT with multi-pass authentication when a sending was denied and a
245 * resend is necessary.
247 CURLcode Curl_readrewind(struct connectdata *conn)
249 struct SessionHandle *data = conn->data;
251 conn->bits.rewindaftersend = FALSE; /* we rewind now */
253 /* explicitly switch off sending data on this connection now since we are
254 about to restart a new transfer and thus we want to avoid inadvertently
255 sending more data on the existing connection until the next transfer
257 data->req.keepon &= ~KEEP_WRITE;
259 /* We have sent away data. If not using CURLOPT_POSTFIELDS or
260 CURLOPT_HTTPPOST, call app to rewind
262 if(data->set.postfields ||
263 (data->set.httpreq == HTTPREQ_POST_FORM))
266 if(data->set.seek_func) {
269 err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
271 failf(data, "seek callback returned error %d", (int)err);
272 return CURLE_SEND_FAIL_REWIND;
275 else if(data->set.ioctl_func) {
278 err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
279 data->set.ioctl_client);
280 infof(data, "the ioctl callback returned %d\n", (int)err);
283 /* FIXME: convert to a human readable error message */
284 failf(data, "ioctl callback returned error %d", (int)err);
285 return CURLE_SEND_FAIL_REWIND;
289 /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
290 given FILE * stream and we can actually attempt to rewind that
291 ourself with fseek() */
292 if(data->set.fread_func == (curl_read_callback)fread) {
293 if(-1 != fseek(data->set.in, 0, SEEK_SET))
294 /* successful rewind */
298 /* no callback set or failure above, makes us fail at once */
299 failf(data, "necessary data rewind wasn't possible");
300 return CURLE_SEND_FAIL_REWIND;
306 static int data_pending(const struct connectdata *conn)
308 /* in the case of libssh2, we can never be really sure that we have emptied
309 its internal buffers so we MUST always try until we get EAGAIN back */
310 return conn->protocol&(PROT_SCP|PROT_SFTP) ||
311 Curl_ssl_data_pending(conn, FIRSTSOCKET);
315 #define MIN(a,b) (a < b ? a : b)
318 static void read_rewind(struct connectdata *conn,
321 conn->read_pos -= thismuch;
322 conn->bits.stream_was_rewound = TRUE;
329 show = MIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
330 if(conn->master_buffer) {
331 memcpy(buf, conn->master_buffer + conn->read_pos, show);
338 DEBUGF(infof(conn->data,
339 "Buffer after stream rewind (read_pos = %d): [%s]",
340 conn->read_pos, buf));
347 * Go ahead and do a read if we have a readable socket or if
348 * the stream was rewound (in which case we have data in a
351 static CURLcode readwrite_data(struct SessionHandle *data,
352 struct connectdata *conn,
353 struct SingleRequest *k,
354 int *didwhat, bool *done)
356 CURLcode result = CURLE_OK;
357 ssize_t nread; /* number of bytes read */
358 bool is_empty_data = FALSE;
360 /* This is where we loop until we have read everything there is to
361 read or we get a EWOULDBLOCK */
363 size_t buffersize = data->set.buffer_size?
364 data->set.buffer_size : BUFSIZE;
365 size_t bytestoread = buffersize;
368 if(k->size != -1 && !k->header) {
369 /* make sure we don't read "too much" if we can help it since we
370 might be pipelining and then someone else might want to read what
372 curl_off_t totalleft = k->size - k->bytecount;
373 if(totalleft < (curl_off_t)bytestoread)
374 bytestoread = (size_t)totalleft;
378 /* receive data from the network! */
379 readrc = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
381 /* subzero, this would've blocked */
383 break; /* get out of loop */
385 /* get the CURLcode from the int */
386 result = (CURLcode)readrc;
392 /* read nothing but since we wanted nothing we consider this an OK
393 situation to proceed from */
397 if((k->bytecount == 0) && (k->writebytecount == 0)) {
398 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
399 if(k->exp100 > EXP100_SEND_DATA)
400 /* set time stamp to compare with when waiting for the 100 */
401 k->start100 = Curl_tvnow();
404 *didwhat |= KEEP_READ;
405 /* indicates data of zero size, i.e. empty file */
406 is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
408 /* NUL terminate, allowing string ops to be used */
409 if(0 < nread || is_empty_data) {
412 else if(0 >= nread) {
413 /* if we receive 0 or less here, the server closed the connection
414 and we bail out from this! */
415 DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
416 k->keepon &= ~KEEP_READ;
420 /* Default buffer to use when we write the buffer, it may be changed
421 in the flow below before the actual storing is done. */
424 /* Since this is a two-state thing, we check if we are parsing
425 headers at the moment or not. */
427 /* we are in parse-the-header-mode */
428 bool stop_reading = FALSE;
429 result = readwrite_headers(data, conn, k, &nread, &stop_reading);
433 /* We've stopped dealing with input, get out of the do-while loop */
438 /* This is not an 'else if' since it may be a rest from the header
439 parsing, where the beginning of the buffer is headers and the end
441 if(k->str && !k->header && (nread > 0 || is_empty_data)) {
443 if(0 == k->bodywrites && !is_empty_data) {
444 /* These checks are only made the first time we are about to
445 write a piece of the body */
446 if(conn->protocol&PROT_HTTP) {
447 /* HTTP-only checks */
449 if(data->req.newurl) {
450 if(conn->bits.close) {
451 /* Abort after the headers if "follow Location" is set
452 and we're set to close anyway. */
453 k->keepon &= ~KEEP_READ;
457 /* We have a new url to load, but since we want to be able
458 to re-use this connection properly, we read the full
459 response in "ignore more" */
460 k->ignorebody = TRUE;
461 infof(data, "Ignoring the response-body\n");
463 if(data->state.resume_from && !k->content_range &&
464 (data->set.httpreq==HTTPREQ_GET) &&
466 /* we wanted to resume a download, although the server doesn't
467 * seem to support this and we did this with a GET (if it
468 * wasn't a GET we did a POST or PUT resume) */
469 failf(data, "HTTP server doesn't seem to support "
470 "byte ranges. Cannot resume.");
471 return CURLE_RANGE_ERROR;
474 if(data->set.timecondition && !data->state.range) {
475 /* A time condition has been set AND no ranges have been
476 requested. This seems to be what chapter 13.3.4 of
477 RFC 2616 defines to be the correct action for a
479 if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
480 switch(data->set.timecondition) {
481 case CURL_TIMECOND_IFMODSINCE:
483 if(k->timeofdoc < data->set.timevalue) {
485 "The requested document is not new enough\n");
490 case CURL_TIMECOND_IFUNMODSINCE:
491 if(k->timeofdoc > data->set.timevalue) {
493 "The requested document is not old enough\n");
499 } /* two valid time strings */
500 } /* we have a time condition */
503 } /* this is the first time we write a body part */
506 /* pass data to the debug function before it gets "dechunked" */
507 if(data->set.verbose) {
509 Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
510 (size_t)k->hbuflen, conn);
511 if(k->badheader == HEADER_PARTHEADER)
512 Curl_debug(data, CURLINFO_DATA_IN,
513 k->str, (size_t)nread, conn);
516 Curl_debug(data, CURLINFO_DATA_IN,
517 k->str, (size_t)nread, conn);
520 #ifndef CURL_DISABLE_HTTP
523 * Here comes a chunked transfer flying and we need to decode this
524 * properly. While the name says read, this function both reads
525 * and writes away the data. The returned 'nread' holds the number
526 * of actual data it wrote to the client.
530 Curl_httpchunk_read(conn, k->str, nread, &nread);
532 if(CHUNKE_OK < res) {
533 if(CHUNKE_WRITE_ERROR == res) {
534 failf(data, "Failed writing data");
535 return CURLE_WRITE_ERROR;
537 failf(data, "Received problem %d in the chunky parser", res);
538 return CURLE_RECV_ERROR;
540 else if(CHUNKE_STOP == res) {
542 /* we're done reading chunks! */
543 k->keepon &= ~KEEP_READ; /* read no more */
545 /* There are now possibly N number of bytes at the end of the
546 str buffer that weren't written to the client.
548 We DO care about this data if we are pipelining.
549 Push it back to be read on the next pass. */
551 dataleft = conn->chunk.dataleft;
553 infof(conn->data, "Leftovers after chunking. "
554 " Rewinding %d bytes\n",dataleft);
555 read_rewind(conn, dataleft);
558 /* If it returned OK, we just keep going */
560 #endif /* CURL_DISABLE_HTTP */
562 if((-1 != k->maxdownload) &&
563 (k->bytecount + nread >= k->maxdownload)) {
564 /* The 'excess' amount below can't be more than BUFSIZE which
565 always will fit in a size_t */
566 size_t excess = (size_t)(k->bytecount + nread - k->maxdownload);
567 if(excess > 0 && !k->ignorebody) {
569 "Rewinding stream by : %d"
570 " bytes on url %s (size = %" FORMAT_OFF_T
571 ", maxdownload = %" FORMAT_OFF_T
572 ", bytecount = %" FORMAT_OFF_T ", nread = %d)\n",
573 excess, data->state.path,
574 k->size, k->maxdownload, k->bytecount, nread);
575 read_rewind(conn, excess);
578 nread = (ssize_t) (k->maxdownload - k->bytecount);
579 if(nread < 0 ) /* this should be unusual */
582 k->keepon &= ~KEEP_READ; /* we're done reading */
585 k->bytecount += nread;
587 Curl_pgrsSetDownloadCounter(data, k->bytecount);
589 if(!k->chunk && (nread || k->badheader || is_empty_data)) {
590 /* If this is chunky transfer, it was already written */
592 if(k->badheader && !k->ignorebody) {
593 /* we parsed a piece of data wrongly assuming it was a header
594 and now we output it as body instead */
595 result = Curl_client_write(conn, CLIENTWRITE_BODY,
596 data->state.headerbuff,
601 if(k->badheader < HEADER_ALLBAD) {
602 /* This switch handles various content encodings. If there's an
603 error here, be sure to check over the almost identical code
605 Make sure that ALL_CONTENT_ENCODINGS contains all the
606 encodings handled here. */
608 switch (conn->data->set.http_ce_skip ?
609 IDENTITY : k->content_encoding) {
612 /* This is the default when the server sends no
613 Content-Encoding header. See Curl_readwrite_init; the
614 memset() call initializes k->content_encoding to zero. */
616 result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
622 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
624 result = Curl_unencode_deflate_write(conn, k, nread);
628 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
630 result = Curl_unencode_gzip_write(conn, k, nread);
635 failf (data, "Unrecognized content encoding type. "
636 "libcurl understands `identity', `deflate' and `gzip' "
637 "content encodings.");
638 result = CURLE_BAD_CONTENT_ENCODING;
643 k->badheader = HEADER_NORMAL; /* taken care of now */
649 } /* if(! header and data to read ) */
652 /* if we received nothing, the server closed the connection and we
654 k->keepon &= ~KEEP_READ;
657 } while(data_pending(conn));
663 * Read any header lines from the server and pass them to the client app.
665 static CURLcode readwrite_headers(struct SessionHandle *data,
666 struct connectdata *conn,
667 struct SingleRequest *k,
673 /* header line within buffer loop */
680 /* str_start is start of line within buf */
681 k->str_start = k->str;
683 /* data is in network encoding so use 0x0a instead of '\n' */
684 k->end_ptr = memchr(k->str_start, 0x0a, *nread);
687 /* Not a complete header line within buffer, append the data to
688 the end of the headerbuff. */
690 if(k->hbuflen + *nread >= data->state.headersize) {
691 /* We enlarge the header buffer as it is too small */
693 size_t newsize=CURLMAX((k->hbuflen+*nread)*3/2,
694 data->state.headersize*2);
695 hbufp_index = k->hbufp - data->state.headerbuff;
696 newbuff = (char *)realloc(data->state.headerbuff, newsize);
698 failf (data, "Failed to alloc memory for big header!");
699 return CURLE_OUT_OF_MEMORY;
701 data->state.headersize=newsize;
702 data->state.headerbuff = newbuff;
703 k->hbufp = data->state.headerbuff + hbufp_index;
705 memcpy(k->hbufp, k->str, *nread);
707 k->hbuflen += *nread;
708 if(!k->headerline && (k->hbuflen>5)) {
709 /* make a first check that this looks like a HTTP header */
710 if(!checkhttpprefix(data, data->state.headerbuff)) {
711 /* this is not the beginning of a HTTP first header line */
713 k->badheader = HEADER_ALLBAD;
718 break; /* read more and try again */
721 /* decrease the size of the remaining (supposed) header line */
722 rest_length = (k->end_ptr - k->str)+1;
723 *nread -= (ssize_t)rest_length;
725 k->str = k->end_ptr + 1; /* move past new line */
727 full_length = k->str - k->str_start;
730 * We're about to copy a chunk of data to the end of the
731 * already received header. We make sure that the full string
732 * fit in the allocated header buffer, or else we enlarge
735 if(k->hbuflen + full_length >=
736 data->state.headersize) {
738 size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
739 data->state.headersize*2);
740 hbufp_index = k->hbufp - data->state.headerbuff;
741 newbuff = (char *)realloc(data->state.headerbuff, newsize);
743 failf (data, "Failed to alloc memory for big header!");
744 return CURLE_OUT_OF_MEMORY;
746 data->state.headersize= newsize;
747 data->state.headerbuff = newbuff;
748 k->hbufp = data->state.headerbuff + hbufp_index;
751 /* copy to end of line */
752 memcpy(k->hbufp, k->str_start, full_length);
753 k->hbufp += full_length;
754 k->hbuflen += full_length;
756 k->end_ptr = k->hbufp;
758 k->p = data->state.headerbuff;
761 * We now have a FULL header line that p points to
765 /* the first read header */
767 !checkhttpprefix(data, data->state.headerbuff)) {
768 /* this is not the beginning of a HTTP first header line */
771 /* since there's more, this is a partial bad header */
772 k->badheader = HEADER_PARTHEADER;
774 /* this was all we read so it's all a bad header */
775 k->badheader = HEADER_ALLBAD;
776 *nread = (ssize_t)rest_length;
782 /* headers are in network encoding so
783 use 0x0a and 0x0d instead of '\n' and '\r' */
784 if((0x0a == *k->p) || (0x0d == *k->p)) {
786 /* Zero-length header line means end of headers! */
788 #ifdef CURL_DOES_CONVERSIONS
790 *k->p = '\r'; /* replace with CR in host encoding */
791 k->p++; /* pass the CR byte */
794 *k->p = '\n'; /* replace with LF in host encoding */
795 k->p++; /* pass the LF byte */
799 k->p++; /* pass the \r byte */
801 k->p++; /* pass the \n byte */
802 #endif /* CURL_DOES_CONVERSIONS */
804 #ifndef CURL_DISABLE_HTTP
805 if(100 <= k->httpcode && 199 >= k->httpcode) {
807 * We have made a HTTP PUT or POST and this is 1.1-lingo
808 * that tells us that the server is OK with this and ready
809 * to receive the data.
810 * However, we'll get more headers now so we must get
811 * back into the header-parsing state!
814 k->headerline = 0; /* restart the header line counter */
816 /* if we did wait for this do enable write now! */
818 k->exp100 = EXP100_SEND_DATA;
819 k->keepon |= KEEP_WRITE;
823 k->header = FALSE; /* no more header to parse! */
825 if((k->size == -1) && !k->chunk && !conn->bits.close &&
826 (k->httpversion >= 11) ) {
827 /* On HTTP 1.1, when connection is not to get closed, but no
828 Content-Length nor Content-Encoding chunked have been
829 received, according to RFC2616 section 4.4 point 5, we
830 assume that the server will close the connection to
831 signal the end of the document. */
832 infof(data, "no chunk, no close, no size. Assume close to "
834 conn->bits.close = TRUE;
838 if(417 == k->httpcode) {
840 * we got: "417 Expectation Failed" this means:
841 * we have made a HTTP call and our Expect Header
842 * seems to cause a problem => abort the write operations
843 * (or prevent them from starting).
845 k->exp100 = EXP100_FAILED;
846 k->keepon &= ~KEEP_WRITE;
850 * When all the headers have been parsed, see if we should give
851 * up and return an error.
853 if(Curl_http_should_fail(conn)) {
854 failf (data, "The requested URL returned error: %d",
856 return CURLE_HTTP_RETURNED_ERROR;
858 #endif /* CURL_DISABLE_HTTP */
860 /* now, only output this if the header AND body are requested:
862 writetype = CLIENTWRITE_HEADER;
863 if(data->set.include_header)
864 writetype |= CLIENTWRITE_BODY;
866 headerlen = k->p - data->state.headerbuff;
868 result = Curl_client_write(conn, writetype,
869 data->state.headerbuff,
874 data->info.header_size += (long)headerlen;
875 data->req.headerbytecount += (long)headerlen;
877 data->req.deductheadercount =
878 (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
880 if(data->state.resume_from &&
881 (data->set.httpreq==HTTPREQ_GET) &&
882 (k->httpcode == 416)) {
883 /* "Requested Range Not Satisfiable" */
884 *stop_reading = TRUE;
887 #ifndef CURL_DISABLE_HTTP
889 /* Curl_http_auth_act() checks what authentication methods
890 * that are available and decides which one (if any) to
891 * use. It will set 'newurl' if an auth method was picked. */
892 result = Curl_http_auth_act(conn);
897 if(conn->bits.rewindaftersend) {
898 /* We rewind after a complete send, so thus we continue
900 infof(data, "Keep sending data to get tossed away!\n");
901 k->keepon |= KEEP_WRITE;
904 #endif /* CURL_DISABLE_HTTP */
908 * really end-of-headers.
910 * If we requested a "no body", this is a good time to get
911 * out and return home.
913 if(data->set.opt_no_body)
914 *stop_reading = TRUE;
916 /* If we know the expected size of this document, we set the
917 maximum download size to the size of the expected
918 document or else, we won't know when to stop reading!
920 Note that we set the download maximum even if we read a
921 "Connection: close" header, to make sure that
922 "Content-Length: 0" still prevents us from attempting to
923 read the (missing) response-body.
925 /* According to RFC2616 section 4.4, we MUST ignore
926 Content-Length: headers if we are now receiving data
927 using chunked Transfer-Encoding.
934 /* We do this operation even if no_body is true, since this
935 data might be retrieved later with curl_easy_getinfo()
936 and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
938 Curl_pgrsSetDownloadSize(data, k->size);
939 k->maxdownload = k->size;
941 /* If max download size is *zero* (nothing) we already
942 have nothing and can safely return ok now! */
943 if(0 == k->maxdownload)
944 *stop_reading = TRUE;
947 /* we make sure that this socket isn't read more now */
948 k->keepon &= ~KEEP_READ;
951 if(data->set.verbose)
952 Curl_debug(data, CURLINFO_HEADER_IN,
953 k->str_start, headerlen, conn);
954 break; /* exit header line loop */
957 /* We continue reading headers, so reset the line-based
958 header parsing variables hbufp && hbuflen */
959 k->hbufp = data->state.headerbuff;
964 #ifndef CURL_DISABLE_HTTP
966 * Checks for special headers coming up.
969 if(!k->headerline++) {
970 /* This is the first header, it MUST be the error code line
971 or else we consider this to be the body right away! */
972 int httpversion_major;
974 #ifdef CURL_DOES_CONVERSIONS
975 #define HEADER1 scratch
976 #define SCRATCHSIZE 21
978 char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
979 /* We can't really convert this yet because we
980 don't know if it's the 1st header line or the body.
981 So we do a partial conversion into a scratch area,
982 leaving the data at k->p as-is.
984 strncpy(&scratch[0], k->p, SCRATCHSIZE);
985 scratch[SCRATCHSIZE] = 0; /* null terminate */
986 res = Curl_convert_from_network(data,
989 if(CURLE_OK != res) {
990 /* Curl_convert_from_network calls failf if unsuccessful */
994 #define HEADER1 k->p /* no conversion needed, just use k->p */
995 #endif /* CURL_DOES_CONVERSIONS */
1003 k->httpversion += 10 * httpversion_major;
1006 /* this is the real world, not a Nirvana
1007 NCSA 1.5.x returns this crap when asked for HTTP/1.1
1009 nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
1010 k->httpversion = 10;
1012 /* If user has set option HTTP200ALIASES,
1013 compare header line against list of aliases
1016 if(checkhttpprefix(data, k->p)) {
1019 k->httpversion = 10;
1025 data->info.httpcode = k->httpcode;
1026 data->info.httpversion = k->httpversion;
1029 * This code executes as part of processing the header. As a
1030 * result, it's not totally clear how to interpret the
1031 * response code yet as that depends on what other headers may
1032 * be present. 401 and 407 may be errors, but may be OK
1033 * depending on how authentication is working. Other codes
1034 * are definitely errors, so give up here.
1036 if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
1037 ((k->httpcode != 401) || !conn->bits.user_passwd) &&
1038 ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
1040 if(data->state.resume_from &&
1041 (data->set.httpreq==HTTPREQ_GET) &&
1042 (k->httpcode == 416)) {
1043 /* "Requested Range Not Satisfiable", just proceed and
1044 pretend this is no error */
1047 /* serious error, go home! */
1048 failf (data, "The requested URL returned error: %d",
1050 return CURLE_HTTP_RETURNED_ERROR;
1054 if(k->httpversion == 10) {
1055 /* Default action for HTTP/1.0 must be to close, unless
1056 we get one of those fancy headers that tell us the
1057 server keeps it open for us! */
1058 infof(data, "HTTP 1.0, assume close after body\n");
1059 conn->bits.close = TRUE;
1061 else if(k->httpversion >= 11 &&
1062 !conn->bits.close) {
1063 /* If HTTP version is >= 1.1 and connection is persistent
1064 server supports pipelining. */
1066 "HTTP 1.1 or later with persistent connection, "
1067 "pipelining supported\n"));
1068 conn->server_supports_pipelining = TRUE;
1071 switch(k->httpcode) {
1073 /* (quote from RFC2616, section 10.2.5): The server has
1074 * fulfilled the request but does not need to return an
1075 * entity-body ... The 204 response MUST NOT include a
1076 * message-body, and thus is always terminated by the first
1077 * empty line after the header fields. */
1079 case 416: /* Requested Range Not Satisfiable, it has the
1080 Content-Length: set as the "real" document but no
1081 actual response is sent. */
1083 /* (quote from RFC2616, section 10.3.5): The 304 response
1084 * MUST NOT contain a message-body, and thus is always
1085 * terminated by the first empty line after the header
1089 k->ignorecl = TRUE; /* ignore Content-Length headers */
1097 k->header = FALSE; /* this is not a header line */
1101 #endif /* CURL_DISABLE_HTTP */
1103 #ifdef CURL_DOES_CONVERSIONS
1104 /* convert from the network encoding */
1105 result = Curl_convert_from_network(data, k->p, strlen(k->p));
1106 if(CURLE_OK != result) {
1109 /* Curl_convert_from_network calls failf if unsuccessful */
1110 #endif /* CURL_DOES_CONVERSIONS */
1112 #ifndef CURL_DISABLE_HTTP
1113 /* Check for Content-Length: header lines to get size. Ignore
1114 the header completely if we get a 416 response as then we're
1115 resuming a document that we don't get, and this header contains
1116 info about the true size of the document we didn't get now. */
1117 if(!k->ignorecl && !data->set.ignorecl &&
1118 checkprefix("Content-Length:", k->p)) {
1119 curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
1120 if(data->set.max_filesize &&
1121 contentlength > data->set.max_filesize) {
1122 failf(data, "Maximum file size exceeded");
1123 return CURLE_FILESIZE_EXCEEDED;
1125 if(contentlength >= 0) {
1126 k->size = contentlength;
1127 k->maxdownload = k->size;
1128 /* we set the progress download size already at this point
1129 just to make it easier for apps/callbacks to extract this
1130 info as soon as possible */
1131 Curl_pgrsSetDownloadSize(data, k->size);
1134 /* Negative Content-Length is really odd, and we know it
1135 happens for example when older Apache servers send large
1137 conn->bits.close = TRUE;
1138 infof(data, "Negative content-length: %" FORMAT_OFF_T
1139 ", closing after transfer\n", contentlength);
1142 /* check for Content-Type: header lines to get the MIME-type */
1143 else if(checkprefix("Content-Type:", k->p)) {
1144 char *contenttype = Curl_copy_header_value(k->p);
1146 return CURLE_OUT_OF_MEMORY;
1148 /* ignore empty data */
1151 Curl_safefree(data->info.contenttype);
1152 data->info.contenttype = contenttype;
1155 else if((k->httpversion == 10) &&
1156 conn->bits.httpproxy &&
1157 Curl_compareheader(k->p,
1158 "Proxy-Connection:", "keep-alive")) {
1160 * When a HTTP/1.0 reply comes when using a proxy, the
1161 * 'Proxy-Connection: keep-alive' line tells us the
1162 * connection will be kept alive for our pleasure.
1163 * Default action for 1.0 is to close.
1165 conn->bits.close = FALSE; /* don't close when done */
1166 infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
1168 else if((k->httpversion == 11) &&
1169 conn->bits.httpproxy &&
1170 Curl_compareheader(k->p,
1171 "Proxy-Connection:", "close")) {
1173 * We get a HTTP/1.1 response from a proxy and it says it'll
1174 * close down after this transfer.
1176 conn->bits.close = TRUE; /* close when done */
1177 infof(data, "HTTP/1.1 proxy connection set close!\n");
1179 else if((k->httpversion == 10) &&
1180 Curl_compareheader(k->p, "Connection:", "keep-alive")) {
1182 * A HTTP/1.0 reply with the 'Connection: keep-alive' line
1183 * tells us the connection will be kept alive for our
1184 * pleasure. Default action for 1.0 is to close.
1186 * [RFC2068, section 19.7.1] */
1187 conn->bits.close = FALSE; /* don't close when done */
1188 infof(data, "HTTP/1.0 connection set to keep alive!\n");
1190 else if(Curl_compareheader(k->p, "Connection:", "close")) {
1192 * [RFC 2616, section 8.1.2.1]
1193 * "Connection: close" is HTTP/1.1 language and means that
1194 * the connection will close when this request has been
1197 conn->bits.close = TRUE; /* close when done */
1199 else if(Curl_compareheader(k->p,
1200 "Transfer-Encoding:", "chunked")) {
1202 * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
1203 * means that the server will send a series of "chunks". Each
1204 * chunk starts with line with info (including size of the
1205 * coming block) (terminated with CRLF), then a block of data
1206 * with the previously mentioned size. There can be any amount
1207 * of chunks, and a chunk-data set to zero signals the
1209 k->chunk = TRUE; /* chunks coming our way */
1211 /* init our chunky engine */
1212 Curl_httpchunk_init(conn);
1215 else if(checkprefix("Trailer:", k->p) ||
1216 checkprefix("Trailers:", k->p)) {
1218 * This test helps Curl_httpchunk_read() to determine to look
1219 * for well formed trailers after the zero chunksize record. In
1220 * this case a CRLF is required after the zero chunksize record
1221 * when no trailers are sent, or after the last trailer record.
1223 * It seems both Trailer: and Trailers: occur in the wild.
1225 k->trailerhdrpresent = TRUE;
1228 else if(checkprefix("Content-Encoding:", k->p) &&
1229 data->set.str[STRING_ENCODING]) {
1231 * Process Content-Encoding. Look for the values: identity,
1232 * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
1233 * x-compress are the same as gzip and compress. (Sec 3.5 RFC
1234 * 2616). zlib cannot handle compress. However, errors are
1235 * handled further down when the response body is processed
1239 /* Find the first non-space letter */
1241 *start && ISSPACE(*start);
1245 /* Record the content-encoding for later use */
1246 if(checkprefix("identity", start))
1247 k->content_encoding = IDENTITY;
1248 else if(checkprefix("deflate", start))
1249 k->content_encoding = DEFLATE;
1250 else if(checkprefix("gzip", start)
1251 || checkprefix("x-gzip", start))
1252 k->content_encoding = GZIP;
1253 else if(checkprefix("compress", start)
1254 || checkprefix("x-compress", start))
1255 k->content_encoding = COMPRESS;
1257 else if(checkprefix("Content-Range:", k->p)) {
1258 /* Content-Range: bytes [num]-
1259 Content-Range: bytes: [num]-
1260 Content-Range: [num]-
1262 The second format was added since Sun's webserver
1263 JavaWebServer/1.1.1 obviously sends the header this way!
1264 The third added since some servers use that!
1267 char *ptr = k->p + 14;
1269 /* Move forward until first digit */
1270 while(*ptr && !ISDIGIT(*ptr))
1273 k->offset = curlx_strtoofft(ptr, NULL, 10);
1275 if(data->state.resume_from == k->offset)
1276 /* we asked for a resume and we got it */
1277 k->content_range = TRUE;
1279 #if !defined(CURL_DISABLE_COOKIES)
1280 else if(data->cookies &&
1281 checkprefix("Set-Cookie:", k->p)) {
1282 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
1283 CURL_LOCK_ACCESS_SINGLE);
1284 Curl_cookie_add(data,
1285 data->cookies, TRUE, k->p+11,
1286 /* If there is a custom-set Host: name, use it
1287 here, or else use real peer host name. */
1288 conn->allocptr.cookiehost?
1289 conn->allocptr.cookiehost:conn->host.name,
1291 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1294 else if(checkprefix("Last-Modified:", k->p) &&
1295 (data->set.timecondition || data->set.get_filetime) ) {
1296 time_t secs=time(NULL);
1297 k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
1299 if(data->set.get_filetime)
1300 data->info.filetime = (long)k->timeofdoc;
1302 else if((checkprefix("WWW-Authenticate:", k->p) &&
1303 (401 == k->httpcode)) ||
1304 (checkprefix("Proxy-authenticate:", k->p) &&
1305 (407 == k->httpcode))) {
1306 result = Curl_http_input_auth(conn, k->httpcode, k->p);
1310 else if((k->httpcode >= 300 && k->httpcode < 400) &&
1311 checkprefix("Location:", k->p)) {
1312 /* this is the URL that the server advises us to use instead */
1313 char *location = Curl_copy_header_value(k->p);
1315 return CURLE_OUT_OF_MEMORY;
1317 /* ignore empty data */
1320 DEBUGASSERT(!data->req.location);
1321 data->req.location = location;
1323 if(data->set.http_follow_location) {
1324 DEBUGASSERT(!data->req.newurl);
1325 data->req.newurl = strdup(data->req.location); /* clone */
1326 if(!data->req.newurl)
1327 return CURLE_OUT_OF_MEMORY;
1329 /* some cases of POST and PUT etc needs to rewind the data
1330 stream at this point */
1331 result = Curl_http_perhapsrewind(conn);
1337 #endif /* CURL_DISABLE_HTTP */
1340 * End of header-checks. Write them to the client.
1343 writetype = CLIENTWRITE_HEADER;
1344 if(data->set.include_header)
1345 writetype |= CLIENTWRITE_BODY;
1347 if(data->set.verbose)
1348 Curl_debug(data, CURLINFO_HEADER_IN,
1349 k->p, (size_t)k->hbuflen, conn);
1351 result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
1355 data->info.header_size += (long)k->hbuflen;
1356 data->req.headerbytecount += (long)k->hbuflen;
1358 /* reset hbufp pointer && hbuflen */
1359 k->hbufp = data->state.headerbuff;
1362 while(!*stop_reading && *k->str); /* header line within buffer */
1364 /* We might have reached the end of the header part here, but
1365 there might be a non-header part left in the end of the read
1372 * Send data to upload to the server, when the socket is writable.
1374 static CURLcode readwrite_upload(struct SessionHandle *data,
1375 struct connectdata *conn,
1376 struct SingleRequest *k,
1380 ssize_t bytes_written;
1382 ssize_t nread; /* number of bytes read */
1384 if((k->bytecount == 0) && (k->writebytecount == 0))
1385 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
1387 *didwhat |= KEEP_WRITE;
1390 * We loop here to do the READ and SEND loop until we run out of
1391 * data to send or until we get EWOULDBLOCK back
1395 /* only read more data if there's no upload data already
1396 present in the upload buffer */
1397 if(0 == data->req.upload_present) {
1398 /* init the "upload from here" pointer */
1399 data->req.upload_fromhere = k->uploadbuf;
1401 if(!k->upload_done) {
1402 /* HTTP pollution, this should be written nicer to become more
1403 protocol agnostic. */
1406 if((k->exp100 == EXP100_SENDING_REQUEST) &&
1407 (data->state.proto.http->sending == HTTPSEND_BODY)) {
1408 /* If this call is to send body data, we must take some action:
1409 We have sent off the full HTTP 1.1 request, and we shall now
1410 go into the Expect: 100 state and await such a header */
1411 k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
1412 k->keepon &= ~KEEP_WRITE; /* disable writing */
1413 k->start100 = Curl_tvnow(); /* timeout count starts now */
1414 *didwhat &= ~KEEP_WRITE; /* we didn't write anything actually */
1418 result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
1422 nread = (ssize_t)fillcount;
1425 nread = 0; /* we're done uploading/reading */
1427 if(!nread && (k->keepon & KEEP_WRITE_PAUSE)) {
1428 /* this is a paused transfer */
1433 k->keepon &= ~KEEP_WRITE; /* we're done writing */
1435 if(conn->bits.rewindaftersend) {
1436 result = Curl_readrewind(conn);
1443 /* store number of bytes available for upload */
1444 data->req.upload_present = nread;
1446 /* convert LF to CRLF if so asked */
1447 #ifdef CURL_DO_LINEEND_CONV
1448 /* always convert if we're FTPing in ASCII mode */
1449 if((data->set.crlf) || (data->set.prefer_ascii))
1452 #endif /* CURL_DO_LINEEND_CONV */
1454 if(data->state.scratch == NULL)
1455 data->state.scratch = malloc(2*BUFSIZE);
1456 if(data->state.scratch == NULL) {
1457 failf (data, "Failed to alloc scratch buffer!");
1458 return CURLE_OUT_OF_MEMORY;
1461 * ASCII/EBCDIC Note: This is presumably a text (not binary)
1462 * transfer so the data should already be in ASCII.
1463 * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
1464 * must be used instead of the escape sequences \r & \n.
1466 for(i = 0, si = 0; i < nread; i++, si++) {
1467 if(data->req.upload_fromhere[i] == 0x0a) {
1468 data->state.scratch[si++] = 0x0d;
1469 data->state.scratch[si] = 0x0a;
1470 if(!data->set.crlf) {
1471 /* we're here only because FTP is in ASCII mode...
1472 bump infilesize for the LF we just added */
1473 data->set.infilesize++;
1477 data->state.scratch[si] = data->req.upload_fromhere[i];
1480 /* only perform the special operation if we really did replace
1484 /* upload from the new (replaced) buffer instead */
1485 data->req.upload_fromhere = data->state.scratch;
1487 /* set the new amount too */
1488 data->req.upload_present = nread;
1491 } /* if 0 == data->req.upload_present */
1493 /* We have a partial buffer left from a previous "round". Use
1494 that instead of reading more data */
1497 /* write to socket (send away data) */
1498 result = Curl_write(conn,
1499 conn->writesockfd, /* socket to send to */
1500 data->req.upload_fromhere, /* buffer pointer */
1501 data->req.upload_present, /* buffer size */
1502 &bytes_written); /* actually send away */
1506 if(data->set.verbose)
1507 /* show the data before we change the pointer upload_fromhere */
1508 Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
1509 (size_t)bytes_written, conn);
1511 if(data->req.upload_present != bytes_written) {
1512 /* we only wrote a part of the buffer (if anything), deal with it! */
1514 /* store the amount of bytes left in the buffer to write */
1515 data->req.upload_present -= bytes_written;
1517 /* advance the pointer where to find the buffer when the next send
1519 data->req.upload_fromhere += bytes_written;
1522 /* we've uploaded that buffer now */
1523 data->req.upload_fromhere = k->uploadbuf;
1524 data->req.upload_present = 0; /* no more bytes left */
1526 if(k->upload_done) {
1527 /* switch off writing, we're done! */
1528 k->keepon &= ~KEEP_WRITE; /* we're done writing */
1532 k->writebytecount += bytes_written;
1533 Curl_pgrsSetUploadCounter(data, k->writebytecount);
1535 } while(0); /* just to break out from! */
1541 * Curl_readwrite() is the low-level function to be called when data is to
1542 * be read and written to/from the connection.
1544 CURLcode Curl_readwrite(struct connectdata *conn,
1547 struct SessionHandle *data = conn->data;
1548 struct SingleRequest *k = &data->req;
1552 curl_socket_t fd_read;
1553 curl_socket_t fd_write;
1554 int select_res = conn->cselect_bits;
1556 conn->cselect_bits = 0;
1558 /* only use the proper socket if the *_HOLD bit is not set simultaneously as
1559 then we are in rate limiting state in that transfer direction */
1561 if((k->keepon & KEEP_READBITS) == KEEP_READ) {
1562 fd_read = conn->sockfd;
1563 #if defined(USE_LIBSSH2)
1564 if(conn->protocol & (PROT_SCP|PROT_SFTP))
1565 select_res |= CURL_CSELECT_IN;
1566 #endif /* USE_LIBSSH2 */
1568 fd_read = CURL_SOCKET_BAD;
1570 if((k->keepon & KEEP_WRITEBITS) == KEEP_WRITE)
1571 fd_write = conn->writesockfd;
1573 fd_write = CURL_SOCKET_BAD;
1575 if(!select_res) { /* Call for select()/poll() only, if read/write/error
1576 status is not known. */
1577 select_res = Curl_socket_ready(fd_read, fd_write, 0);
1580 if(select_res == CURL_CSELECT_ERR) {
1581 failf(data, "select/poll returned error");
1582 return CURLE_SEND_ERROR;
1585 /* We go ahead and do a read if we have a readable socket or if
1586 the stream was rewound (in which case we have data in a
1588 if((k->keepon & KEEP_READ) &&
1589 ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
1591 result = readwrite_data(data, conn, k, &didwhat, done);
1596 /* If we still have writing to do, we check if we have a writable socket. */
1597 if((k->keepon & KEEP_WRITE) && (select_res & CURL_CSELECT_OUT)) {
1600 result = readwrite_upload(data, conn, k, &didwhat);
1605 k->now = Curl_tvnow();
1607 /* Update read/write counters */
1609 *k->bytecountp = k->bytecount; /* read count */
1610 if(k->writebytecountp)
1611 *k->writebytecountp = k->writebytecount; /* write count */
1614 /* no read no write, this is a timeout? */
1615 if(k->exp100 == EXP100_AWAITING_CONTINUE) {
1616 /* This should allow some time for the header to arrive, but only a
1617 very short time as otherwise it'll be too much wasted time too
1620 /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
1622 Therefore, when a client sends this header field to an origin server
1623 (possibly via a proxy) from which it has never seen a 100 (Continue)
1624 status, the client SHOULD NOT wait for an indefinite period before
1625 sending the request body.
1629 long ms = Curl_tvdiff(k->now, k->start100);
1630 if(ms > CURL_TIMEOUT_EXPECT_100) {
1631 /* we've waited long enough, continue anyway */
1632 k->exp100 = EXP100_SEND_DATA;
1633 k->keepon |= KEEP_WRITE;
1634 infof(data, "Done waiting for 100-continue\n");
1639 if(Curl_pgrsUpdate(conn))
1640 result = CURLE_ABORTED_BY_CALLBACK;
1642 result = Curl_speedcheck(data, k->now);
1646 if(data->set.timeout &&
1647 (Curl_tvdiff(k->now, k->start) >= data->set.timeout)) {
1649 failf(data, "Operation timed out after %ld milliseconds with %"
1650 FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes received",
1651 data->set.timeout, k->bytecount, k->size);
1653 failf(data, "Operation timed out after %ld milliseconds with %"
1654 FORMAT_OFF_T " bytes received",
1655 data->set.timeout, k->bytecount);
1657 return CURLE_OPERATION_TIMEDOUT;
1662 * The transfer has been performed. Just make some general checks before
1666 if(!(data->set.opt_no_body) && (k->size != -1) &&
1667 (k->bytecount != k->size) &&
1668 #ifdef CURL_DO_LINEEND_CONV
1669 /* Most FTP servers don't adjust their file SIZE response for CRLFs,
1670 so we'll check to see if the discrepancy can be explained
1671 by the number of CRLFs we've changed to LFs.
1673 (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1674 #endif /* CURL_DO_LINEEND_CONV */
1675 !data->req.newurl) {
1676 failf(data, "transfer closed with %" FORMAT_OFF_T
1677 " bytes remaining to read",
1678 k->size - k->bytecount);
1679 return CURLE_PARTIAL_FILE;
1681 else if(!(data->set.opt_no_body) &&
1683 (conn->chunk.state != CHUNK_STOP)) {
1685 * In chunked mode, return an error if the connection is closed prior to
1686 * the empty (terminiating) chunk is read.
1688 * The condition above used to check for
1689 * conn->proto.http->chunk.datasize != 0 which is true after reading
1690 * *any* chunk, not just the empty chunk.
1693 failf(data, "transfer closed with outstanding read data remaining");
1694 return CURLE_PARTIAL_FILE;
1696 if(Curl_pgrsUpdate(conn))
1697 return CURLE_ABORTED_BY_CALLBACK;
1700 /* Now update the "done" boolean we return */
1701 *done = (bool)(0 == (k->keepon&(KEEP_READ|KEEP_WRITE|
1702 KEEP_READ_PAUSE|KEEP_WRITE_PAUSE)));
1708 * Curl_single_getsock() gets called by the multi interface code when the app
1709 * has requested to get the sockets for the current connection. This function
1710 * will then be called once for every connection that the multi interface
1711 * keeps track of. This function will only be called for connections that are
1712 * in the proper state to have this information available.
1714 int Curl_single_getsock(const struct connectdata *conn,
1715 curl_socket_t *sock, /* points to numsocks number
1719 const struct SessionHandle *data = conn->data;
1720 int bitmap = GETSOCK_BLANK;
1721 unsigned sockindex = 0;
1724 /* simple check but we might need two slots */
1725 return GETSOCK_BLANK;
1727 /* don't include HOLD and PAUSE connections */
1728 if((data->req.keepon & KEEP_READBITS) == KEEP_READ) {
1730 DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1732 bitmap |= GETSOCK_READSOCK(sockindex);
1733 sock[sockindex] = conn->sockfd;
1736 /* don't include HOLD and PAUSE connections */
1737 if((data->req.keepon & KEEP_WRITEBITS) == KEEP_WRITE) {
1739 if((conn->sockfd != conn->writesockfd) ||
1740 !(data->req.keepon & KEEP_READ)) {
1741 /* only if they are not the same socket or we didn't have a readable
1742 one, we increase index */
1743 if(data->req.keepon & KEEP_READ)
1744 sockindex++; /* increase index if we need two entries */
1746 DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1748 sock[sockindex] = conn->writesockfd;
1751 bitmap |= GETSOCK_WRITESOCK(sockindex);
1761 * This function is what performs the actual transfer. It is capable of
1762 * doing both ways simultaneously.
1763 * The transfer must already have been setup by a call to Curl_setup_transfer().
1765 * Note that headers are created in a preallocated buffer of a default size.
1766 * That buffer can be enlarged on demand, but it is never shrunken again.
1768 * Parts of this function was once written by the friendly Mark Butler
1769 * <butlerm@xmission.com>.
1773 Transfer(struct connectdata *conn)
1776 struct SessionHandle *data = conn->data;
1777 struct SingleRequest *k = &data->req;
1780 if((conn->sockfd == CURL_SOCKET_BAD) &&
1781 (conn->writesockfd == CURL_SOCKET_BAD))
1782 /* nothing to read, nothing to write, we're already OK! */
1785 /* we want header and/or body, if neither then don't do this! */
1786 if(!k->getheader && data->set.opt_no_body)
1790 curl_socket_t fd_read;
1791 curl_socket_t fd_write;
1793 /* limit-rate logic: if speed exceeds threshold, then do not include fd in
1794 select set. The current speed is recalculated in each Curl_readwrite()
1796 if((k->keepon & KEEP_WRITE) &&
1797 (!data->set.max_send_speed ||
1798 (data->progress.ulspeed < data->set.max_send_speed) )) {
1799 fd_write = conn->writesockfd;
1800 k->keepon &= ~KEEP_WRITE_HOLD;
1803 fd_write = CURL_SOCKET_BAD;
1804 if(k->keepon & KEEP_WRITE)
1805 k->keepon |= KEEP_WRITE_HOLD; /* hold it */
1808 if((k->keepon & KEEP_READ) &&
1809 (!data->set.max_recv_speed ||
1810 (data->progress.dlspeed < data->set.max_recv_speed)) ) {
1811 fd_read = conn->sockfd;
1812 k->keepon &= ~KEEP_READ_HOLD;
1815 fd_read = CURL_SOCKET_BAD;
1816 if(k->keepon & KEEP_READ)
1817 k->keepon |= KEEP_READ_HOLD; /* hold it */
1820 /* pause logic. Don't check descriptors for paused connections */
1821 if(k->keepon & KEEP_READ_PAUSE)
1822 fd_read = CURL_SOCKET_BAD;
1823 if(k->keepon & KEEP_WRITE_PAUSE)
1824 fd_write = CURL_SOCKET_BAD;
1826 /* The *_HOLD and *_PAUSE logic is necessary since even though there might
1827 be no traffic during the select interval, we still call
1828 Curl_readwrite() for the timeout case and if we limit transfer speed we
1829 must make sure that this function doesn't transfer anything while in
1832 switch (Curl_socket_ready(fd_read, fd_write, 1000)) {
1833 case -1: /* select() error, stop reading */
1835 /* The EINTR is not serious, and it seems you might get this more
1836 often when using the lib in a multi-threaded environment! */
1837 if(SOCKERRNO == EINTR)
1841 done = TRUE; /* no more read or write */
1843 case 0: /* timeout */
1844 default: /* readable descriptors */
1846 result = Curl_readwrite(conn, &done);
1852 /* "done" signals to us if the transfer(s) are ready */
1859 * Curl_pretransfer() is called immediately before a transfer starts.
1861 CURLcode Curl_pretransfer(struct SessionHandle *data)
1864 if(!data->change.url) {
1865 /* we can't do anything without URL */
1866 failf(data, "No URL set!");
1867 return CURLE_URL_MALFORMAT;
1870 /* Init the SSL session ID cache here. We do it here since we want to do it
1871 after the *_setopt() calls (that could change the size of the cache) but
1872 before any transfer takes place. */
1873 res = Curl_ssl_initsessions(data, data->set.ssl.numsessions);
1877 data->set.followlocation=0; /* reset the location-follow counter */
1878 data->state.this_is_a_follow = FALSE; /* reset this */
1879 data->state.errorbuf = FALSE; /* no error has occurred */
1881 data->state.authproblem = FALSE;
1882 data->state.authhost.want = data->set.httpauth;
1883 data->state.authproxy.want = data->set.proxyauth;
1885 /* If there is a list of cookie files to read, do it now! */
1886 if(data->change.cookielist) {
1887 Curl_cookie_loadfiles(data);
1890 /* Allow data->set.use_port to set which port to use. This needs to be
1891 * disabled for example when we follow Location: headers to URLs using
1892 * different ports! */
1893 data->state.allow_port = TRUE;
1895 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1896 /*************************************************************
1897 * Tell signal handler to ignore SIGPIPE
1898 *************************************************************/
1899 if(!data->set.no_signal)
1900 data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
1903 Curl_initinfo(data); /* reset session-specific information "variables" */
1904 Curl_pgrsStartNow(data);
1910 * Curl_posttransfer() is called immediately after a transfer ends
1912 CURLcode Curl_posttransfer(struct SessionHandle *data)
1914 #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1915 /* restore the signal handler for SIGPIPE before we get back */
1916 if(!data->set.no_signal)
1917 signal(SIGPIPE, data->state.prev_signal);
1919 (void)data; /* unused parameter */
1922 if(!(data->progress.flags & PGRS_HIDE) &&
1923 !data->progress.callback)
1924 /* only output if we don't use a progress callback and we're not hidden */
1925 fprintf(data->set.err, "\n");
1931 * strlen_url() returns the length of the given URL if the spaces within the
1932 * URL were properly URL encoded.
1934 static size_t strlen_url(const char *url)
1938 bool left=TRUE; /* left side of the ? */
1940 for(ptr=url; *ptr; ptr++) {
1959 /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
1960 * the source URL accordingly.
1962 static void strcpy_url(char *output, const char *url)
1964 /* we must add this with whitespace-replacing */
1967 char *optr = output;
1968 for(iptr = url; /* read from here */
1969 *iptr; /* until zero byte */
1980 *optr++='%'; /* add a '%' */
1981 *optr++='2'; /* add a '2' */
1982 *optr++='0'; /* add a '0' */
1985 *optr++='+'; /* add a '+' here */
1989 *optr=0; /* zero terminate output buffer */
1994 * Returns true if the given URL is absolute (as opposed to relative)
1996 static bool is_absolute_url(const char *url)
1998 char prot[16]; /* URL protocol string storage */
1999 char letter; /* used for a silly sscanf */
2001 return 2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter);
2005 * Concatenate a relative URL to a base URL making it absolute.
2006 * URL-encodes any spaces.
2007 * The returned pointer must be freed by the caller unless NULL
2008 * (returns NULL on out of memory).
2010 static char *concat_url(const char *base, const char *relurl)
2013 TRY to append this new path to the old URL
2014 to the right of the host part. Oh crap, this is doomed to cause
2015 problems in the future...
2022 const char *useurl = relurl;
2025 /* we must make our own copy of the URL to play with, as it may
2026 point to read-only data */
2027 char *url_clone=strdup(base);
2030 return NULL; /* skip out of this NOW */
2032 /* protsep points to the start of the host name */
2033 protsep=strstr(url_clone, "//");
2037 protsep+=2; /* pass the slashes */
2039 if('/' != relurl[0]) {
2042 /* First we need to find out if there's a ?-letter in the URL,
2043 and cut it and the right-side of that off */
2044 pathsep = strchr(protsep, '?');
2048 /* we have a relative path to append to the last slash if there's one
2049 available, or if the new URL is just a query string (starts with a
2050 '?') we append the new one at the end of the entire currently worked
2052 if(useurl[0] != '?') {
2053 pathsep = strrchr(protsep, '/');
2058 /* Check if there's any slash after the host name, and if so, remember
2059 that position instead */
2060 pathsep = strchr(protsep, '/');
2062 protsep = pathsep+1;
2066 /* now deal with one "./" or any amount of "../" in the newurl
2067 and act accordingly */
2069 if((useurl[0] == '.') && (useurl[1] == '/'))
2070 useurl+=2; /* just skip the "./" */
2072 while((useurl[0] == '.') &&
2073 (useurl[1] == '.') &&
2074 (useurl[2] == '/')) {
2076 useurl+=3; /* pass the "../" */
2081 /* cut off one more level from the right of the original URL */
2082 pathsep = strrchr(protsep, '/');
2093 /* We got a new absolute path for this server, cut off from the
2095 pathsep = strchr(protsep, '/');
2097 /* When people use badly formatted URLs, such as
2098 "http://www.url.com?dir=/home/daniel" we must not use the first
2099 slash, if there's a ?-letter before it! */
2100 char *sep = strchr(protsep, '?');
2101 if(sep && (sep < pathsep))
2106 /* There was no slash. Now, since we might be operating on a badly
2107 formatted URL, such as "http://www.url.com?id=2380" which doesn't
2108 use a slash separator as it is supposed to, we need to check for a
2109 ?-letter as well! */
2110 pathsep = strchr(protsep, '?');
2116 /* If the new part contains a space, this is a mighty stupid redirect
2117 but we still make an effort to do "right". To the left of a '?'
2118 letter we replace each space with %20 while it is replaced with '+'
2119 on the right side of the '?' letter.
2121 newlen = strlen_url(useurl);
2123 urllen = strlen(url_clone);
2125 newest=(char *)malloc( urllen + 1 + /* possible slash */
2126 newlen + 1 /* zero byte */);
2129 free(url_clone); /* don't leak this */
2133 /* copy over the root url part */
2134 memcpy(newest, url_clone, urllen);
2136 /* check if we need to append a slash */
2137 if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
2140 newest[urllen++]='/';
2142 /* then append the new piece on the right side */
2143 strcpy_url(&newest[urllen], useurl);
2151 * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
2152 * as given by the remote server and set up the new URL to request.
2154 CURLcode Curl_follow(struct SessionHandle *data,
2155 char *newurl, /* this 'newurl' is the Location: string,
2156 and it must be malloc()ed before passed
2158 followtype type) /* see transfer.h */
2160 /* Location: redirect */
2161 bool disallowport = FALSE;
2163 if(type == FOLLOW_REDIR) {
2164 if((data->set.maxredirs != -1) &&
2165 (data->set.followlocation >= data->set.maxredirs)) {
2166 failf(data,"Maximum (%d) redirects followed", data->set.maxredirs);
2167 return CURLE_TOO_MANY_REDIRECTS;
2170 /* mark the next request as a followed location: */
2171 data->state.this_is_a_follow = TRUE;
2173 data->set.followlocation++; /* count location-followers */
2175 if(data->set.http_auto_referer) {
2176 /* We are asked to automatically set the previous URL as the referer
2177 when we get the next URL. We pick the ->url field, which may or may
2178 not be 100% correct */
2180 if(data->change.referer_alloc)
2181 /* If we already have an allocated referer, free this first */
2182 free(data->change.referer);
2184 data->change.referer = strdup(data->change.url);
2185 data->change.referer_alloc = TRUE; /* yes, free this later */
2189 if(!is_absolute_url(newurl)) {
2191 *DANG* this is an RFC 2068 violation. The URL is supposed
2192 to be absolute and this doesn't seem to be that!
2194 char *absolute = concat_url(data->change.url, newurl);
2196 return CURLE_OUT_OF_MEMORY;
2201 /* This is an absolute URL, don't allow the custom port number */
2202 disallowport = TRUE;
2204 if(strchr(newurl, ' ')) {
2205 /* This new URL contains at least one space, this is a mighty stupid
2206 redirect but we still make an effort to do "right". */
2208 size_t newlen = strlen_url(newurl);
2210 newest = malloc(newlen+1); /* get memory for this */
2212 return CURLE_OUT_OF_MEMORY;
2213 strcpy_url(newest, newurl); /* create a space-free URL */
2215 free(newurl); /* that was no good */
2216 newurl = newest; /* use this instead now */
2221 if(type == FOLLOW_FAKE) {
2222 /* we're only figuring out the new url if we would've followed locations
2223 but now we're done so we can get out! */
2224 data->info.wouldredirect = newurl;
2229 data->state.allow_port = FALSE;
2231 if(data->change.url_alloc)
2232 free(data->change.url);
2234 data->change.url_alloc = TRUE; /* the URL is allocated */
2236 data->change.url = newurl;
2237 newurl = NULL; /* don't free! */
2239 infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
2242 * We get here when the HTTP code is 300-399 (and 401). We need to perform
2243 * differently based on exactly what return code there was.
2245 * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
2246 * a HTTP (proxy-) authentication scheme other than Basic.
2248 switch(data->info.httpcode) {
2249 /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
2250 Authorization: XXXX header in the HTTP request code snippet */
2251 /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
2252 Proxy-Authorization: XXXX header in the HTTP request code snippet */
2253 /* 300 - Multiple Choices */
2254 /* 306 - Not used */
2255 /* 307 - Temporary Redirect */
2256 default: /* for all above (and the unknown ones) */
2257 /* Some codes are explicitly mentioned since I've checked RFC2616 and they
2258 * seem to be OK to POST to.
2261 case 301: /* Moved Permanently */
2262 /* (quote from RFC2616, section 10.3.2):
2264 * Note: When automatically redirecting a POST request after receiving a
2265 * 301 status code, some existing HTTP/1.0 user agents will erroneously
2266 * change it into a GET request.
2270 * Warning: Because most of importants user agents do this obvious RFC2616
2271 * violation, many webservers expect this misbehavior. So these servers
2272 * often answers to a POST request with an error page. To be sure that
2273 * libcurl gets the page that most user agents would get, libcurl has to
2276 * This behaviour can be overridden with CURLOPT_POST301.
2278 if( (data->set.httpreq == HTTPREQ_POST
2279 || data->set.httpreq == HTTPREQ_POST_FORM)
2280 && !data->set.post301) {
2282 "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
2283 data->set.httpreq = HTTPREQ_GET;
2286 case 302: /* Found */
2289 Note: RFC 1945 and RFC 2068 specify that the client is not allowed
2290 to change the method on the redirected request. However, most
2291 existing user agent implementations treat 302 as if it were a 303
2292 response, performing a GET on the Location field-value regardless
2293 of the original request method. The status codes 303 and 307 have
2294 been added for servers that wish to make unambiguously clear which
2295 kind of reaction is expected of the client.
2299 Note: Many pre-HTTP/1.1 user agents do not understand the 303
2300 status. When interoperability with such clients is a concern, the
2301 302 status code may be used instead, since most user agents react
2302 to a 302 response as described here for 303.
2304 case 303: /* See Other */
2305 /* Disable both types of POSTs, since doing a second POST when
2306 * following isn't what anyone would want! */
2307 if(data->set.httpreq != HTTPREQ_GET) {
2308 data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
2309 infof(data, "Disables POST, goes with %s\n",
2310 data->set.opt_no_body?"HEAD":"GET");
2313 case 304: /* Not Modified */
2314 /* 304 means we did a conditional request and it was "Not modified".
2315 * We shouldn't get any Location: header in this response!
2318 case 305: /* Use Proxy */
2319 /* (quote from RFC2616, section 10.3.6):
2320 * "The requested resource MUST be accessed through the proxy given
2321 * by the Location field. The Location field gives the URI of the
2322 * proxy. The recipient is expected to repeat this single request
2323 * via the proxy. 305 responses MUST only be generated by origin
2328 Curl_pgrsTime(data, TIMER_REDIRECT);
2329 Curl_pgrsResetTimes(data);
2335 connect_host(struct SessionHandle *data,
2336 struct connectdata **conn)
2338 CURLcode res = CURLE_OK;
2341 bool protocol_done=TRUE; /* will be TRUE always since this is only used
2342 within the easy interface */
2343 Curl_pgrsTime(data, TIMER_STARTSINGLE);
2344 res = Curl_connect(data, conn, &async, &protocol_done);
2346 if((CURLE_OK == res) && async) {
2347 /* Now, if async is TRUE here, we need to wait for the name
2349 res = Curl_wait_for_resolv(*conn, NULL);
2351 /* Resolved, continue with the connection */
2352 res = Curl_async_resolved(*conn, &protocol_done);
2354 /* if we can't resolve, we kill this "connection" now */
2355 (void)Curl_disconnect(*conn);
2361 /* Returns TRUE and sets '*url' if a request retry is wanted.
2363 NOTE: that the *url is malloc()ed. */
2364 bool Curl_retry_request(struct connectdata *conn,
2368 struct SessionHandle *data = conn->data;
2370 /* if we're talking upload, we can't do the checks below, unless the protocol
2371 is HTTP as when uploading over HTTP we will still get a response */
2372 if(data->set.upload && !(conn->protocol&PROT_HTTP))
2375 if((data->req.bytecount +
2376 data->req.headerbytecount == 0) &&
2378 !data->set.opt_no_body) {
2379 /* We got no data, we attempted to re-use a connection and yet we want a
2380 "body". This might happen if the connection was left alive when we were
2381 done using it before, but that was closed when we wanted to read from
2382 it again. Bad luck. Retry the same request on a fresh connect! */
2383 infof(conn->data, "Connection died, retrying a fresh connect\n");
2384 *url = strdup(conn->data->change.url);
2386 conn->bits.close = TRUE; /* close this connection */
2387 conn->bits.retry = TRUE; /* mark this as a connection we're about
2388 to retry. Marking it this way should
2389 prevent i.e HTTP transfers to return
2390 error just because nothing has been
2399 * Curl_perform() is the internal high-level function that gets called by the
2400 * external curl_easy_perform() function. It inits, performs and cleans up a
2401 * single file transfer.
2403 CURLcode Curl_perform(struct SessionHandle *data)
2407 struct connectdata *conn=NULL;
2408 char *newurl = NULL; /* possibly a new URL to follow to! */
2409 followtype follow = FOLLOW_NONE;
2411 data->state.used_interface = Curl_if_easy;
2413 res = Curl_pretransfer(data);
2418 * It is important that there is NO 'return' from this function at any other
2419 * place than falling down to the end of the function! This is because we
2420 * have cleanup stuff that must be done before we get back, and that is only
2421 * performed after this do-while loop.
2425 res = connect_host(data, &conn); /* primary connection */
2427 if(res == CURLE_OK) {
2429 if(data->set.connect_only) {
2430 /* keep connection open for application to use the socket */
2431 conn->bits.close = FALSE;
2432 res = Curl_done(&conn, CURLE_OK, FALSE);
2435 res = Curl_do(&conn, &do_done);
2437 if(res == CURLE_OK) {
2438 res = Transfer(conn); /* now fetch that URL please */
2439 if(res == CURLE_OK) {
2440 bool retry = Curl_retry_request(conn, &newurl);
2443 follow = FOLLOW_RETRY;
2445 res = CURLE_OUT_OF_MEMORY;
2449 * We must duplicate the new URL here as the connection data may
2450 * be free()ed in the Curl_done() function. We prefer the newurl
2451 * one since that's used for redirects or just further requests
2452 * for retries or multi-stage HTTP auth methods etc.
2454 if(data->req.newurl) {
2455 follow = FOLLOW_REDIR;
2456 newurl = strdup(data->req.newurl);
2458 res = CURLE_OUT_OF_MEMORY;
2460 else if(data->req.location) {
2461 follow = FOLLOW_FAKE;
2462 newurl = strdup(data->req.location);
2464 res = CURLE_OUT_OF_MEMORY;
2468 /* in the above cases where 'newurl' gets assigned, we have a fresh
2469 * allocated memory pointed to */
2471 if(res != CURLE_OK) {
2472 /* The transfer phase returned error, we mark the connection to get
2473 * closed to prevent being re-used. This is because we can't
2474 * possibly know if the connection is in a good shape or not now. */
2475 conn->bits.close = TRUE;
2477 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
2478 /* if we failed anywhere, we must clean up the secondary socket if
2480 sclose(conn->sock[SECONDARYSOCKET]);
2481 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
2485 /* Always run Curl_done(), even if some of the previous calls
2486 failed, but return the previous (original) error code */
2487 res2 = Curl_done(&conn, res, FALSE);
2493 /* Curl_do() failed, clean up left-overs in the done-call, but note
2494 that at some cases the conn pointer is NULL when Curl_do() failed
2495 and the connection cache is very small so only call Curl_done() if
2496 conn is still "alive".
2498 res2 = Curl_done(&conn, res, FALSE);
2501 * Important: 'conn' cannot be used here, since it may have been closed
2502 * in 'Curl_done' or other functions.
2505 if((res == CURLE_OK) && follow) {
2506 res = Curl_follow(data, newurl, follow);
2507 if(CURLE_OK == res) {
2508 /* if things went fine, Curl_follow() freed or otherwise took
2509 responsibility for the newurl pointer */
2511 if(follow >= FOLLOW_RETRY) {
2512 follow = FOLLOW_NONE;
2515 /* else we break out of the loop below */
2519 break; /* it only reaches here when this shouldn't loop */
2521 } while(1); /* loop if Location: */
2526 if(res && !data->state.errorbuf) {
2528 * As an extra precaution: if no error string has been set and there was
2529 * an error, use the strerror() string or if things are so bad that not
2530 * even that is good, set a bad string that mentions the error code.
2532 const char *str = curl_easy_strerror(res);
2534 failf(data, "unspecified error %d", (int)res);
2536 failf(data, "%s", str);
2539 /* run post-transfer unconditionally, but don't clobber the return code if
2540 we already have an error code recorder */
2541 res2 = Curl_posttransfer(data);
2549 * Curl_setup_transfer() is called to setup some basic properties for the
2550 * upcoming transfer.
2553 Curl_setup_transfer(
2554 struct connectdata *conn, /* connection data */
2555 int sockindex, /* socket index to read from or -1 */
2556 curl_off_t size, /* -1 if unknown at this point */
2557 bool getheader, /* TRUE if header parsing is wanted */
2558 curl_off_t *bytecountp, /* return number of bytes read or NULL */
2559 int writesockindex, /* socket index to write to, it may very well be
2560 the same we read from. -1 disables */
2561 curl_off_t *writecountp /* return number of bytes written or NULL */
2564 struct SessionHandle *data;
2565 struct SingleRequest *k;
2567 DEBUGASSERT(conn != NULL);
2572 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
2574 /* now copy all input parameters */
2575 conn->sockfd = sockindex == -1 ?
2576 CURL_SOCKET_BAD : conn->sock[sockindex];
2577 conn->writesockfd = writesockindex == -1 ?
2578 CURL_SOCKET_BAD:conn->sock[writesockindex];
2579 k->getheader = getheader;
2582 k->bytecountp = bytecountp;
2583 k->writebytecountp = writecountp;
2585 /* The code sequence below is placed in this function just because all
2586 necessary input is not always known in do_complete() as this function may
2587 be called after that */
2592 Curl_pgrsSetDownloadSize(data, size);
2594 /* we want header and/or body, if neither then don't do this! */
2595 if(k->getheader || !data->set.opt_no_body) {
2597 if(conn->sockfd != CURL_SOCKET_BAD) {
2598 k->keepon |= KEEP_READ;
2601 if(conn->writesockfd != CURL_SOCKET_BAD) {
2604 Even if we require a 100-return code before uploading data, we might
2605 need to write data before that since the REQUEST may not have been
2606 finished sent off just yet.
2608 Thus, we must check if the request has been sent before we set the
2609 state info where we wait for the 100-return code
2611 if((data->state.expect100header) &&
2612 (data->state.proto.http->sending == HTTPSEND_BODY)) {
2613 /* wait with write until we either got 100-continue or a timeout */
2614 k->exp100 = EXP100_AWAITING_CONTINUE;
2615 k->start100 = k->start;
2618 if(data->state.expect100header)
2619 /* when we've sent off the rest of the headers, we must await a
2620 100-continue but first finish sending the request */
2621 k->exp100 = EXP100_SENDING_REQUEST;
2623 /* enable the write bit when we're not waiting for continue */
2624 k->keepon |= KEEP_WRITE;
2626 } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
2627 } /* if(k->getheader || !data->set.opt_no_body) */