409
* Go ahead and do a read if we have a readable socket or if
410
* the stream was rewound (in which case we have data in a
413
static CURLcode readwrite_data(struct SessionHandle *data,
414
struct connectdata *conn,
415
struct SingleRequest *k,
416
int *didwhat, bool *done)
418
CURLcode result = CURLE_OK;
419
ssize_t nread; /* number of bytes read */
420
bool is_empty_data = FALSE;
424
/* This is where we loop until we have read everything there is to
425
read or we get a EWOULDBLOCK */
427
size_t buffersize = data->set.buffer_size?
428
data->set.buffer_size : BUFSIZE;
429
size_t bytestoread = buffersize;
432
if(k->size != -1 && !k->header) {
433
/* make sure we don't read "too much" if we can help it since we
434
might be pipelining and then someone else might want to read what
436
curl_off_t totalleft = k->size - k->bytecount;
437
if(totalleft < (curl_off_t)bytestoread)
438
bytestoread = (size_t)totalleft;
442
/* receive data from the network! */
443
readrc = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
445
/* subzero, this would've blocked */
447
break; /* get out of loop */
449
/* get the CURLcode from the int */
450
result = (CURLcode)readrc;
456
/* read nothing but since we wanted nothing we consider this an OK
457
situation to proceed from */
461
if((k->bytecount == 0) && (k->writebytecount == 0)) {
462
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
463
if(k->exp100 > EXP100_SEND_DATA)
464
/* set time stamp to compare with when waiting for the 100 */
465
k->start100 = Curl_tvnow();
468
*didwhat |= KEEP_RECV;
469
/* indicates data of zero size, i.e. empty file */
470
is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
472
/* NUL terminate, allowing string ops to be used */
473
if(0 < nread || is_empty_data) {
476
else if(0 >= nread) {
477
/* if we receive 0 or less here, the server closed the connection
478
and we bail out from this! */
479
DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
480
k->keepon &= ~KEEP_RECV;
484
/* Default buffer to use when we write the buffer, it may be changed
485
in the flow below before the actual storing is done. */
488
#ifndef CURL_DISABLE_HTTP
489
/* Since this is a two-state thing, we check if we are parsing
490
headers at the moment or not. */
492
/* we are in parse-the-header-mode */
493
bool stop_reading = FALSE;
494
result = readwrite_http_headers(data, conn, k, &nread, &stop_reading);
498
/* We've stopped dealing with input, get out of the do-while loop */
501
#endif /* CURL_DISABLE_HTTP */
504
/* This is not an 'else if' since it may be a rest from the header
505
parsing, where the beginning of the buffer is headers and the end
507
if(k->str && !k->header && (nread > 0 || is_empty_data)) {
509
#ifndef CURL_DISABLE_HTTP
510
if(0 == k->bodywrites && !is_empty_data) {
511
/* These checks are only made the first time we are about to
512
write a piece of the body */
513
if(conn->protocol&PROT_HTTP) {
514
/* HTTP-only checks */
516
if(data->req.newurl) {
517
if(conn->bits.close) {
518
/* Abort after the headers if "follow Location" is set
519
and we're set to close anyway. */
520
k->keepon &= ~KEEP_RECV;
524
/* We have a new url to load, but since we want to be able
525
to re-use this connection properly, we read the full
526
response in "ignore more" */
527
k->ignorebody = TRUE;
528
infof(data, "Ignoring the response-body\n");
530
if(data->state.resume_from && !k->content_range &&
531
(data->set.httpreq==HTTPREQ_GET) &&
533
/* we wanted to resume a download, although the server doesn't
534
* seem to support this and we did this with a GET (if it
535
* wasn't a GET we did a POST or PUT resume) */
536
failf(data, "HTTP server doesn't seem to support "
537
"byte ranges. Cannot resume.");
538
return CURLE_RANGE_ERROR;
541
if(data->set.timecondition && !data->state.range) {
542
/* A time condition has been set AND no ranges have been
543
requested. This seems to be what chapter 13.3.4 of
544
RFC 2616 defines to be the correct action for a
546
if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
547
switch(data->set.timecondition) {
548
case CURL_TIMECOND_IFMODSINCE:
550
if(k->timeofdoc < data->set.timevalue) {
552
"The requested document is not new enough\n");
554
data->info.timecond = TRUE;
558
case CURL_TIMECOND_IFUNMODSINCE:
559
if(k->timeofdoc > data->set.timevalue) {
561
"The requested document is not old enough\n");
563
data->info.timecond = TRUE;
568
} /* two valid time strings */
569
} /* we have a time condition */
572
} /* this is the first time we write a body part */
573
#endif /* CURL_DISABLE_HTTP */
576
/* pass data to the debug function before it gets "dechunked" */
577
if(data->set.verbose) {
579
Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
580
(size_t)k->hbuflen, conn);
581
if(k->badheader == HEADER_PARTHEADER)
582
Curl_debug(data, CURLINFO_DATA_IN,
583
k->str, (size_t)nread, conn);
586
Curl_debug(data, CURLINFO_DATA_IN,
587
k->str, (size_t)nread, conn);
590
#ifndef CURL_DISABLE_HTTP
593
* Here comes a chunked transfer flying and we need to decode this
594
* properly. While the name says read, this function both reads
595
* and writes away the data. The returned 'nread' holds the number
596
* of actual data it wrote to the client.
600
Curl_httpchunk_read(conn, k->str, nread, &nread);
602
if(CHUNKE_OK < res) {
603
if(CHUNKE_WRITE_ERROR == res) {
604
failf(data, "Failed writing data");
605
return CURLE_WRITE_ERROR;
607
failf(data, "Received problem %d in the chunky parser", res);
608
return CURLE_RECV_ERROR;
610
else if(CHUNKE_STOP == res) {
612
/* we're done reading chunks! */
613
k->keepon &= ~KEEP_RECV; /* read no more */
615
/* There are now possibly N number of bytes at the end of the
616
str buffer that weren't written to the client.
618
We DO care about this data if we are pipelining.
619
Push it back to be read on the next pass. */
621
dataleft = conn->chunk.dataleft;
623
infof(conn->data, "Leftovers after chunking. "
624
" Rewinding %d bytes\n",dataleft);
625
read_rewind(conn, dataleft);
628
/* If it returned OK, we just keep going */
630
#endif /* CURL_DISABLE_HTTP */
632
if((-1 != k->maxdownload) &&
633
(k->bytecount + nread >= k->maxdownload)) {
634
/* The 'excess' amount below can't be more than BUFSIZE which
635
always will fit in a size_t */
636
size_t excess = (size_t)(k->bytecount + nread - k->maxdownload);
637
if(excess > 0 && !k->ignorebody) {
639
"Rewinding stream by : %d"
640
" bytes on url %s (size = %" FORMAT_OFF_T
641
", maxdownload = %" FORMAT_OFF_T
642
", bytecount = %" FORMAT_OFF_T ", nread = %d)\n",
643
excess, data->state.path,
644
k->size, k->maxdownload, k->bytecount, nread);
645
read_rewind(conn, excess);
648
nread = (ssize_t) (k->maxdownload - k->bytecount);
649
if(nread < 0 ) /* this should be unusual */
652
k->keepon &= ~KEEP_RECV; /* we're done reading */
655
k->bytecount += nread;
657
Curl_pgrsSetDownloadCounter(data, k->bytecount);
659
if(!k->chunk && (nread || k->badheader || is_empty_data)) {
660
/* If this is chunky transfer, it was already written */
662
if(k->badheader && !k->ignorebody) {
663
/* we parsed a piece of data wrongly assuming it was a header
664
and now we output it as body instead */
665
result = Curl_client_write(conn, CLIENTWRITE_BODY,
666
data->state.headerbuff,
671
if(k->badheader < HEADER_ALLBAD) {
672
/* This switch handles various content encodings. If there's an
673
error here, be sure to check over the almost identical code
675
Make sure that ALL_CONTENT_ENCODINGS contains all the
676
encodings handled here. */
678
switch (conn->data->set.http_ce_skip ?
679
IDENTITY : k->content_encoding) {
682
/* This is the default when the server sends no
683
Content-Encoding header. See Curl_readwrite_init; the
684
memset() call initializes k->content_encoding to zero. */
686
result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
692
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
694
result = Curl_unencode_deflate_write(conn, k, nread);
698
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
700
result = Curl_unencode_gzip_write(conn, k, nread);
705
failf (data, "Unrecognized content encoding type. "
706
"libcurl understands `identity', `deflate' and `gzip' "
707
"content encodings.");
708
result = CURLE_BAD_CONTENT_ENCODING;
713
k->badheader = HEADER_NORMAL; /* taken care of now */
719
} /* if(! header and data to read ) */
722
/* if we received nothing, the server closed the connection and we
724
k->keepon &= ~KEEP_RECV;
727
} while(data_pending(conn));
729
if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
731
/* When we've read the entire thing and the close bit is set, the server
732
may now close the connection. If there's now any kind of sending going
733
on from our side, we need to stop that immediately. */
734
infof(data, "we are done reading and this is set to close, stop send\n");
735
k->keepon &= ~KEEP_SEND; /* no writing anymore either */
741
#ifndef CURL_DISABLE_HTTP
743
* Read any HTTP header lines from the server and pass them to the client app.
745
static CURLcode readwrite_http_headers(struct SessionHandle *data,
746
struct connectdata *conn,
747
struct SingleRequest *k,
753
/* header line within buffer loop */
760
/* str_start is start of line within buf */
761
k->str_start = k->str;
763
/* data is in network encoding so use 0x0a instead of '\n' */
764
k->end_ptr = memchr(k->str_start, 0x0a, *nread);
767
/* Not a complete header line within buffer, append the data to
768
the end of the headerbuff. */
770
if(k->hbuflen + *nread >= data->state.headersize) {
771
/* We enlarge the header buffer as it is too small */
773
size_t newsize=CURLMAX((k->hbuflen+*nread)*3/2,
774
data->state.headersize*2);
775
hbufp_index = k->hbufp - data->state.headerbuff;
776
newbuff = realloc(data->state.headerbuff, newsize);
778
failf (data, "Failed to alloc memory for big header!");
779
return CURLE_OUT_OF_MEMORY;
781
data->state.headersize=newsize;
782
data->state.headerbuff = newbuff;
783
k->hbufp = data->state.headerbuff + hbufp_index;
785
memcpy(k->hbufp, k->str, *nread);
787
k->hbuflen += *nread;
788
if(!k->headerline && (k->hbuflen>5)) {
789
/* make a first check that this looks like a HTTP header */
790
if(!checkhttpprefix(data, data->state.headerbuff)) {
791
/* this is not the beginning of a HTTP first header line */
793
k->badheader = HEADER_ALLBAD;
798
break; /* read more and try again */
801
/* decrease the size of the remaining (supposed) header line */
802
rest_length = (k->end_ptr - k->str)+1;
803
*nread -= (ssize_t)rest_length;
805
k->str = k->end_ptr + 1; /* move past new line */
807
full_length = k->str - k->str_start;
810
* We're about to copy a chunk of data to the end of the
811
* already received header. We make sure that the full string
812
* fit in the allocated header buffer, or else we enlarge
815
if(k->hbuflen + full_length >=
816
data->state.headersize) {
818
size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
819
data->state.headersize*2);
820
hbufp_index = k->hbufp - data->state.headerbuff;
821
newbuff = realloc(data->state.headerbuff, newsize);
823
failf (data, "Failed to alloc memory for big header!");
824
return CURLE_OUT_OF_MEMORY;
826
data->state.headersize= newsize;
827
data->state.headerbuff = newbuff;
828
k->hbufp = data->state.headerbuff + hbufp_index;
831
/* copy to end of line */
832
memcpy(k->hbufp, k->str_start, full_length);
833
k->hbufp += full_length;
834
k->hbuflen += full_length;
836
k->end_ptr = k->hbufp;
838
k->p = data->state.headerbuff;
841
* We now have a FULL header line that p points to
845
/* the first read header */
847
!checkhttpprefix(data, data->state.headerbuff)) {
848
/* this is not the beginning of a HTTP first header line */
851
/* since there's more, this is a partial bad header */
852
k->badheader = HEADER_PARTHEADER;
854
/* this was all we read so it's all a bad header */
855
k->badheader = HEADER_ALLBAD;
856
*nread = (ssize_t)rest_length;
862
/* headers are in network encoding so
863
use 0x0a and 0x0d instead of '\n' and '\r' */
864
if((0x0a == *k->p) || (0x0d == *k->p)) {
866
/* Zero-length header line means end of headers! */
868
#ifdef CURL_DOES_CONVERSIONS
870
*k->p = '\r'; /* replace with CR in host encoding */
871
k->p++; /* pass the CR byte */
874
*k->p = '\n'; /* replace with LF in host encoding */
875
k->p++; /* pass the LF byte */
879
k->p++; /* pass the \r byte */
881
k->p++; /* pass the \n byte */
882
#endif /* CURL_DOES_CONVERSIONS */
884
if(100 <= k->httpcode && 199 >= k->httpcode) {
886
* We have made a HTTP PUT or POST and this is 1.1-lingo
887
* that tells us that the server is OK with this and ready
888
* to receive the data.
889
* However, we'll get more headers now so we must get
890
* back into the header-parsing state!
893
k->headerline = 0; /* restart the header line counter */
895
/* if we did wait for this do enable write now! */
897
k->exp100 = EXP100_SEND_DATA;
898
k->keepon |= KEEP_SEND;
902
k->header = FALSE; /* no more header to parse! */
904
if((k->size == -1) && !k->chunk && !conn->bits.close &&
905
(conn->httpversion >= 11) ) {
906
/* On HTTP 1.1, when connection is not to get closed, but no
907
Content-Length nor Content-Encoding chunked have been
908
received, according to RFC2616 section 4.4 point 5, we
909
assume that the server will close the connection to
910
signal the end of the document. */
911
infof(data, "no chunk, no close, no size. Assume close to "
913
conn->bits.close = TRUE;
917
if(417 == k->httpcode) {
919
* we got: "417 Expectation Failed" this means:
920
* we have made a HTTP call and our Expect Header
921
* seems to cause a problem => abort the write operations
922
* (or prevent them from starting).
924
k->exp100 = EXP100_FAILED;
925
k->keepon &= ~KEEP_SEND;
929
* When all the headers have been parsed, see if we should give
930
* up and return an error.
932
if(Curl_http_should_fail(conn)) {
933
failf (data, "The requested URL returned error: %d",
935
return CURLE_HTTP_RETURNED_ERROR;
938
/* now, only output this if the header AND body are requested:
940
writetype = CLIENTWRITE_HEADER;
941
if(data->set.include_header)
942
writetype |= CLIENTWRITE_BODY;
944
headerlen = k->p - data->state.headerbuff;
946
result = Curl_client_write(conn, writetype,
947
data->state.headerbuff,
952
data->info.header_size += (long)headerlen;
953
data->req.headerbytecount += (long)headerlen;
955
data->req.deductheadercount =
956
(100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
958
if(data->state.resume_from &&
959
(data->set.httpreq==HTTPREQ_GET) &&
960
(k->httpcode == 416)) {
961
/* "Requested Range Not Satisfiable" */
962
*stop_reading = TRUE;
966
/* Curl_http_auth_act() checks what authentication methods
967
* that are available and decides which one (if any) to
968
* use. It will set 'newurl' if an auth method was picked. */
969
result = Curl_http_auth_act(conn);
974
if(conn->bits.rewindaftersend) {
975
/* We rewind after a complete send, so thus we continue
977
infof(data, "Keep sending data to get tossed away!\n");
978
k->keepon |= KEEP_SEND;
984
* really end-of-headers.
986
* If we requested a "no body", this is a good time to get
987
* out and return home.
989
if(data->set.opt_no_body)
990
*stop_reading = TRUE;
992
/* If we know the expected size of this document, we set the
993
maximum download size to the size of the expected
994
document or else, we won't know when to stop reading!
996
Note that we set the download maximum even if we read a
997
"Connection: close" header, to make sure that
998
"Content-Length: 0" still prevents us from attempting to
999
read the (missing) response-body.
1001
/* According to RFC2616 section 4.4, we MUST ignore
1002
Content-Length: headers if we are now receiving data
1003
using chunked Transfer-Encoding.
1010
/* We do this operation even if no_body is true, since this
1011
data might be retrieved later with curl_easy_getinfo()
1012
and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
1014
Curl_pgrsSetDownloadSize(data, k->size);
1015
k->maxdownload = k->size;
1017
/* If max download size is *zero* (nothing) we already
1018
have nothing and can safely return ok now! */
1019
if(0 == k->maxdownload)
1020
*stop_reading = TRUE;
1023
/* we make sure that this socket isn't read more now */
1024
k->keepon &= ~KEEP_RECV;
1027
if(data->set.verbose)
1028
Curl_debug(data, CURLINFO_HEADER_IN,
1029
k->str_start, headerlen, conn);
1030
break; /* exit header line loop */
1033
/* We continue reading headers, so reset the line-based
1034
header parsing variables hbufp && hbuflen */
1035
k->hbufp = data->state.headerbuff;
1041
* Checks for special headers coming up.
1044
if(!k->headerline++) {
1045
/* This is the first header, it MUST be the error code line
1046
or else we consider this to be the body right away! */
1047
int httpversion_major;
1049
#ifdef CURL_DOES_CONVERSIONS
1050
#define HEADER1 scratch
1051
#define SCRATCHSIZE 21
1053
char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
1054
/* We can't really convert this yet because we
1055
don't know if it's the 1st header line or the body.
1056
So we do a partial conversion into a scratch area,
1057
leaving the data at k->p as-is.
1059
strncpy(&scratch[0], k->p, SCRATCHSIZE);
1060
scratch[SCRATCHSIZE] = 0; /* null terminate */
1061
res = Curl_convert_from_network(data,
1064
if(CURLE_OK != res) {
1065
/* Curl_convert_from_network calls failf if unsuccessful */
1069
#define HEADER1 k->p /* no conversion needed, just use k->p */
1070
#endif /* CURL_DOES_CONVERSIONS */
1072
nc = sscanf(HEADER1,
1078
conn->httpversion += 10 * httpversion_major;
1081
/* this is the real world, not a Nirvana
1082
NCSA 1.5.x returns this crap when asked for HTTP/1.1
1084
nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
1085
conn->httpversion = 10;
1087
/* If user has set option HTTP200ALIASES,
1088
compare header line against list of aliases
1091
if(checkhttpprefix(data, k->p)) {
1094
conn->httpversion = 10;
1100
data->info.httpcode = k->httpcode;
1101
data->info.httpversion = conn->httpversion;
1102
if (!data->state.httpversion ||
1103
data->state.httpversion > conn->httpversion)
1104
/* store the lowest server version we encounter */
1105
data->state.httpversion = conn->httpversion;
1108
* This code executes as part of processing the header. As a
1109
* result, it's not totally clear how to interpret the
1110
* response code yet as that depends on what other headers may
1111
* be present. 401 and 407 may be errors, but may be OK
1112
* depending on how authentication is working. Other codes
1113
* are definitely errors, so give up here.
1115
if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
1116
((k->httpcode != 401) || !conn->bits.user_passwd) &&
1117
((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
1119
if(data->state.resume_from &&
1120
(data->set.httpreq==HTTPREQ_GET) &&
1121
(k->httpcode == 416)) {
1122
/* "Requested Range Not Satisfiable", just proceed and
1123
pretend this is no error */
1126
/* serious error, go home! */
1127
failf (data, "The requested URL returned error: %d",
1129
return CURLE_HTTP_RETURNED_ERROR;
1133
if(conn->httpversion == 10) {
1134
/* Default action for HTTP/1.0 must be to close, unless
1135
we get one of those fancy headers that tell us the
1136
server keeps it open for us! */
1137
infof(data, "HTTP 1.0, assume close after body\n");
1138
conn->bits.close = TRUE;
1140
else if(conn->httpversion >= 11 &&
1141
!conn->bits.close) {
1142
/* If HTTP version is >= 1.1 and connection is persistent
1143
server supports pipelining. */
1145
"HTTP 1.1 or later with persistent connection, "
1146
"pipelining supported\n"));
1147
conn->server_supports_pipelining = TRUE;
1150
switch(k->httpcode) {
1152
/* (quote from RFC2616, section 10.2.5): The server has
1153
* fulfilled the request but does not need to return an
1154
* entity-body ... The 204 response MUST NOT include a
1155
* message-body, and thus is always terminated by the first
1156
* empty line after the header fields. */
1158
case 416: /* Requested Range Not Satisfiable, it has the
1159
Content-Length: set as the "real" document but no
1160
actual response is sent. */
1162
/* (quote from RFC2616, section 10.3.5): The 304 response
1163
* MUST NOT contain a message-body, and thus is always
1164
* terminated by the first empty line after the header
1166
if(data->set.timecondition)
1167
data->info.timecond = TRUE;
1170
k->ignorecl = TRUE; /* ignore Content-Length headers */
1178
k->header = FALSE; /* this is not a header line */
1183
#ifdef CURL_DOES_CONVERSIONS
1184
/* convert from the network encoding */
1185
result = Curl_convert_from_network(data, k->p, strlen(k->p));
1186
if(CURLE_OK != result) {
1189
/* Curl_convert_from_network calls failf if unsuccessful */
1190
#endif /* CURL_DOES_CONVERSIONS */
1192
/* Check for Content-Length: header lines to get size. Ignore
1193
the header completely if we get a 416 response as then we're
1194
resuming a document that we don't get, and this header contains
1195
info about the true size of the document we didn't get now. */
1196
if(!k->ignorecl && !data->set.ignorecl &&
1197
checkprefix("Content-Length:", k->p)) {
1198
curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
1199
if(data->set.max_filesize &&
1200
contentlength > data->set.max_filesize) {
1201
failf(data, "Maximum file size exceeded");
1202
return CURLE_FILESIZE_EXCEEDED;
1204
if(contentlength >= 0) {
1205
k->size = contentlength;
1206
k->maxdownload = k->size;
1207
/* we set the progress download size already at this point
1208
just to make it easier for apps/callbacks to extract this
1209
info as soon as possible */
1210
Curl_pgrsSetDownloadSize(data, k->size);
1213
/* Negative Content-Length is really odd, and we know it
1214
happens for example when older Apache servers send large
1216
conn->bits.close = TRUE;
1217
infof(data, "Negative content-length: %" FORMAT_OFF_T
1218
", closing after transfer\n", contentlength);
1221
/* check for Content-Type: header lines to get the MIME-type */
1222
else if(checkprefix("Content-Type:", k->p)) {
1223
char *contenttype = Curl_copy_header_value(k->p);
1225
return CURLE_OUT_OF_MEMORY;
1227
/* ignore empty data */
1230
Curl_safefree(data->info.contenttype);
1231
data->info.contenttype = contenttype;
1234
else if((conn->httpversion == 10) &&
1235
conn->bits.httpproxy &&
1236
Curl_compareheader(k->p,
1237
"Proxy-Connection:", "keep-alive")) {
1239
* When a HTTP/1.0 reply comes when using a proxy, the
1240
* 'Proxy-Connection: keep-alive' line tells us the
1241
* connection will be kept alive for our pleasure.
1242
* Default action for 1.0 is to close.
1244
conn->bits.close = FALSE; /* don't close when done */
1245
infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
1247
else if((conn->httpversion == 11) &&
1248
conn->bits.httpproxy &&
1249
Curl_compareheader(k->p,
1250
"Proxy-Connection:", "close")) {
1252
* We get a HTTP/1.1 response from a proxy and it says it'll
1253
* close down after this transfer.
1255
conn->bits.close = TRUE; /* close when done */
1256
infof(data, "HTTP/1.1 proxy connection set close!\n");
1258
else if((conn->httpversion == 10) &&
1259
Curl_compareheader(k->p, "Connection:", "keep-alive")) {
1261
* A HTTP/1.0 reply with the 'Connection: keep-alive' line
1262
* tells us the connection will be kept alive for our
1263
* pleasure. Default action for 1.0 is to close.
1265
* [RFC2068, section 19.7.1] */
1266
conn->bits.close = FALSE; /* don't close when done */
1267
infof(data, "HTTP/1.0 connection set to keep alive!\n");
1269
else if(Curl_compareheader(k->p, "Connection:", "close")) {
1271
* [RFC 2616, section 8.1.2.1]
1272
* "Connection: close" is HTTP/1.1 language and means that
1273
* the connection will close when this request has been
1276
conn->bits.close = TRUE; /* close when done */
1278
else if(Curl_compareheader(k->p,
1279
"Transfer-Encoding:", "chunked")) {
1281
* [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
1282
* means that the server will send a series of "chunks". Each
1283
* chunk starts with line with info (including size of the
1284
* coming block) (terminated with CRLF), then a block of data
1285
* with the previously mentioned size. There can be any amount
1286
* of chunks, and a chunk-data set to zero signals the
1288
k->chunk = TRUE; /* chunks coming our way */
1290
/* init our chunky engine */
1291
Curl_httpchunk_init(conn);
1294
else if(checkprefix("Trailer:", k->p) ||
1295
checkprefix("Trailers:", k->p)) {
1297
* This test helps Curl_httpchunk_read() to determine to look
1298
* for well formed trailers after the zero chunksize record. In
1299
* this case a CRLF is required after the zero chunksize record
1300
* when no trailers are sent, or after the last trailer record.
1302
* It seems both Trailer: and Trailers: occur in the wild.
1304
k->trailerhdrpresent = TRUE;
1307
else if(checkprefix("Content-Encoding:", k->p) &&
1308
data->set.str[STRING_ENCODING]) {
1310
* Process Content-Encoding. Look for the values: identity,
1311
* gzip, deflate, compress, x-gzip and x-compress. x-gzip and
1312
* x-compress are the same as gzip and compress. (Sec 3.5 RFC
1313
* 2616). zlib cannot handle compress. However, errors are
1314
* handled further down when the response body is processed
1318
/* Find the first non-space letter */
1320
while(*start && ISSPACE(*start))
1323
/* Record the content-encoding for later use */
1324
if(checkprefix("identity", start))
1325
k->content_encoding = IDENTITY;
1326
else if(checkprefix("deflate", start))
1327
k->content_encoding = DEFLATE;
1328
else if(checkprefix("gzip", start)
1329
|| checkprefix("x-gzip", start))
1330
k->content_encoding = GZIP;
1331
else if(checkprefix("compress", start)
1332
|| checkprefix("x-compress", start))
1333
k->content_encoding = COMPRESS;
1335
else if(checkprefix("Content-Range:", k->p)) {
1336
/* Content-Range: bytes [num]-
1337
Content-Range: bytes: [num]-
1338
Content-Range: [num]-
1340
The second format was added since Sun's webserver
1341
JavaWebServer/1.1.1 obviously sends the header this way!
1342
The third added since some servers use that!
1345
char *ptr = k->p + 14;
1347
/* Move forward until first digit */
1348
while(*ptr && !ISDIGIT(*ptr))
1351
k->offset = curlx_strtoofft(ptr, NULL, 10);
1353
if(data->state.resume_from == k->offset)
1354
/* we asked for a resume and we got it */
1355
k->content_range = TRUE;
1357
#if !defined(CURL_DISABLE_COOKIES)
1358
else if(data->cookies &&
1359
checkprefix("Set-Cookie:", k->p)) {
1360
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
1361
CURL_LOCK_ACCESS_SINGLE);
1362
Curl_cookie_add(data,
1363
data->cookies, TRUE, k->p+11,
1364
/* If there is a custom-set Host: name, use it
1365
here, or else use real peer host name. */
1366
conn->allocptr.cookiehost?
1367
conn->allocptr.cookiehost:conn->host.name,
1369
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1372
else if(checkprefix("Last-Modified:", k->p) &&
1373
(data->set.timecondition || data->set.get_filetime) ) {
1374
time_t secs=time(NULL);
1375
k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
1377
if(data->set.get_filetime)
1378
data->info.filetime = (long)k->timeofdoc;
1380
else if((checkprefix("WWW-Authenticate:", k->p) &&
1381
(401 == k->httpcode)) ||
1382
(checkprefix("Proxy-authenticate:", k->p) &&
1383
(407 == k->httpcode))) {
1384
result = Curl_http_input_auth(conn, k->httpcode, k->p);
1388
else if((k->httpcode >= 300 && k->httpcode < 400) &&
1389
checkprefix("Location:", k->p)) {
1390
/* this is the URL that the server advises us to use instead */
1391
char *location = Curl_copy_header_value(k->p);
1393
return CURLE_OUT_OF_MEMORY;
1395
/* ignore empty data */
1398
DEBUGASSERT(!data->req.location);
1399
data->req.location = location;
1401
if(data->set.http_follow_location) {
1402
DEBUGASSERT(!data->req.newurl);
1403
data->req.newurl = strdup(data->req.location); /* clone */
1404
if(!data->req.newurl)
1405
return CURLE_OUT_OF_MEMORY;
1407
/* some cases of POST and PUT etc needs to rewind the data
1408
stream at this point */
1409
result = Curl_http_perhapsrewind(conn);
1417
* End of header-checks. Write them to the client.
1420
writetype = CLIENTWRITE_HEADER;
1421
if(data->set.include_header)
1422
writetype |= CLIENTWRITE_BODY;
1424
if(data->set.verbose)
1425
Curl_debug(data, CURLINFO_HEADER_IN,
1426
k->p, (size_t)k->hbuflen, conn);
1428
result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
1432
data->info.header_size += (long)k->hbuflen;
1433
data->req.headerbytecount += (long)k->hbuflen;
1435
/* reset hbufp pointer && hbuflen */
1436
k->hbufp = data->state.headerbuff;
1439
while(!*stop_reading && *k->str); /* header line within buffer */
1441
/* We might have reached the end of the header part here, but
1442
there might be a non-header part left in the end of the read
1447
#endif /* CURL_DISABLE_HTTP */
1450
* Send data to upload to the server, when the socket is writable.
1452
static CURLcode readwrite_upload(struct SessionHandle *data,
1453
struct connectdata *conn,
1454
struct SingleRequest *k,
1458
ssize_t bytes_written;
1460
ssize_t nread; /* number of bytes read */
1461
bool sending_http_headers = FALSE;
1463
if((k->bytecount == 0) && (k->writebytecount == 0))
1464
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
1466
*didwhat |= KEEP_SEND;
1469
* We loop here to do the READ and SEND loop until we run out of
1470
* data to send or until we get EWOULDBLOCK back
1474
/* only read more data if there's no upload data already
1475
present in the upload buffer */
1476
if(0 == data->req.upload_present) {
1477
/* init the "upload from here" pointer */
1478
data->req.upload_fromhere = k->uploadbuf;
1480
if(!k->upload_done) {
1481
/* HTTP pollution, this should be written nicer to become more
1482
protocol agnostic. */
1485
if((k->exp100 == EXP100_SENDING_REQUEST) &&
1486
(data->state.proto.http->sending == HTTPSEND_BODY)) {
1487
/* If this call is to send body data, we must take some action:
1488
We have sent off the full HTTP 1.1 request, and we shall now
1489
go into the Expect: 100 state and await such a header */
1490
k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
1491
k->keepon &= ~KEEP_SEND; /* disable writing */
1492
k->start100 = Curl_tvnow(); /* timeout count starts now */
1493
*didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
1497
if(conn->protocol&PROT_HTTP) {
1498
if(data->state.proto.http->sending == HTTPSEND_REQUEST)
1499
/* We're sending the HTTP request headers, not the data.
1500
Remember that so we don't change the line endings. */
1501
sending_http_headers = TRUE;
1503
sending_http_headers = FALSE;
1506
result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
1510
nread = (ssize_t)fillcount;
1513
nread = 0; /* we're done uploading/reading */
1515
if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
1516
/* this is a paused transfer */
1521
k->keepon &= ~KEEP_SEND; /* we're done writing */
1523
if(conn->bits.rewindaftersend) {
1524
result = Curl_readrewind(conn);
1531
/* store number of bytes available for upload */
1532
data->req.upload_present = nread;
1534
/* convert LF to CRLF if so asked */
1535
if((!sending_http_headers) &&
1536
#ifdef CURL_DO_LINEEND_CONV
1537
/* always convert if we're FTPing in ASCII mode */
1538
((data->set.crlf) || (data->set.prefer_ascii))) {
1542
if(data->state.scratch == NULL)
1543
data->state.scratch = malloc(2*BUFSIZE);
1544
if(data->state.scratch == NULL) {
1545
failf (data, "Failed to alloc scratch buffer!");
1546
return CURLE_OUT_OF_MEMORY;
1549
* ASCII/EBCDIC Note: This is presumably a text (not binary)
1550
* transfer so the data should already be in ASCII.
1551
* That means the hex values for ASCII CR (0x0d) & LF (0x0a)
1552
* must be used instead of the escape sequences \r & \n.
1554
for(i = 0, si = 0; i < nread; i++, si++) {
1555
if(data->req.upload_fromhere[i] == 0x0a) {
1556
data->state.scratch[si++] = 0x0d;
1557
data->state.scratch[si] = 0x0a;
1558
if(!data->set.crlf) {
1559
/* we're here only because FTP is in ASCII mode...
1560
bump infilesize for the LF we just added */
1561
data->set.infilesize++;
1565
data->state.scratch[si] = data->req.upload_fromhere[i];
1568
/* only perform the special operation if we really did replace
1572
/* upload from the new (replaced) buffer instead */
1573
data->req.upload_fromhere = data->state.scratch;
1575
/* set the new amount too */
1576
data->req.upload_present = nread;
1579
} /* if 0 == data->req.upload_present */
1581
/* We have a partial buffer left from a previous "round". Use
1582
that instead of reading more data */
1585
/* write to socket (send away data) */
1586
result = Curl_write(conn,
1587
conn->writesockfd, /* socket to send to */
1588
data->req.upload_fromhere, /* buffer pointer */
1589
data->req.upload_present, /* buffer size */
1590
&bytes_written); /* actually send away */
1595
if(data->set.verbose)
1596
/* show the data before we change the pointer upload_fromhere */
1597
Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
1598
(size_t)bytes_written, conn);
1600
if(data->req.upload_present != bytes_written) {
1601
/* we only wrote a part of the buffer (if anything), deal with it! */
1603
/* store the amount of bytes left in the buffer to write */
1604
data->req.upload_present -= bytes_written;
1606
/* advance the pointer where to find the buffer when the next send
1608
data->req.upload_fromhere += bytes_written;
1611
/* we've uploaded that buffer now */
1612
data->req.upload_fromhere = k->uploadbuf;
1613
data->req.upload_present = 0; /* no more bytes left */
1615
if(k->upload_done) {
1616
/* switch off writing, we're done! */
1617
k->keepon &= ~KEEP_SEND; /* we're done writing */
1621
k->writebytecount += bytes_written;
1622
Curl_pgrsSetUploadCounter(data, k->writebytecount);
1624
} while(0); /* just to break out from! */
334
1630
* Curl_readwrite() is the low-level function to be called when data is to
335
1631
* be read and written to/from the connection.
380
1674
/* We go ahead and do a read if we have a readable socket or if
381
1675
the stream was rewound (in which case we have data in a
383
if((k->keepon & KEEP_READ) &&
1677
if((k->keepon & KEEP_RECV) &&
384
1678
((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 ) */
1680
result = readwrite_data(data, conn, k, &didwhat, done);
1417
1685
/* If we still have writing to do, we check if we have a writable socket. */
1418
if((k->keepon & KEEP_WRITE) && (select_res & CURL_CSELECT_OUT)) {
1686
if((k->keepon & KEEP_SEND) && (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) */
1689
result = readwrite_upload(data, conn, k, &didwhat);
1579
1694
k->now = Curl_tvnow();