355
* Go ahead and do a read if we have a readable socket or if
356
* the stream was rewound (in which case we have data in a
359
static CURLcode readwrite_data(struct SessionHandle *data,
360
struct connectdata *conn,
361
struct SingleRequest *k,
362
int *didwhat, bool *done)
364
CURLcode result = CURLE_OK;
365
ssize_t nread; /* number of bytes read */
366
bool is_empty_data = FALSE;
370
/* This is where we loop until we have read everything there is to
371
read or we get a EWOULDBLOCK */
373
size_t buffersize = data->set.buffer_size?
374
data->set.buffer_size : BUFSIZE;
375
size_t bytestoread = buffersize;
378
if(k->size != -1 && !k->header) {
379
/* make sure we don't read "too much" if we can help it since we
380
might be pipelining and then someone else might want to read what
382
curl_off_t totalleft = k->size - k->bytecount;
383
if(totalleft < (curl_off_t)bytestoread)
384
bytestoread = (size_t)totalleft;
388
/* receive data from the network! */
389
readrc = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
391
/* subzero, this would've blocked */
393
break; /* get out of loop */
395
/* get the CURLcode from the int */
396
result = (CURLcode)readrc;
402
/* read nothing but since we wanted nothing we consider this an OK
403
situation to proceed from */
407
if((k->bytecount == 0) && (k->writebytecount == 0)) {
408
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
409
if(k->exp100 > EXP100_SEND_DATA)
410
/* set time stamp to compare with when waiting for the 100 */
411
k->start100 = Curl_tvnow();
414
*didwhat |= KEEP_READ;
415
/* indicates data of zero size, i.e. empty file */
416
is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
418
/* NUL terminate, allowing string ops to be used */
419
if(0 < nread || is_empty_data) {
422
else if(0 >= nread) {
423
/* if we receive 0 or less here, the server closed the connection
424
and we bail out from this! */
425
DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
426
k->keepon &= ~KEEP_READ;
430
/* Default buffer to use when we write the buffer, it may be changed
431
in the flow below before the actual storing is done. */
434
#ifndef CURL_DISABLE_HTTP
435
/* Since this is a two-state thing, we check if we are parsing
436
headers at the moment or not. */
438
/* we are in parse-the-header-mode */
439
bool stop_reading = FALSE;
440
result = readwrite_http_headers(data, conn, k, &nread, &stop_reading);
444
/* We've stopped dealing with input, get out of the do-while loop */
447
#endif /* CURL_DISABLE_HTTP */
450
/* This is not an 'else if' since it may be a rest from the header
451
parsing, where the beginning of the buffer is headers and the end
453
if(k->str && !k->header && (nread > 0 || is_empty_data)) {
455
#ifndef CURL_DISABLE_HTTP
456
if(0 == k->bodywrites && !is_empty_data) {
457
/* These checks are only made the first time we are about to
458
write a piece of the body */
459
if(conn->protocol&PROT_HTTP) {
460
/* HTTP-only checks */
462
if(data->req.newurl) {
463
if(conn->bits.close) {
464
/* Abort after the headers if "follow Location" is set
465
and we're set to close anyway. */
466
k->keepon &= ~KEEP_READ;
470
/* We have a new url to load, but since we want to be able
471
to re-use this connection properly, we read the full
472
response in "ignore more" */
473
k->ignorebody = TRUE;
474
infof(data, "Ignoring the response-body\n");
476
if(data->state.resume_from && !k->content_range &&
477
(data->set.httpreq==HTTPREQ_GET) &&
479
/* we wanted to resume a download, although the server doesn't
480
* seem to support this and we did this with a GET (if it
481
* wasn't a GET we did a POST or PUT resume) */
482
failf(data, "HTTP server doesn't seem to support "
483
"byte ranges. Cannot resume.");
484
return CURLE_RANGE_ERROR;
487
if(data->set.timecondition && !data->state.range) {
488
/* A time condition has been set AND no ranges have been
489
requested. This seems to be what chapter 13.3.4 of
490
RFC 2616 defines to be the correct action for a
492
if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
493
switch(data->set.timecondition) {
494
case CURL_TIMECOND_IFMODSINCE:
496
if(k->timeofdoc < data->set.timevalue) {
498
"The requested document is not new enough\n");
500
data->info.timecond = TRUE;
504
case CURL_TIMECOND_IFUNMODSINCE:
505
if(k->timeofdoc > data->set.timevalue) {
507
"The requested document is not old enough\n");
509
data->info.timecond = TRUE;
514
} /* two valid time strings */
515
} /* we have a time condition */
518
} /* this is the first time we write a body part */
519
#endif /* CURL_DISABLE_HTTP */
522
/* pass data to the debug function before it gets "dechunked" */
523
if(data->set.verbose) {
525
Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
526
(size_t)k->hbuflen, conn);
527
if(k->badheader == HEADER_PARTHEADER)
528
Curl_debug(data, CURLINFO_DATA_IN,
529
k->str, (size_t)nread, conn);
532
Curl_debug(data, CURLINFO_DATA_IN,
533
k->str, (size_t)nread, conn);
536
#ifndef CURL_DISABLE_HTTP
539
* Here comes a chunked transfer flying and we need to decode this
540
* properly. While the name says read, this function both reads
541
* and writes away the data. The returned 'nread' holds the number
542
* of actual data it wrote to the client.
546
Curl_httpchunk_read(conn, k->str, nread, &nread);
548
if(CHUNKE_OK < res) {
549
if(CHUNKE_WRITE_ERROR == res) {
550
failf(data, "Failed writing data");
551
return CURLE_WRITE_ERROR;
553
failf(data, "Received problem %d in the chunky parser", res);
554
return CURLE_RECV_ERROR;
556
else if(CHUNKE_STOP == res) {
558
/* we're done reading chunks! */
559
k->keepon &= ~KEEP_READ; /* read no more */
561
/* There are now possibly N number of bytes at the end of the
562
str buffer that weren't written to the client.
564
We DO care about this data if we are pipelining.
565
Push it back to be read on the next pass. */
567
dataleft = conn->chunk.dataleft;
569
infof(conn->data, "Leftovers after chunking. "
570
" Rewinding %d bytes\n",dataleft);
571
read_rewind(conn, dataleft);
574
/* If it returned OK, we just keep going */
576
#endif /* CURL_DISABLE_HTTP */
578
if((-1 != k->maxdownload) &&
579
(k->bytecount + nread >= k->maxdownload)) {
580
/* The 'excess' amount below can't be more than BUFSIZE which
581
always will fit in a size_t */
582
size_t excess = (size_t)(k->bytecount + nread - k->maxdownload);
583
if(excess > 0 && !k->ignorebody) {
585
"Rewinding stream by : %d"
586
" bytes on url %s (size = %" FORMAT_OFF_T
587
", maxdownload = %" FORMAT_OFF_T
588
", bytecount = %" FORMAT_OFF_T ", nread = %d)\n",
589
excess, data->state.path,
590
k->size, k->maxdownload, k->bytecount, nread);
591
read_rewind(conn, excess);
594
nread = (ssize_t) (k->maxdownload - k->bytecount);
595
if(nread < 0 ) /* this should be unusual */
598
k->keepon &= ~KEEP_READ; /* we're done reading */
601
k->bytecount += nread;
603
Curl_pgrsSetDownloadCounter(data, k->bytecount);
605
if(!k->chunk && (nread || k->badheader || is_empty_data)) {
606
/* If this is chunky transfer, it was already written */
608
if(k->badheader && !k->ignorebody) {
609
/* we parsed a piece of data wrongly assuming it was a header
610
and now we output it as body instead */
611
result = Curl_client_write(conn, CLIENTWRITE_BODY,
612
data->state.headerbuff,
617
if(k->badheader < HEADER_ALLBAD) {
618
/* This switch handles various content encodings. If there's an
619
error here, be sure to check over the almost identical code
621
Make sure that ALL_CONTENT_ENCODINGS contains all the
622
encodings handled here. */
624
switch (conn->data->set.http_ce_skip ?
625
IDENTITY : k->content_encoding) {
628
/* This is the default when the server sends no
629
Content-Encoding header. See Curl_readwrite_init; the
630
memset() call initializes k->content_encoding to zero. */
632
result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
638
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
640
result = Curl_unencode_deflate_write(conn, k, nread);
644
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
646
result = Curl_unencode_gzip_write(conn, k, nread);
651
failf (data, "Unrecognized content encoding type. "
652
"libcurl understands `identity', `deflate' and `gzip' "
653
"content encodings.");
654
result = CURLE_BAD_CONTENT_ENCODING;
659
k->badheader = HEADER_NORMAL; /* taken care of now */
665
} /* if(! header and data to read ) */
668
/* if we received nothing, the server closed the connection and we
670
k->keepon &= ~KEEP_READ;
673
} while(data_pending(conn));
675
if(((k->keepon & (KEEP_READ|KEEP_WRITE)) == KEEP_WRITE) &&
677
/* When we've read the entire thing and the close bit is set, the server
678
may now close the connection. If there's now any kind of sending going
679
on from our side, we need to stop that immediately. */
680
infof(data, "we are done reading and this is set to close, stop send\n");
681
k->keepon &= ~KEEP_WRITE; /* no writing anymore either */
687
#ifndef CURL_DISABLE_HTTP
689
* Read any HTTP header lines from the server and pass them to the client app.
691
static CURLcode readwrite_http_headers(struct SessionHandle *data,
692
struct connectdata *conn,
693
struct SingleRequest *k,
699
/* header line within buffer loop */
706
/* str_start is start of line within buf */
707
k->str_start = k->str;
709
/* data is in network encoding so use 0x0a instead of '\n' */
710
k->end_ptr = memchr(k->str_start, 0x0a, *nread);
713
/* Not a complete header line within buffer, append the data to
714
the end of the headerbuff. */
716
if(k->hbuflen + *nread >= data->state.headersize) {
717
/* We enlarge the header buffer as it is too small */
719
size_t newsize=CURLMAX((k->hbuflen+*nread)*3/2,
720
data->state.headersize*2);
721
hbufp_index = k->hbufp - data->state.headerbuff;
722
newbuff = realloc(data->state.headerbuff, newsize);
724
failf (data, "Failed to alloc memory for big header!");
725
return CURLE_OUT_OF_MEMORY;
727
data->state.headersize=newsize;
728
data->state.headerbuff = newbuff;
729
k->hbufp = data->state.headerbuff + hbufp_index;
731
memcpy(k->hbufp, k->str, *nread);
733
k->hbuflen += *nread;
734
if(!k->headerline && (k->hbuflen>5)) {
735
/* make a first check that this looks like a HTTP header */
736
if(!checkhttpprefix(data, data->state.headerbuff)) {
737
/* this is not the beginning of a HTTP first header line */
739
k->badheader = HEADER_ALLBAD;
744
break; /* read more and try again */
747
/* decrease the size of the remaining (supposed) header line */
748
rest_length = (k->end_ptr - k->str)+1;
749
*nread -= (ssize_t)rest_length;
751
k->str = k->end_ptr + 1; /* move past new line */
753
full_length = k->str - k->str_start;
756
* We're about to copy a chunk of data to the end of the
757
* already received header. We make sure that the full string
758
* fit in the allocated header buffer, or else we enlarge
761
if(k->hbuflen + full_length >=
762
data->state.headersize) {
764
size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
765
data->state.headersize*2);
766
hbufp_index = k->hbufp - data->state.headerbuff;
767
newbuff = realloc(data->state.headerbuff, newsize);
769
failf (data, "Failed to alloc memory for big header!");
770
return CURLE_OUT_OF_MEMORY;
772
data->state.headersize= newsize;
773
data->state.headerbuff = newbuff;
774
k->hbufp = data->state.headerbuff + hbufp_index;
777
/* copy to end of line */
778
memcpy(k->hbufp, k->str_start, full_length);
779
k->hbufp += full_length;
780
k->hbuflen += full_length;
782
k->end_ptr = k->hbufp;
784
k->p = data->state.headerbuff;
787
* We now have a FULL header line that p points to
791
/* the first read header */
793
!checkhttpprefix(data, data->state.headerbuff)) {
794
/* this is not the beginning of a HTTP first header line */
797
/* since there's more, this is a partial bad header */
798
k->badheader = HEADER_PARTHEADER;
800
/* this was all we read so it's all a bad header */
801
k->badheader = HEADER_ALLBAD;
802
*nread = (ssize_t)rest_length;
808
/* headers are in network encoding so
809
use 0x0a and 0x0d instead of '\n' and '\r' */
810
if((0x0a == *k->p) || (0x0d == *k->p)) {
812
/* Zero-length header line means end of headers! */
814
#ifdef CURL_DOES_CONVERSIONS
816
*k->p = '\r'; /* replace with CR in host encoding */
817
k->p++; /* pass the CR byte */
820
*k->p = '\n'; /* replace with LF in host encoding */
821
k->p++; /* pass the LF byte */
825
k->p++; /* pass the \r byte */
827
k->p++; /* pass the \n byte */
828
#endif /* CURL_DOES_CONVERSIONS */
830
if(100 <= k->httpcode && 199 >= k->httpcode) {
832
* We have made a HTTP PUT or POST and this is 1.1-lingo
833
* that tells us that the server is OK with this and ready
834
* to receive the data.
835
* However, we'll get more headers now so we must get
836
* back into the header-parsing state!
839
k->headerline = 0; /* restart the header line counter */
841
/* if we did wait for this do enable write now! */
843
k->exp100 = EXP100_SEND_DATA;
844
k->keepon |= KEEP_WRITE;
848
k->header = FALSE; /* no more header to parse! */
850
if((k->size == -1) && !k->chunk && !conn->bits.close &&
851
(conn->httpversion >= 11) ) {
852
/* On HTTP 1.1, when connection is not to get closed, but no
853
Content-Length nor Content-Encoding chunked have been
854
received, according to RFC2616 section 4.4 point 5, we
855
assume that the server will close the connection to
856
signal the end of the document. */
857
infof(data, "no chunk, no close, no size. Assume close to "
859
conn->bits.close = TRUE;
863
if(417 == k->httpcode) {
865
* we got: "417 Expectation Failed" this means:
866
* we have made a HTTP call and our Expect Header
867
* seems to cause a problem => abort the write operations
868
* (or prevent them from starting).
870
k->exp100 = EXP100_FAILED;
871
k->keepon &= ~KEEP_WRITE;
875
* When all the headers have been parsed, see if we should give
876
* up and return an error.
878
if(Curl_http_should_fail(conn)) {
879
failf (data, "The requested URL returned error: %d",
881
return CURLE_HTTP_RETURNED_ERROR;
884
/* now, only output this if the header AND body are requested:
886
writetype = CLIENTWRITE_HEADER;
887
if(data->set.include_header)
888
writetype |= CLIENTWRITE_BODY;
890
headerlen = k->p - data->state.headerbuff;
892
result = Curl_client_write(conn, writetype,
893
data->state.headerbuff,
898
data->info.header_size += (long)headerlen;
899
data->req.headerbytecount += (long)headerlen;
901
data->req.deductheadercount =
902
(100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
904
if(data->state.resume_from &&
905
(data->set.httpreq==HTTPREQ_GET) &&
906
(k->httpcode == 416)) {
907
/* "Requested Range Not Satisfiable" */
908
*stop_reading = TRUE;
912
/* Curl_http_auth_act() checks what authentication methods
913
* that are available and decides which one (if any) to
914
* use. It will set 'newurl' if an auth method was picked. */
915
result = Curl_http_auth_act(conn);
920
if(conn->bits.rewindaftersend) {
921
/* We rewind after a complete send, so thus we continue
923
infof(data, "Keep sending data to get tossed away!\n");
924
k->keepon |= KEEP_WRITE;
930
* really end-of-headers.
932
* If we requested a "no body", this is a good time to get
933
* out and return home.
935
if(data->set.opt_no_body)
936
*stop_reading = TRUE;
938
/* If we know the expected size of this document, we set the
939
maximum download size to the size of the expected
940
document or else, we won't know when to stop reading!
942
Note that we set the download maximum even if we read a
943
"Connection: close" header, to make sure that
944
"Content-Length: 0" still prevents us from attempting to
945
read the (missing) response-body.
947
/* According to RFC2616 section 4.4, we MUST ignore
948
Content-Length: headers if we are now receiving data
949
using chunked Transfer-Encoding.
956
/* We do this operation even if no_body is true, since this
957
data might be retrieved later with curl_easy_getinfo()
958
and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
960
Curl_pgrsSetDownloadSize(data, k->size);
961
k->maxdownload = k->size;
963
/* If max download size is *zero* (nothing) we already
964
have nothing and can safely return ok now! */
965
if(0 == k->maxdownload)
966
*stop_reading = TRUE;
969
/* we make sure that this socket isn't read more now */
970
k->keepon &= ~KEEP_READ;
973
if(data->set.verbose)
974
Curl_debug(data, CURLINFO_HEADER_IN,
975
k->str_start, headerlen, conn);
976
break; /* exit header line loop */
979
/* We continue reading headers, so reset the line-based
980
header parsing variables hbufp && hbuflen */
981
k->hbufp = data->state.headerbuff;
987
* Checks for special headers coming up.
990
if(!k->headerline++) {
991
/* This is the first header, it MUST be the error code line
992
or else we consider this to be the body right away! */
993
int httpversion_major;
995
#ifdef CURL_DOES_CONVERSIONS
996
#define HEADER1 scratch
997
#define SCRATCHSIZE 21
999
char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
1000
/* We can't really convert this yet because we
1001
don't know if it's the 1st header line or the body.
1002
So we do a partial conversion into a scratch area,
1003
leaving the data at k->p as-is.
1005
strncpy(&scratch[0], k->p, SCRATCHSIZE);
1006
scratch[SCRATCHSIZE] = 0; /* null terminate */
1007
res = Curl_convert_from_network(data,
1010
if(CURLE_OK != res) {
1011
/* Curl_convert_from_network calls failf if unsuccessful */
1015
#define HEADER1 k->p /* no conversion needed, just use k->p */
1016
#endif /* CURL_DOES_CONVERSIONS */
1018
nc = sscanf(HEADER1,
1024
conn->httpversion += 10 * httpversion_major;
1027
/* this is the real world, not a Nirvana
1028
NCSA 1.5.x returns this crap when asked for HTTP/1.1
1030
nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
1031
conn->httpversion = 10;
1033
/* If user has set option HTTP200ALIASES,
1034
compare header line against list of aliases
1037
if(checkhttpprefix(data, k->p)) {
1040
conn->httpversion = 10;
1046
data->info.httpcode = k->httpcode;
1047
data->info.httpversion = conn->httpversion;
1048
if (!data->state.httpversion ||
1049
data->state.httpversion > conn->httpversion)
1050
/* store the lowest server version we encounter */
1051
data->state.httpversion = conn->httpversion;
1054
* This code executes as part of processing the header. As a
1055
* result, it's not totally clear how to interpret the
1056
* response code yet as that depends on what other headers may
1057
* be present. 401 and 407 may be errors, but may be OK
1058
* depending on how authentication is working. Other codes
1059
* are definitely errors, so give up here.
1061
if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
1062
((k->httpcode != 401) || !conn->bits.user_passwd) &&
1063
((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
1065
if(data->state.resume_from &&
1066
(data->set.httpreq==HTTPREQ_GET) &&
1067
(k->httpcode == 416)) {
1068
/* "Requested Range Not Satisfiable", just proceed and
1069
pretend this is no error */
1072
/* serious error, go home! */
1073
failf (data, "The requested URL returned error: %d",
1075
return CURLE_HTTP_RETURNED_ERROR;
1079
if(conn->httpversion == 10) {
1080
/* Default action for HTTP/1.0 must be to close, unless
1081
we get one of those fancy headers that tell us the
1082
server keeps it open for us! */
1083
infof(data, "HTTP 1.0, assume close after body\n");
1084
conn->bits.close = TRUE;
1086
else if(conn->httpversion >= 11 &&
1087
!conn->bits.close) {
1088
/* If HTTP version is >= 1.1 and connection is persistent
1089
server supports pipelining. */
1091
"HTTP 1.1 or later with persistent connection, "
1092
"pipelining supported\n"));
1093
conn->server_supports_pipelining = TRUE;
1096
switch(k->httpcode) {
1098
/* (quote from RFC2616, section 10.2.5): The server has
1099
* fulfilled the request but does not need to return an
1100
* entity-body ... The 204 response MUST NOT include a
1101
* message-body, and thus is always terminated by the first
1102
* empty line after the header fields. */
1104
case 416: /* Requested Range Not Satisfiable, it has the
1105
Content-Length: set as the "real" document but no
1106
actual response is sent. */
1108
/* (quote from RFC2616, section 10.3.5): The 304 response
1109
* MUST NOT contain a message-body, and thus is always
1110
* terminated by the first empty line after the header
1112
if(data->set.timecondition)
1113
data->info.timecond = TRUE;
1116
k->ignorecl = TRUE; /* ignore Content-Length headers */
1124
k->header = FALSE; /* this is not a header line */
1129
#ifdef CURL_DOES_CONVERSIONS
1130
/* convert from the network encoding */
1131
result = Curl_convert_from_network(data, k->p, strlen(k->p));
1132
if(CURLE_OK != result) {
1135
/* Curl_convert_from_network calls failf if unsuccessful */
1136
#endif /* CURL_DOES_CONVERSIONS */
1138
/* Check for Content-Length: header lines to get size. Ignore
1139
the header completely if we get a 416 response as then we're
1140
resuming a document that we don't get, and this header contains
1141
info about the true size of the document we didn't get now. */
1142
if(!k->ignorecl && !data->set.ignorecl &&
1143
checkprefix("Content-Length:", k->p)) {
1144
curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
1145
if(data->set.max_filesize &&
1146
contentlength > data->set.max_filesize) {
1147
failf(data, "Maximum file size exceeded");
1148
return CURLE_FILESIZE_EXCEEDED;
1150
if(contentlength >= 0) {
1151
k->size = contentlength;
1152
k->maxdownload = k->size;
1153
/* we set the progress download size already at this point
1154
just to make it easier for apps/callbacks to extract this
1155
info as soon as possible */
1156
Curl_pgrsSetDownloadSize(data, k->size);
1159
/* Negative Content-Length is really odd, and we know it
1160
happens for example when older Apache servers send large
1162
conn->bits.close = TRUE;
1163
infof(data, "Negative content-length: %" FORMAT_OFF_T
1164
", closing after transfer\n", contentlength);
1167
/* check for Content-Type: header lines to get the MIME-type */
1168
else if(checkprefix("Content-Type:", k->p)) {
1169
char *contenttype = Curl_copy_header_value(k->p);
1171
return CURLE_OUT_OF_MEMORY;
1173
/* ignore empty data */
1176
Curl_safefree(data->info.contenttype);
1177
data->info.contenttype = contenttype;
1180
else if((conn->httpversion == 10) &&
1181
conn->bits.httpproxy &&
1182
Curl_compareheader(k->p,
1183
"Proxy-Connection:", "keep-alive")) {
1185
* When a HTTP/1.0 reply comes when using a proxy, the
1186
* 'Proxy-Connection: keep-alive' line tells us the
1187
* connection will be kept alive for our pleasure.
1188
* Default action for 1.0 is to close.
1190
conn->bits.close = FALSE; /* don't close when done */
1191
infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
1193
else if((conn->httpversion == 11) &&
1194
conn->bits.httpproxy &&
1195
Curl_compareheader(k->p,
1196
"Proxy-Connection:", "close")) {
1198
* We get a HTTP/1.1 response from a proxy and it says it'll
1199
* close down after this transfer.
1201
conn->bits.close = TRUE; /* close when done */
1202
infof(data, "HTTP/1.1 proxy connection set close!\n");
1204
else if((conn->httpversion == 10) &&
1205
Curl_compareheader(k->p, "Connection:", "keep-alive")) {
1207
* A HTTP/1.0 reply with the 'Connection: keep-alive' line
1208
* tells us the connection will be kept alive for our
1209
* pleasure. Default action for 1.0 is to close.
1211
* [RFC2068, section 19.7.1] */
1212
conn->bits.close = FALSE; /* don't close when done */
1213
infof(data, "HTTP/1.0 connection set to keep alive!\n");
1215
else if(Curl_compareheader(k->p, "Connection:", "close")) {
1217
* [RFC 2616, section 8.1.2.1]
1218
* "Connection: close" is HTTP/1.1 language and means that
1219
* the connection will close when this request has been
1222
conn->bits.close = TRUE; /* close when done */
1224
else if(Curl_compareheader(k->p,
1225
"Transfer-Encoding:", "chunked")) {
1227
* [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
1228
* means that the server will send a series of "chunks". Each
1229
* chunk starts with line with info (including size of the
1230
* coming block) (terminated with CRLF), then a block of data
1231
* with the previously mentioned size. There can be any amount
1232
* of chunks, and a chunk-data set to zero signals the
1234
k->chunk = TRUE; /* chunks coming our way */
1236
/* init our chunky engine */
1237
Curl_httpchunk_init(conn);
1240
else if(checkprefix("Trailer:", k->p) ||
1241
checkprefix("Trailers:", k->p)) {
1243
* This test helps Curl_httpchunk_read() to determine to look
1244
* for well formed trailers after the zero chunksize record. In
1245
* this case a CRLF is required after the zero chunksize record
1246
* when no trailers are sent, or after the last trailer record.
1248
* It seems both Trailer: and Trailers: occur in the wild.
1250
k->trailerhdrpresent = TRUE;
1253
else if(checkprefix("Content-Encoding:", k->p) &&
1254
data->set.str[STRING_ENCODING]) {
1256
* Process Content-Encoding. Look for the values: identity,
1257
* gzip, deflate, compress, x-gzip and x-compress. x-gzip and
1258
* x-compress are the same as gzip and compress. (Sec 3.5 RFC
1259
* 2616). zlib cannot handle compress. However, errors are
1260
* handled further down when the response body is processed
1264
/* Find the first non-space letter */
1266
while(*start && ISSPACE(*start))
1269
/* Record the content-encoding for later use */
1270
if(checkprefix("identity", start))
1271
k->content_encoding = IDENTITY;
1272
else if(checkprefix("deflate", start))
1273
k->content_encoding = DEFLATE;
1274
else if(checkprefix("gzip", start)
1275
|| checkprefix("x-gzip", start))
1276
k->content_encoding = GZIP;
1277
else if(checkprefix("compress", start)
1278
|| checkprefix("x-compress", start))
1279
k->content_encoding = COMPRESS;
1281
else if(checkprefix("Content-Range:", k->p)) {
1282
/* Content-Range: bytes [num]-
1283
Content-Range: bytes: [num]-
1284
Content-Range: [num]-
1286
The second format was added since Sun's webserver
1287
JavaWebServer/1.1.1 obviously sends the header this way!
1288
The third added since some servers use that!
1291
char *ptr = k->p + 14;
1293
/* Move forward until first digit */
1294
while(*ptr && !ISDIGIT(*ptr))
1297
k->offset = curlx_strtoofft(ptr, NULL, 10);
1299
if(data->state.resume_from == k->offset)
1300
/* we asked for a resume and we got it */
1301
k->content_range = TRUE;
1303
#if !defined(CURL_DISABLE_COOKIES)
1304
else if(data->cookies &&
1305
checkprefix("Set-Cookie:", k->p)) {
1306
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
1307
CURL_LOCK_ACCESS_SINGLE);
1308
Curl_cookie_add(data,
1309
data->cookies, TRUE, k->p+11,
1310
/* If there is a custom-set Host: name, use it
1311
here, or else use real peer host name. */
1312
conn->allocptr.cookiehost?
1313
conn->allocptr.cookiehost:conn->host.name,
1315
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1318
else if(checkprefix("Last-Modified:", k->p) &&
1319
(data->set.timecondition || data->set.get_filetime) ) {
1320
time_t secs=time(NULL);
1321
k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
1323
if(data->set.get_filetime)
1324
data->info.filetime = (long)k->timeofdoc;
1326
else if((checkprefix("WWW-Authenticate:", k->p) &&
1327
(401 == k->httpcode)) ||
1328
(checkprefix("Proxy-authenticate:", k->p) &&
1329
(407 == k->httpcode))) {
1330
result = Curl_http_input_auth(conn, k->httpcode, k->p);
1334
else if((k->httpcode >= 300 && k->httpcode < 400) &&
1335
checkprefix("Location:", k->p)) {
1336
/* this is the URL that the server advises us to use instead */
1337
char *location = Curl_copy_header_value(k->p);
1339
return CURLE_OUT_OF_MEMORY;
1341
/* ignore empty data */
1344
DEBUGASSERT(!data->req.location);
1345
data->req.location = location;
1347
if(data->set.http_follow_location) {
1348
DEBUGASSERT(!data->req.newurl);
1349
data->req.newurl = strdup(data->req.location); /* clone */
1350
if(!data->req.newurl)
1351
return CURLE_OUT_OF_MEMORY;
1353
/* some cases of POST and PUT etc needs to rewind the data
1354
stream at this point */
1355
result = Curl_http_perhapsrewind(conn);
1363
* End of header-checks. Write them to the client.
1366
writetype = CLIENTWRITE_HEADER;
1367
if(data->set.include_header)
1368
writetype |= CLIENTWRITE_BODY;
1370
if(data->set.verbose)
1371
Curl_debug(data, CURLINFO_HEADER_IN,
1372
k->p, (size_t)k->hbuflen, conn);
1374
result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
1378
data->info.header_size += (long)k->hbuflen;
1379
data->req.headerbytecount += (long)k->hbuflen;
1381
/* reset hbufp pointer && hbuflen */
1382
k->hbufp = data->state.headerbuff;
1385
while(!*stop_reading && *k->str); /* header line within buffer */
1387
/* We might have reached the end of the header part here, but
1388
there might be a non-header part left in the end of the read
1393
#endif /* CURL_DISABLE_HTTP */
1396
* Send data to upload to the server, when the socket is writable.
1398
static CURLcode readwrite_upload(struct SessionHandle *data,
1399
struct connectdata *conn,
1400
struct SingleRequest *k,
1404
ssize_t bytes_written;
1406
ssize_t nread; /* number of bytes read */
1408
if((k->bytecount == 0) && (k->writebytecount == 0))
1409
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
1411
*didwhat |= KEEP_WRITE;
1414
* We loop here to do the READ and SEND loop until we run out of
1415
* data to send or until we get EWOULDBLOCK back
1419
/* only read more data if there's no upload data already
1420
present in the upload buffer */
1421
if(0 == data->req.upload_present) {
1422
/* init the "upload from here" pointer */
1423
data->req.upload_fromhere = k->uploadbuf;
1425
if(!k->upload_done) {
1426
/* HTTP pollution, this should be written nicer to become more
1427
protocol agnostic. */
1430
if((k->exp100 == EXP100_SENDING_REQUEST) &&
1431
(data->state.proto.http->sending == HTTPSEND_BODY)) {
1432
/* If this call is to send body data, we must take some action:
1433
We have sent off the full HTTP 1.1 request, and we shall now
1434
go into the Expect: 100 state and await such a header */
1435
k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
1436
k->keepon &= ~KEEP_WRITE; /* disable writing */
1437
k->start100 = Curl_tvnow(); /* timeout count starts now */
1438
*didwhat &= ~KEEP_WRITE; /* we didn't write anything actually */
1442
result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
1446
nread = (ssize_t)fillcount;
1449
nread = 0; /* we're done uploading/reading */
1451
if(!nread && (k->keepon & KEEP_WRITE_PAUSE)) {
1452
/* this is a paused transfer */
1457
k->keepon &= ~KEEP_WRITE; /* we're done writing */
1459
if(conn->bits.rewindaftersend) {
1460
result = Curl_readrewind(conn);
1467
/* store number of bytes available for upload */
1468
data->req.upload_present = nread;
1470
/* convert LF to CRLF if so asked */
1471
#ifdef CURL_DO_LINEEND_CONV
1472
/* always convert if we're FTPing in ASCII mode */
1473
if((data->set.crlf) || (data->set.prefer_ascii))
1476
#endif /* CURL_DO_LINEEND_CONV */
1478
if(data->state.scratch == NULL)
1479
data->state.scratch = malloc(2*BUFSIZE);
1480
if(data->state.scratch == NULL) {
1481
failf (data, "Failed to alloc scratch buffer!");
1482
return CURLE_OUT_OF_MEMORY;
1485
* ASCII/EBCDIC Note: This is presumably a text (not binary)
1486
* transfer so the data should already be in ASCII.
1487
* That means the hex values for ASCII CR (0x0d) & LF (0x0a)
1488
* must be used instead of the escape sequences \r & \n.
1490
for(i = 0, si = 0; i < nread; i++, si++) {
1491
if(data->req.upload_fromhere[i] == 0x0a) {
1492
data->state.scratch[si++] = 0x0d;
1493
data->state.scratch[si] = 0x0a;
1494
if(!data->set.crlf) {
1495
/* we're here only because FTP is in ASCII mode...
1496
bump infilesize for the LF we just added */
1497
data->set.infilesize++;
1501
data->state.scratch[si] = data->req.upload_fromhere[i];
1504
/* only perform the special operation if we really did replace
1508
/* upload from the new (replaced) buffer instead */
1509
data->req.upload_fromhere = data->state.scratch;
1511
/* set the new amount too */
1512
data->req.upload_present = nread;
1515
} /* if 0 == data->req.upload_present */
1517
/* We have a partial buffer left from a previous "round". Use
1518
that instead of reading more data */
1521
/* write to socket (send away data) */
1522
result = Curl_write(conn,
1523
conn->writesockfd, /* socket to send to */
1524
data->req.upload_fromhere, /* buffer pointer */
1525
data->req.upload_present, /* buffer size */
1526
&bytes_written); /* actually send away */
1531
if(data->set.verbose)
1532
/* show the data before we change the pointer upload_fromhere */
1533
Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
1534
(size_t)bytes_written, conn);
1536
if(data->req.upload_present != bytes_written) {
1537
/* we only wrote a part of the buffer (if anything), deal with it! */
1539
/* store the amount of bytes left in the buffer to write */
1540
data->req.upload_present -= bytes_written;
1542
/* advance the pointer where to find the buffer when the next send
1544
data->req.upload_fromhere += bytes_written;
1547
/* we've uploaded that buffer now */
1548
data->req.upload_fromhere = k->uploadbuf;
1549
data->req.upload_present = 0; /* no more bytes left */
1551
if(k->upload_done) {
1552
/* switch off writing, we're done! */
1553
k->keepon &= ~KEEP_WRITE; /* we're done writing */
1557
k->writebytecount += bytes_written;
1558
Curl_pgrsSetUploadCounter(data, k->writebytecount);
1560
} while(0); /* just to break out from! */
334
1566
* Curl_readwrite() is the low-level function to be called when data is to
335
1567
* be read and written to/from the connection.
383
1613
if((k->keepon & KEEP_READ) &&
384
1614
((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
386
bool is_empty_data = FALSE;
388
/* This is where we loop until we have read everything there is to
389
read or we get a EWOULDBLOCK */
391
size_t buffersize = data->set.buffer_size?
392
data->set.buffer_size : BUFSIZE;
393
size_t bytestoread = buffersize;
396
if(k->size != -1 && !k->header) {
397
/* make sure we don't read "too much" if we can help it since we
398
might be pipelining and then someone else might want to read what
400
curl_off_t totalleft = k->size - k->bytecount;
401
if(totalleft < (curl_off_t)bytestoread)
402
bytestoread = (size_t)totalleft;
406
/* receive data from the network! */
407
readrc = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
409
/* subzero, this would've blocked */
411
break; /* get out of loop */
413
/* get the CURLcode from the int */
414
result = (CURLcode)readrc;
420
/* read nothing but since we wanted nothing we consider this an OK
421
situation to proceed from */
426
if((k->bytecount == 0) && (k->writebytecount == 0)) {
427
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
428
if(k->exp100 > EXP100_SEND_DATA)
429
/* set time stamp to compare with when waiting for the 100 */
430
k->start100 = Curl_tvnow();
433
didwhat |= KEEP_READ;
434
/* indicates data of zero size, i.e. empty file */
435
is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
437
/* NULL terminate, allowing string ops to be used */
438
if(0 < nread || is_empty_data) {
441
else if(0 >= nread) {
442
/* if we receive 0 or less here, the server closed the connection
443
and we bail out from this! */
444
DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
445
k->keepon &= ~KEEP_READ;
449
/* Default buffer to use when we write the buffer, it may be changed
450
in the flow below before the actual storing is done. */
453
/* Since this is a two-state thing, we check if we are parsing
454
headers at the moment or not. */
456
/* we are in parse-the-header-mode */
457
bool stop_reading = FALSE;
459
/* header line within buffer loop */
466
/* str_start is start of line within buf */
467
k->str_start = k->str;
469
/* data is in network encoding so use 0x0a instead of '\n' */
470
k->end_ptr = memchr(k->str_start, 0x0a, nread);
473
/* Not a complete header line within buffer, append the data to
474
the end of the headerbuff. */
476
if(k->hbuflen + nread >= data->state.headersize) {
477
/* We enlarge the header buffer as it is too small */
479
size_t newsize=CURLMAX((k->hbuflen+nread)*3/2,
480
data->state.headersize*2);
481
hbufp_index = k->hbufp - data->state.headerbuff;
482
newbuff = (char *)realloc(data->state.headerbuff, newsize);
484
failf (data, "Failed to alloc memory for big header!");
485
return CURLE_OUT_OF_MEMORY;
487
data->state.headersize=newsize;
488
data->state.headerbuff = newbuff;
489
k->hbufp = data->state.headerbuff + hbufp_index;
491
memcpy(k->hbufp, k->str, nread);
494
if(!k->headerline && (k->hbuflen>5)) {
495
/* make a first check that this looks like a HTTP header */
496
if(!checkhttpprefix(data, data->state.headerbuff)) {
497
/* this is not the beginning of a HTTP first header line */
499
k->badheader = HEADER_ALLBAD;
504
break; /* read more and try again */
507
/* decrease the size of the remaining (supposed) header line */
508
rest_length = (k->end_ptr - k->str)+1;
509
nread -= (ssize_t)rest_length;
511
k->str = k->end_ptr + 1; /* move past new line */
513
full_length = k->str - k->str_start;
516
* We're about to copy a chunk of data to the end of the
517
* already received header. We make sure that the full string
518
* fit in the allocated header buffer, or else we enlarge
521
if(k->hbuflen + full_length >=
522
data->state.headersize) {
524
size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
525
data->state.headersize*2);
526
hbufp_index = k->hbufp - data->state.headerbuff;
527
newbuff = (char *)realloc(data->state.headerbuff, newsize);
529
failf (data, "Failed to alloc memory for big header!");
530
return CURLE_OUT_OF_MEMORY;
532
data->state.headersize= newsize;
533
data->state.headerbuff = newbuff;
534
k->hbufp = data->state.headerbuff + hbufp_index;
537
/* copy to end of line */
538
memcpy(k->hbufp, k->str_start, full_length);
539
k->hbufp += full_length;
540
k->hbuflen += full_length;
542
k->end_ptr = k->hbufp;
544
k->p = data->state.headerbuff;
547
* We now have a FULL header line that p points to
551
/* the first read header */
553
!checkhttpprefix(data, data->state.headerbuff)) {
554
/* this is not the beginning of a HTTP first header line */
557
/* since there's more, this is a partial bad header */
558
k->badheader = HEADER_PARTHEADER;
560
/* this was all we read so its all a bad header */
561
k->badheader = HEADER_ALLBAD;
562
nread = (ssize_t)rest_length;
568
/* headers are in network encoding so
569
use 0x0a and 0x0d instead of '\n' and '\r' */
570
if((0x0a == *k->p) || (0x0d == *k->p)) {
572
/* Zero-length header line means end of headers! */
574
#ifdef CURL_DOES_CONVERSIONS
576
*k->p = '\r'; /* replace with CR in host encoding */
577
k->p++; /* pass the CR byte */
580
*k->p = '\n'; /* replace with LF in host encoding */
581
k->p++; /* pass the LF byte */
585
k->p++; /* pass the \r byte */
587
k->p++; /* pass the \n byte */
588
#endif /* CURL_DOES_CONVERSIONS */
590
if(100 == k->httpcode) {
592
* We have made a HTTP PUT or POST and this is 1.1-lingo
593
* that tells us that the server is OK with this and ready
594
* to receive the data.
595
* However, we'll get more headers now so we must get
596
* back into the header-parsing state!
599
k->headerline = 0; /* restart the header line counter */
601
/* if we did wait for this do enable write now! */
603
k->exp100 = EXP100_SEND_DATA;
604
k->keepon |= KEEP_WRITE;
608
k->header = FALSE; /* no more header to parse! */
610
if((k->size == -1) && !k->chunk && !conn->bits.close &&
611
(k->httpversion >= 11) ) {
612
/* On HTTP 1.1, when connection is not to get closed, but no
613
Content-Length nor Content-Encoding chunked have been
614
received, according to RFC2616 section 4.4 point 5, we
615
assume that the server will close the connection to
616
signal the end of the document. */
617
infof(data, "no chunk, no close, no size. Assume close to "
619
conn->bits.close = TRUE;
623
if(417 == k->httpcode) {
625
* we got: "417 Expectation Failed" this means:
626
* we have made a HTTP call and our Expect Header
627
* seems to cause a problem => abort the write operations
628
* (or prevent them from starting).
630
k->exp100 = EXP100_FAILED;
631
k->keepon &= ~KEEP_WRITE;
634
#ifndef CURL_DISABLE_HTTP
636
* When all the headers have been parsed, see if we should give
637
* up and return an error.
639
if(Curl_http_should_fail(conn)) {
640
failf (data, "The requested URL returned error: %d",
642
return CURLE_HTTP_RETURNED_ERROR;
644
#endif /* CURL_DISABLE_HTTP */
646
/* now, only output this if the header AND body are requested:
648
writetype = CLIENTWRITE_HEADER;
649
if(data->set.include_header)
650
writetype |= CLIENTWRITE_BODY;
652
headerlen = k->p - data->state.headerbuff;
654
result = Curl_client_write(conn, writetype,
655
data->state.headerbuff,
660
data->info.header_size += (long)headerlen;
661
data->req.headerbytecount += (long)headerlen;
663
data->req.deductheadercount =
664
(100 == k->httpcode)?data->req.headerbytecount:0;
666
if(data->state.resume_from &&
667
(data->set.httpreq==HTTPREQ_GET) &&
668
(k->httpcode == 416)) {
669
/* "Requested Range Not Satisfiable" */
673
#ifndef CURL_DISABLE_HTTP
675
/* Curl_http_auth_act() checks what authentication methods
676
* that are available and decides which one (if any) to
677
* use. It will set 'newurl' if an auth metod was picked. */
678
result = Curl_http_auth_act(conn);
683
if(conn->bits.rewindaftersend) {
684
/* We rewind after a complete send, so thus we continue
686
infof(data, "Keep sending data to get tossed away!\n");
687
k->keepon |= KEEP_WRITE;
690
#endif /* CURL_DISABLE_HTTP */
694
* really end-of-headers.
696
* If we requested a "no body", this is a good time to get
697
* out and return home.
699
if(data->set.opt_no_body)
702
/* If we know the expected size of this document, we set the
703
maximum download size to the size of the expected
704
document or else, we won't know when to stop reading!
706
Note that we set the download maximum even if we read a
707
"Connection: close" header, to make sure that
708
"Content-Length: 0" still prevents us from attempting to
709
read the (missing) response-body.
711
/* According to RFC2616 section 4.4, we MUST ignore
712
Content-Length: headers if we are now receiving data
713
using chunked Transfer-Encoding.
720
/* We do this operation even if no_body is true, since this
721
data might be retrieved later with curl_easy_getinfo()
722
and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
724
Curl_pgrsSetDownloadSize(data, k->size);
725
k->maxdownload = k->size;
727
/* If max download size is *zero* (nothing) we already
728
have nothing and can safely return ok now! */
729
if(0 == k->maxdownload)
733
/* we make sure that this socket isn't read more now */
734
k->keepon &= ~KEEP_READ;
737
if(data->set.verbose)
738
Curl_debug(data, CURLINFO_HEADER_IN,
739
k->str_start, headerlen, conn);
740
break; /* exit header line loop */
743
/* We continue reading headers, so reset the line-based
744
header parsing variables hbufp && hbuflen */
745
k->hbufp = data->state.headerbuff;
751
* Checks for special headers coming up.
754
if(!k->headerline++) {
755
/* This is the first header, it MUST be the error code line
756
or else we consider this to be the body right away! */
757
int httpversion_major;
759
#ifdef CURL_DOES_CONVERSIONS
760
#define HEADER1 scratch
761
#define SCRATCHSIZE 21
763
char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
764
/* We can't really convert this yet because we
765
don't know if it's the 1st header line or the body.
766
So we do a partial conversion into a scratch area,
767
leaving the data at k->p as-is.
769
strncpy(&scratch[0], k->p, SCRATCHSIZE);
770
scratch[SCRATCHSIZE] = 0; /* null terminate */
771
res = Curl_convert_from_network(data,
774
if(CURLE_OK != res) {
775
/* Curl_convert_from_network calls failf if unsuccessful */
779
#define HEADER1 k->p /* no conversion needed, just use k->p */
780
#endif /* CURL_DOES_CONVERSIONS */
788
k->httpversion += 10 * httpversion_major;
791
/* this is the real world, not a Nirvana
792
NCSA 1.5.x returns this crap when asked for HTTP/1.1
794
nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
797
/* If user has set option HTTP200ALIASES,
798
compare header line against list of aliases
801
if(checkhttpprefix(data, k->p)) {
810
data->info.httpcode = k->httpcode;
811
data->info.httpversion = k->httpversion;
814
* This code executes as part of processing the header. As a
815
* result, it's not totally clear how to interpret the
816
* response code yet as that depends on what other headers may
817
* be present. 401 and 407 may be errors, but may be OK
818
* depending on how authentication is working. Other codes
819
* are definitely errors, so give up here.
821
if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
822
((k->httpcode != 401) || !conn->bits.user_passwd) &&
823
((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
825
if(data->state.resume_from &&
826
(data->set.httpreq==HTTPREQ_GET) &&
827
(k->httpcode == 416)) {
828
/* "Requested Range Not Satisfiable", just proceed and
829
pretend this is no error */
832
/* serious error, go home! */
833
failf (data, "The requested URL returned error: %d",
835
return CURLE_HTTP_RETURNED_ERROR;
839
if(k->httpversion == 10) {
840
/* Default action for HTTP/1.0 must be to close, unless
841
we get one of those fancy headers that tell us the
842
server keeps it open for us! */
843
infof(data, "HTTP 1.0, assume close after body\n");
844
conn->bits.close = TRUE;
846
else if(k->httpversion >= 11 &&
848
/* If HTTP version is >= 1.1 and connection is persistent
849
server supports pipelining. */
851
"HTTP 1.1 or later with persistent connection, "
852
"pipelining supported\n"));
853
conn->server_supports_pipelining = TRUE;
856
switch(k->httpcode) {
858
/* (quote from RFC2616, section 10.2.5): The server has
859
* fulfilled the request but does not need to return an
860
* entity-body ... The 204 response MUST NOT include a
861
* message-body, and thus is always terminated by the first
862
* empty line after the header fields. */
864
case 416: /* Requested Range Not Satisfiable, it has the
865
Content-Length: set as the "real" document but no
866
actual response is sent. */
868
/* (quote from RFC2616, section 10.3.5): The 304 response
869
* MUST NOT contain a message-body, and thus is always
870
* terminated by the first empty line after the header
874
k->ignorecl = TRUE; /* ignore Content-Length headers */
882
k->header = FALSE; /* this is not a header line */
887
#ifdef CURL_DOES_CONVERSIONS
888
/* convert from the network encoding */
889
result = Curl_convert_from_network(data, k->p, strlen(k->p));
890
if(CURLE_OK != result) {
893
/* Curl_convert_from_network calls failf if unsuccessful */
894
#endif /* CURL_DOES_CONVERSIONS */
896
/* Check for Content-Length: header lines to get size. Ignore
897
the header completely if we get a 416 response as then we're
898
resuming a document that we don't get, and this header contains
899
info about the true size of the document we didn't get now. */
900
if(!k->ignorecl && !data->set.ignorecl &&
901
checkprefix("Content-Length:", k->p)) {
902
contentlength = curlx_strtoofft(k->p+15, NULL, 10);
903
if(data->set.max_filesize &&
904
contentlength > data->set.max_filesize) {
905
failf(data, "Maximum file size exceeded");
906
return CURLE_FILESIZE_EXCEEDED;
908
if(contentlength >= 0) {
909
k->size = contentlength;
910
k->maxdownload = k->size;
911
/* we set the progress download size already at this point
912
just to make it easier for apps/callbacks to extract this
913
info as soon as possible */
914
Curl_pgrsSetDownloadSize(data, k->size);
917
/* Negative Content-Length is really odd, and we know it
918
happens for example when older Apache servers send large
920
conn->bits.close = TRUE;
921
infof(data, "Negative content-length: %" FORMAT_OFF_T
922
", closing after transfer\n", contentlength);
925
/* check for Content-Type: header lines to get the mime-type */
926
else if(checkprefix("Content-Type:", k->p)) {
931
/* Find the first non-space letter */
933
*start && ISSPACE(*start);
937
/* data is now in the host encoding so
938
use '\r' and '\n' instead of 0x0d and 0x0a */
939
end = strchr(start, '\r');
941
end = strchr(start, '\n');
944
/* skip all trailing space letters */
945
for(; ISSPACE(*end) && (end > start); end--)
948
/* get length of the type */
951
/* allocate memory of a cloned copy */
952
Curl_safefree(data->info.contenttype);
954
data->info.contenttype = malloc(len + 1);
955
if(NULL == data->info.contenttype)
956
return CURLE_OUT_OF_MEMORY;
958
/* copy the content-type string */
959
memcpy(data->info.contenttype, start, len);
960
data->info.contenttype[len] = 0; /* zero terminate */
963
#ifndef CURL_DISABLE_HTTP
964
else if((k->httpversion == 10) &&
965
conn->bits.httpproxy &&
966
Curl_compareheader(k->p,
967
"Proxy-Connection:", "keep-alive")) {
969
* When a HTTP/1.0 reply comes when using a proxy, the
970
* 'Proxy-Connection: keep-alive' line tells us the
971
* connection will be kept alive for our pleasure.
972
* Default action for 1.0 is to close.
974
conn->bits.close = FALSE; /* don't close when done */
975
infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
977
else if((k->httpversion == 11) &&
978
conn->bits.httpproxy &&
979
Curl_compareheader(k->p,
980
"Proxy-Connection:", "close")) {
982
* We get a HTTP/1.1 response from a proxy and it says it'll
983
* close down after this transfer.
985
conn->bits.close = TRUE; /* close when done */
986
infof(data, "HTTP/1.1 proxy connection set close!\n");
988
else if((k->httpversion == 10) &&
989
Curl_compareheader(k->p, "Connection:", "keep-alive")) {
991
* A HTTP/1.0 reply with the 'Connection: keep-alive' line
992
* tells us the connection will be kept alive for our
993
* pleasure. Default action for 1.0 is to close.
995
* [RFC2068, section 19.7.1] */
996
conn->bits.close = FALSE; /* don't close when done */
997
infof(data, "HTTP/1.0 connection set to keep alive!\n");
999
else if(Curl_compareheader(k->p, "Connection:", "close")) {
1001
* [RFC 2616, section 8.1.2.1]
1002
* "Connection: close" is HTTP/1.1 language and means that
1003
* the connection will close when this request has been
1006
conn->bits.close = TRUE; /* close when done */
1008
else if(Curl_compareheader(k->p,
1009
"Transfer-Encoding:", "chunked")) {
1011
* [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
1012
* means that the server will send a series of "chunks". Each
1013
* chunk starts with line with info (including size of the
1014
* coming block) (terminated with CRLF), then a block of data
1015
* with the previously mentioned size. There can be any amount
1016
* of chunks, and a chunk-data set to zero signals the
1018
k->chunk = TRUE; /* chunks coming our way */
1020
/* init our chunky engine */
1021
Curl_httpchunk_init(conn);
1024
else if(checkprefix("Trailer:", k->p) ||
1025
checkprefix("Trailers:", k->p)) {
1027
* This test helps Curl_httpchunk_read() to determine to look
1028
* for well formed trailers after the zero chunksize record. In
1029
* this case a CRLF is required after the zero chunksize record
1030
* when no trailers are sent, or after the last trailer record.
1032
* It seems both Trailer: and Trailers: occur in the wild.
1034
k->trailerhdrpresent = TRUE;
1037
else if(checkprefix("Content-Encoding:", k->p) &&
1038
data->set.str[STRING_ENCODING]) {
1040
* Process Content-Encoding. Look for the values: identity,
1041
* gzip, deflate, compress, x-gzip and x-compress. x-gzip and
1042
* x-compress are the same as gzip and compress. (Sec 3.5 RFC
1043
* 2616). zlib cannot handle compress. However, errors are
1044
* handled further down when the response body is processed
1048
/* Find the first non-space letter */
1050
*start && ISSPACE(*start);
1054
/* Record the content-encoding for later use */
1055
if(checkprefix("identity", start))
1056
k->content_encoding = IDENTITY;
1057
else if(checkprefix("deflate", start))
1058
k->content_encoding = DEFLATE;
1059
else if(checkprefix("gzip", start)
1060
|| checkprefix("x-gzip", start))
1061
k->content_encoding = GZIP;
1062
else if(checkprefix("compress", start)
1063
|| checkprefix("x-compress", start))
1064
k->content_encoding = COMPRESS;
1066
else if(checkprefix("Content-Range:", k->p)) {
1067
/* Content-Range: bytes [num]-
1068
Content-Range: bytes: [num]-
1069
Content-Range: [num]-
1071
The second format was added since Sun's webserver
1072
JavaWebServer/1.1.1 obviously sends the header this way!
1073
The third added since some servers use that!
1076
char *ptr = k->p + 14;
1078
/* Move forward until first digit */
1079
while(*ptr && !ISDIGIT(*ptr))
1082
k->offset = curlx_strtoofft(ptr, NULL, 10);
1084
if(data->state.resume_from == k->offset)
1085
/* we asked for a resume and we got it */
1086
k->content_range = TRUE;
1088
#if !defined(CURL_DISABLE_COOKIES)
1089
else if(data->cookies &&
1090
checkprefix("Set-Cookie:", k->p)) {
1091
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
1092
CURL_LOCK_ACCESS_SINGLE);
1093
Curl_cookie_add(data,
1094
data->cookies, TRUE, k->p+11,
1095
/* If there is a custom-set Host: name, use it
1096
here, or else use real peer host name. */
1097
conn->allocptr.cookiehost?
1098
conn->allocptr.cookiehost:conn->host.name,
1100
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1103
else if(checkprefix("Last-Modified:", k->p) &&
1104
(data->set.timecondition || data->set.get_filetime) ) {
1105
time_t secs=time(NULL);
1106
k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
1108
if(data->set.get_filetime)
1109
data->info.filetime = (long)k->timeofdoc;
1111
else if((checkprefix("WWW-Authenticate:", k->p) &&
1112
(401 == k->httpcode)) ||
1113
(checkprefix("Proxy-authenticate:", k->p) &&
1114
(407 == k->httpcode))) {
1115
result = Curl_http_input_auth(conn, k->httpcode, k->p);
1119
else if((k->httpcode >= 300 && k->httpcode < 400) &&
1120
checkprefix("Location:", k->p)) {
1121
/* this is the URL that the server advices us to use instead */
1126
start += 9; /* pass "Location:" */
1128
/* Skip spaces and tabs. We do this to support multiple
1129
white spaces after the "Location:" keyword. */
1130
while(*start && ISSPACE(*start ))
1133
/* Scan through the string from the end to find the last
1134
non-space. k->end_ptr points to the actual terminating zero
1135
letter, move pointer one letter back and start from
1136
there. This logic strips off trailing whitespace, but keeps
1137
any embedded whitespace. */
1139
while((ptr>=start) && ISSPACE(*ptr))
1143
backup = *ptr; /* store the ending letter */
1145
*ptr = '\0'; /* zero terminate */
1146
data->req.location = strdup(start); /* clone string */
1147
*ptr = backup; /* restore ending letter */
1148
if(!data->req.location)
1149
return CURLE_OUT_OF_MEMORY;
1150
if(data->set.http_follow_location) {
1151
data->req.newurl = strdup(data->req.location); /* clone */
1152
if(!data->req.newurl)
1153
return CURLE_OUT_OF_MEMORY;
1157
#endif /* CURL_DISABLE_HTTP */
1160
* End of header-checks. Write them to the client.
1163
writetype = CLIENTWRITE_HEADER;
1164
if(data->set.include_header)
1165
writetype |= CLIENTWRITE_BODY;
1167
if(data->set.verbose)
1168
Curl_debug(data, CURLINFO_HEADER_IN,
1169
k->p, (size_t)k->hbuflen, conn);
1171
result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
1175
data->info.header_size += (long)k->hbuflen;
1176
data->req.headerbytecount += (long)k->hbuflen;
1178
/* reset hbufp pointer && hbuflen */
1179
k->hbufp = data->state.headerbuff;
1182
while(!stop_reading && *k->str); /* header line within buffer */
1185
/* We've stopped dealing with input, get out of the do-while loop */
1188
/* We might have reached the end of the header part here, but
1189
there might be a non-header part left in the end of the read
1192
} /* end if header mode */
1194
/* This is not an 'else if' since it may be a rest from the header
1195
parsing, where the beginning of the buffer is headers and the end
1197
if(k->str && !k->header && (nread > 0 || is_empty_data)) {
1199
if(0 == k->bodywrites && !is_empty_data) {
1200
/* These checks are only made the first time we are about to
1201
write a piece of the body */
1202
if(conn->protocol&PROT_HTTP) {
1203
/* HTTP-only checks */
1205
if(data->req.newurl) {
1206
if(conn->bits.close) {
1207
/* Abort after the headers if "follow Location" is set
1208
and we're set to close anyway. */
1209
k->keepon &= ~KEEP_READ;
1213
/* We have a new url to load, but since we want to be able
1214
to re-use this connection properly, we read the full
1215
response in "ignore more" */
1216
k->ignorebody = TRUE;
1217
infof(data, "Ignoring the response-body\n");
1219
if(data->state.resume_from && !k->content_range &&
1220
(data->set.httpreq==HTTPREQ_GET) &&
1222
/* we wanted to resume a download, although the server doesn't
1223
* seem to support this and we did this with a GET (if it
1224
* wasn't a GET we did a POST or PUT resume) */
1225
failf(data, "HTTP server doesn't seem to support "
1226
"byte ranges. Cannot resume.");
1227
return CURLE_RANGE_ERROR;
1230
if(data->set.timecondition && !data->state.range) {
1231
/* A time condition has been set AND no ranges have been
1232
requested. This seems to be what chapter 13.3.4 of
1233
RFC 2616 defines to be the correct action for a
1235
if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
1236
switch(data->set.timecondition) {
1237
case CURL_TIMECOND_IFMODSINCE:
1239
if(k->timeofdoc < data->set.timevalue) {
1241
"The requested document is not new enough\n");
1246
case CURL_TIMECOND_IFUNMODSINCE:
1247
if(k->timeofdoc > data->set.timevalue) {
1249
"The requested document is not old enough\n");
1255
} /* two valid time strings */
1256
} /* we have a time condition */
1258
} /* this is HTTP */
1259
} /* this is the first time we write a body part */
1262
/* pass data to the debug function before it gets "dechunked" */
1263
if(data->set.verbose) {
1265
Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
1266
(size_t)k->hbuflen, conn);
1267
if(k->badheader == HEADER_PARTHEADER)
1268
Curl_debug(data, CURLINFO_DATA_IN,
1269
k->str, (size_t)nread, conn);
1272
Curl_debug(data, CURLINFO_DATA_IN,
1273
k->str, (size_t)nread, conn);
1276
#ifndef CURL_DISABLE_HTTP
1279
* Here comes a chunked transfer flying and we need to decode this
1280
* properly. While the name says read, this function both reads
1281
* and writes away the data. The returned 'nread' holds the number
1282
* of actual data it wrote to the client.
1286
Curl_httpchunk_read(conn, k->str, nread, &nread);
1288
if(CHUNKE_OK < res) {
1289
if(CHUNKE_WRITE_ERROR == res) {
1290
failf(data, "Failed writing data");
1291
return CURLE_WRITE_ERROR;
1293
failf(data, "Received problem %d in the chunky parser", res);
1294
return CURLE_RECV_ERROR;
1296
else if(CHUNKE_STOP == res) {
1298
/* we're done reading chunks! */
1299
k->keepon &= ~KEEP_READ; /* read no more */
1301
/* There are now possibly N number of bytes at the end of the
1302
str buffer that weren't written to the client.
1304
We DO care about this data if we are pipelining.
1305
Push it back to be read on the next pass. */
1307
dataleft = conn->chunk.dataleft;
1309
infof(conn->data, "Leftovers after chunking. "
1310
" Rewinding %d bytes\n",dataleft);
1311
read_rewind(conn, dataleft);
1314
/* If it returned OK, we just keep going */
1316
#endif /* CURL_DISABLE_HTTP */
1318
if((-1 != k->maxdownload) &&
1319
(k->bytecount + nread >= k->maxdownload)) {
1320
/* The 'excess' amount below can't be more than BUFSIZE which
1321
always will fit in a size_t */
1322
size_t excess = (size_t)(k->bytecount + nread - k->maxdownload);
1323
if(excess > 0 && !k->ignorebody) {
1325
"Rewinding stream by : %d"
1326
" bytes on url %s (size = %" FORMAT_OFF_T
1327
", maxdownload = %" FORMAT_OFF_T
1328
", bytecount = %" FORMAT_OFF_T ", nread = %d)\n",
1329
excess, data->state.path,
1330
k->size, k->maxdownload, k->bytecount, nread);
1331
read_rewind(conn, excess);
1334
nread = (ssize_t) (k->maxdownload - k->bytecount);
1335
if(nread < 0 ) /* this should be unusual */
1338
k->keepon &= ~KEEP_READ; /* we're done reading */
1341
k->bytecount += nread;
1343
Curl_pgrsSetDownloadCounter(data, k->bytecount);
1345
if(!k->chunk && (nread || k->badheader || is_empty_data)) {
1346
/* If this is chunky transfer, it was already written */
1348
if(k->badheader && !k->ignorebody) {
1349
/* we parsed a piece of data wrongly assuming it was a header
1350
and now we output it as body instead */
1351
result = Curl_client_write(conn, CLIENTWRITE_BODY,
1352
data->state.headerbuff,
1357
if(k->badheader < HEADER_ALLBAD) {
1358
/* This switch handles various content encodings. If there's an
1359
error here, be sure to check over the almost identical code
1361
Make sure that ALL_CONTENT_ENCODINGS contains all the
1362
encodings handled here. */
1364
switch (conn->data->set.http_ce_skip ?
1365
IDENTITY : k->content_encoding) {
1368
/* This is the default when the server sends no
1369
Content-Encoding header. See Curl_readwrite_init; the
1370
memset() call initializes k->content_encoding to zero. */
1372
result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
1378
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
1380
result = Curl_unencode_deflate_write(conn, k, nread);
1384
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
1386
result = Curl_unencode_gzip_write(conn, k, nread);
1391
failf (data, "Unrecognized content encoding type. "
1392
"libcurl understands `identity', `deflate' and `gzip' "
1393
"content encodings.");
1394
result = CURLE_BAD_CONTENT_ENCODING;
1399
k->badheader = HEADER_NORMAL; /* taken care of now */
1405
} /* if(! header and data to read ) */
1408
/* if we received nothing, the server closed the connection and we
1410
k->keepon &= ~KEEP_READ;
1413
} while(data_pending(conn));
1415
} /* if( read from socket ) */
1616
result = readwrite_data(data, conn, k, &didwhat, done);
1417
1621
/* If we still have writing to do, we check if we have a writable socket. */
1418
1622
if((k->keepon & KEEP_WRITE) && (select_res & CURL_CSELECT_OUT)) {
1422
ssize_t bytes_written;
1424
if((k->bytecount == 0) && (k->writebytecount == 0))
1425
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
1427
didwhat |= KEEP_WRITE;
1430
* We loop here to do the READ and SEND loop until we run out of
1431
* data to send or until we get EWOULDBLOCK back
1435
/* only read more data if there's no upload data already
1436
present in the upload buffer */
1437
if(0 == data->req.upload_present) {
1438
/* init the "upload from here" pointer */
1439
data->req.upload_fromhere = k->uploadbuf;
1441
if(!k->upload_done) {
1442
/* HTTP pollution, this should be written nicer to become more
1443
protocol agnostic. */
1446
if((k->exp100 == EXP100_SENDING_REQUEST) &&
1447
(data->state.proto.http->sending == HTTPSEND_BODY)) {
1448
/* If this call is to send body data, we must take some action:
1449
We have sent off the full HTTP 1.1 request, and we shall now
1450
go into the Expect: 100 state and await such a header */
1451
k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
1452
k->keepon &= ~KEEP_WRITE; /* disable writing */
1453
k->start100 = Curl_tvnow(); /* timeout count starts now */
1454
didwhat &= ~KEEP_WRITE; /* we didn't write anything actually */
1458
result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
1462
nread = (ssize_t)fillcount;
1465
nread = 0; /* we're done uploading/reading */
1467
if(!nread && (k->keepon & KEEP_READ_PAUSE)) {
1468
/* this is a paused transfer */
1473
k->keepon &= ~KEEP_WRITE; /* we're done writing */
1475
if(conn->bits.rewindaftersend) {
1476
result = Curl_readrewind(conn);
1483
/* store number of bytes available for upload */
1484
data->req.upload_present = nread;
1486
/* convert LF to CRLF if so asked */
1487
#ifdef CURL_DO_LINEEND_CONV
1488
/* always convert if we're FTPing in ASCII mode */
1489
if((data->set.crlf) || (data->set.prefer_ascii))
1492
#endif /* CURL_DO_LINEEND_CONV */
1494
if(data->state.scratch == NULL)
1495
data->state.scratch = malloc(2*BUFSIZE);
1496
if(data->state.scratch == NULL) {
1497
failf (data, "Failed to alloc scratch buffer!");
1498
return CURLE_OUT_OF_MEMORY;
1501
* ASCII/EBCDIC Note: This is presumably a text (not binary)
1502
* transfer so the data should already be in ASCII.
1503
* That means the hex values for ASCII CR (0x0d) & LF (0x0a)
1504
* must be used instead of the escape sequences \r & \n.
1506
for(i = 0, si = 0; i < nread; i++, si++) {
1507
if(data->req.upload_fromhere[i] == 0x0a) {
1508
data->state.scratch[si++] = 0x0d;
1509
data->state.scratch[si] = 0x0a;
1510
if(!data->set.crlf) {
1511
/* we're here only because FTP is in ASCII mode...
1512
bump infilesize for the LF we just added */
1513
data->set.infilesize++;
1517
data->state.scratch[si] = data->req.upload_fromhere[i];
1520
/* only perform the special operation if we really did replace
1524
/* upload from the new (replaced) buffer instead */
1525
data->req.upload_fromhere = data->state.scratch;
1527
/* set the new amount too */
1528
data->req.upload_present = nread;
1531
} /* if 0 == data->req.upload_present */
1533
/* We have a partial buffer left from a previous "round". Use
1534
that instead of reading more data */
1537
/* write to socket (send away data) */
1538
result = Curl_write(conn,
1539
conn->writesockfd, /* socket to send to */
1540
data->req.upload_fromhere, /* buffer pointer */
1541
data->req.upload_present, /* buffer size */
1542
&bytes_written); /* actually send away */
1546
if(data->set.verbose)
1547
/* show the data before we change the pointer upload_fromhere */
1548
Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
1549
(size_t)bytes_written, conn);
1551
if(data->req.upload_present != bytes_written) {
1552
/* we only wrote a part of the buffer (if anything), deal with it! */
1554
/* store the amount of bytes left in the buffer to write */
1555
data->req.upload_present -= bytes_written;
1557
/* advance the pointer where to find the buffer when the next send
1559
data->req.upload_fromhere += bytes_written;
1562
/* we've uploaded that buffer now */
1563
data->req.upload_fromhere = k->uploadbuf;
1564
data->req.upload_present = 0; /* no more bytes left */
1566
if(k->upload_done) {
1567
/* switch off writing, we're done! */
1568
k->keepon &= ~KEEP_WRITE; /* we're done writing */
1572
k->writebytecount += bytes_written;
1573
Curl_pgrsSetUploadCounter(data, k->writebytecount);
1575
} while(0); /* just to break out from! */
1577
} /* if(something to write) */
1625
result = readwrite_upload(data, conn, k, &didwhat);
1579
1630
k->now = Curl_tvnow();