1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifndef CURL_DISABLE_HTTP
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
44 #ifdef HAVE_SYS_PARAM_H
45 #include <sys/param.h>
49 #include <curl/curl.h>
54 #include "curl_base64.h"
57 #include "vtls/vtls.h"
58 #include "http_digest.h"
59 #include "curl_ntlm.h"
60 #include "curl_ntlm_wb.h"
61 #include "http_negotiate.h"
67 #include "parsedate.h" /* for the week day and month names */
68 #include "strtoofft.h"
71 #include "content_encoding.h"
72 #include "http_proxy.h"
74 #include "non-ascii.h"
75 #include "conncache.h"
79 #include "curl_printf.h"
81 /* The last #include files should be: */
82 #include "curl_memory.h"
86 * Forward declarations.
89 static int http_getsock_do(struct connectdata *conn,
92 static int http_should_fail(struct connectdata *conn);
95 static CURLcode https_connecting(struct connectdata *conn, bool *done);
96 static int https_getsock(struct connectdata *conn,
100 #define https_connecting(x,y) CURLE_COULDNT_CONNECT
104 * HTTP handler interface.
106 const struct Curl_handler Curl_handler_http = {
108 Curl_http_setup_conn, /* setup_connection */
109 Curl_http, /* do_it */
110 Curl_http_done, /* done */
111 ZERO_NULL, /* do_more */
112 Curl_http_connect, /* connect_it */
113 ZERO_NULL, /* connecting */
114 ZERO_NULL, /* doing */
115 ZERO_NULL, /* proto_getsock */
116 http_getsock_do, /* doing_getsock */
117 ZERO_NULL, /* domore_getsock */
118 ZERO_NULL, /* perform_getsock */
119 ZERO_NULL, /* disconnect */
120 ZERO_NULL, /* readwrite */
121 PORT_HTTP, /* defport */
122 CURLPROTO_HTTP, /* protocol */
123 PROTOPT_CREDSPERREQUEST /* flags */
128 * HTTPS handler interface.
130 const struct Curl_handler Curl_handler_https = {
131 "HTTPS", /* scheme */
132 Curl_http_setup_conn, /* setup_connection */
133 Curl_http, /* do_it */
134 Curl_http_done, /* done */
135 ZERO_NULL, /* do_more */
136 Curl_http_connect, /* connect_it */
137 https_connecting, /* connecting */
138 ZERO_NULL, /* doing */
139 https_getsock, /* proto_getsock */
140 http_getsock_do, /* doing_getsock */
141 ZERO_NULL, /* domore_getsock */
142 ZERO_NULL, /* perform_getsock */
143 ZERO_NULL, /* disconnect */
144 ZERO_NULL, /* readwrite */
145 PORT_HTTPS, /* defport */
146 CURLPROTO_HTTPS, /* protocol */
147 PROTOPT_SSL | PROTOPT_CREDSPERREQUEST /* flags */
152 CURLcode Curl_http_setup_conn(struct connectdata *conn)
154 /* allocate the HTTP-specific struct for the SessionHandle, only to survive
155 during this request */
157 DEBUGASSERT(conn->data->req.protop == NULL);
159 http = calloc(1, sizeof(struct HTTP));
161 return CURLE_OUT_OF_MEMORY;
163 conn->data->req.protop = http;
165 Curl_http2_setup_conn(conn);
166 Curl_http2_setup_req(conn->data);
172 * checkheaders() checks the linked list of custom HTTP headers for a
173 * particular header (prefix).
175 * Returns a pointer to the first matching header or NULL if none matched.
177 char *Curl_checkheaders(const struct connectdata *conn,
178 const char *thisheader)
180 struct curl_slist *head;
181 size_t thislen = strlen(thisheader);
182 struct SessionHandle *data = conn->data;
184 for(head = data->set.headers;head; head=head->next) {
185 if(Curl_raw_nequal(head->data, thisheader, thislen))
192 * checkProxyHeaders() checks the linked list of custom proxy headers
193 * if proxy headers are not available, then it will lookup into http header
196 * It takes a connectdata struct as input instead of the SessionHandle simply
197 * to know if this is a proxy request or not, as it then might check a
198 * different header list.
201 char *Curl_checkProxyheaders(const struct connectdata *conn,
202 const char *thisheader)
204 struct curl_slist *head;
205 size_t thislen = strlen(thisheader);
206 struct SessionHandle *data = conn->data;
208 for(head = (conn->bits.proxy && data->set.sep_headers)?
209 data->set.proxyheaders:data->set.headers;
210 head; head=head->next) {
211 if(Curl_raw_nequal(head->data, thisheader, thislen))
218 * Strip off leading and trailing whitespace from the value in the
219 * given HTTP header line and return a strdupped copy. Returns NULL in
220 * case of allocation failure. Returns an empty string if the header value
221 * consists entirely of whitespace.
223 char *Curl_copy_header_value(const char *header)
232 /* Find the end of the header name */
233 while(*header && (*header != ':'))
237 /* Skip over colon */
240 /* Find the first non-space letter */
242 while(*start && ISSPACE(*start))
245 /* data is in the host encoding so
246 use '\r' and '\n' instead of 0x0d and 0x0a */
247 end = strchr(start, '\r');
249 end = strchr(start, '\n');
251 end = strchr(start, '\0');
255 /* skip all trailing space letters */
256 while((end > start) && ISSPACE(*end))
259 /* get length of the type */
260 len = end - start + 1;
262 value = malloc(len + 1);
266 memcpy(value, start, len);
267 value[len] = 0; /* zero terminate */
273 * http_output_basic() sets up an Authorization: header (or the proxy version)
274 * for HTTP Basic authentication.
278 static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
281 char *authorization = NULL;
282 struct SessionHandle *data = conn->data;
289 userp = &conn->allocptr.proxyuserpwd;
290 user = conn->proxyuser;
291 pwd = conn->proxypasswd;
294 userp = &conn->allocptr.userpwd;
299 snprintf(data->state.buffer, sizeof(data->state.buffer), "%s:%s", user, pwd);
301 result = Curl_base64_encode(data,
302 data->state.buffer, strlen(data->state.buffer),
303 &authorization, &size);
308 return CURLE_REMOTE_ACCESS_DENIED;
311 *userp = aprintf("%sAuthorization: Basic %s\r\n",
316 return CURLE_OUT_OF_MEMORY;
321 /* pickoneauth() selects the most favourable authentication method from the
322 * ones available and the ones we want.
324 * return TRUE if one was picked
326 static bool pickoneauth(struct auth *pick)
329 /* only deal with authentication we want */
330 unsigned long avail = pick->avail & pick->want;
333 /* The order of these checks is highly relevant, as this will be the order
334 of preference in case of the existence of multiple accepted types. */
335 if(avail & CURLAUTH_NEGOTIATE)
336 pick->picked = CURLAUTH_NEGOTIATE;
337 else if(avail & CURLAUTH_DIGEST)
338 pick->picked = CURLAUTH_DIGEST;
339 else if(avail & CURLAUTH_NTLM)
340 pick->picked = CURLAUTH_NTLM;
341 else if(avail & CURLAUTH_NTLM_WB)
342 pick->picked = CURLAUTH_NTLM_WB;
343 else if(avail & CURLAUTH_BASIC)
344 pick->picked = CURLAUTH_BASIC;
346 pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
349 pick->avail = CURLAUTH_NONE; /* clear it here */
355 * Curl_http_perhapsrewind()
357 * If we are doing POST or PUT {
358 * If we have more data to send {
359 * If we are doing NTLM {
360 * Keep sending since we must not disconnect
363 * If there is more than just a little data left to send, close
364 * the current connection by force.
367 * If we have sent any data {
368 * If we don't have track of all the data {
369 * call app to tell it to rewind
372 * rewind internally so that the operation can restart fine
377 static CURLcode http_perhapsrewind(struct connectdata *conn)
379 struct SessionHandle *data = conn->data;
380 struct HTTP *http = data->req.protop;
381 curl_off_t bytessent;
382 curl_off_t expectsend = -1; /* default is unknown */
385 /* If this is still NULL, we have not reach very far and we can safely
386 skip this rewinding stuff */
389 switch(data->set.httpreq) {
397 bytessent = http->writebytecount;
399 if(conn->bits.authneg) {
400 /* This is a state where we are known to be negotiating and we don't send
404 else if(!conn->bits.protoconnstart) {
405 /* HTTP CONNECT in progress: there is no body */
409 /* figure out how much data we are expected to send */
410 switch(data->set.httpreq) {
412 if(data->state.infilesize != -1)
413 expectsend = data->state.infilesize;
414 else if(data->set.postfields)
415 expectsend = (curl_off_t)strlen(data->set.postfields);
418 if(data->state.infilesize != -1)
419 expectsend = data->state.infilesize;
421 case HTTPREQ_POST_FORM:
422 expectsend = http->postsize;
429 conn->bits.rewindaftersend = FALSE; /* default */
431 if((expectsend == -1) || (expectsend > bytessent)) {
432 #if defined(USE_NTLM)
433 /* There is still data left to send */
434 if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
435 (data->state.authhost.picked == CURLAUTH_NTLM) ||
436 (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
437 (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
438 if(((expectsend - bytessent) < 2000) ||
439 (conn->ntlm.state != NTLMSTATE_NONE) ||
440 (conn->proxyntlm.state != NTLMSTATE_NONE)) {
441 /* The NTLM-negotiation has started *OR* there is just a little (<2K)
442 data left to send, keep on sending. */
444 /* rewind data when completely done sending! */
445 if(!conn->bits.authneg) {
446 conn->bits.rewindaftersend = TRUE;
447 infof(data, "Rewind stream after send\n");
454 /* this is already marked to get closed */
457 infof(data, "NTLM send, close instead of sending %"
458 CURL_FORMAT_CURL_OFF_T " bytes\n",
459 (curl_off_t)(expectsend - bytessent));
463 /* This is not NTLM or many bytes left to send: close */
464 connclose(conn, "Mid-auth HTTP and much data left to send");
465 data->req.size = 0; /* don't download any more than 0 bytes */
467 /* There still is data left to send, but this connection is marked for
468 closure so we can safely do the rewind right now */
472 /* we rewind now at once since if we already sent something */
473 return Curl_readrewind(conn);
479 * Curl_http_auth_act() gets called when all HTTP headers have been received
480 * and it checks what authentication methods that are available and decides
481 * which one (if any) to use. It will set 'newurl' if an auth method was
485 CURLcode Curl_http_auth_act(struct connectdata *conn)
487 struct SessionHandle *data = conn->data;
488 bool pickhost = FALSE;
489 bool pickproxy = FALSE;
490 CURLcode result = CURLE_OK;
492 if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
493 /* this is a transient response code, ignore */
496 if(data->state.authproblem)
497 return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
499 if(conn->bits.user_passwd &&
500 ((data->req.httpcode == 401) ||
501 (conn->bits.authneg && data->req.httpcode < 300))) {
502 pickhost = pickoneauth(&data->state.authhost);
504 data->state.authproblem = TRUE;
506 if(conn->bits.proxy_user_passwd &&
507 ((data->req.httpcode == 407) ||
508 (conn->bits.authneg && data->req.httpcode < 300))) {
509 pickproxy = pickoneauth(&data->state.authproxy);
511 data->state.authproblem = TRUE;
514 if(pickhost || pickproxy) {
515 /* In case this is GSS auth, the newurl field is already allocated so
516 we must make sure to free it before allocating a new one. As figured
517 out in bug #2284386 */
518 Curl_safefree(data->req.newurl);
519 data->req.newurl = strdup(data->change.url); /* clone URL */
520 if(!data->req.newurl)
521 return CURLE_OUT_OF_MEMORY;
523 if((data->set.httpreq != HTTPREQ_GET) &&
524 (data->set.httpreq != HTTPREQ_HEAD) &&
525 !conn->bits.rewindaftersend) {
526 result = http_perhapsrewind(conn);
532 else if((data->req.httpcode < 300) &&
533 (!data->state.authhost.done) &&
534 conn->bits.authneg) {
535 /* no (known) authentication available,
536 authentication is not "done" yet and
537 no authentication seems to be required and
538 we didn't try HEAD or GET */
539 if((data->set.httpreq != HTTPREQ_GET) &&
540 (data->set.httpreq != HTTPREQ_HEAD)) {
541 data->req.newurl = strdup(data->change.url); /* clone URL */
542 if(!data->req.newurl)
543 return CURLE_OUT_OF_MEMORY;
544 data->state.authhost.done = TRUE;
547 if(http_should_fail(conn)) {
548 failf (data, "The requested URL returned error: %d",
550 result = CURLE_HTTP_RETURNED_ERROR;
558 * Output the correct authentication header depending on the auth type
559 * and whether or not it is to a proxy.
562 output_auth_headers(struct connectdata *conn,
563 struct auth *authstatus,
568 const char *auth = NULL;
569 CURLcode result = CURLE_OK;
570 #if defined(USE_SPNEGO) || !defined(CURL_DISABLE_VERBOSE_STRINGS)
571 struct SessionHandle *data = conn->data;
574 struct negotiatedata *negdata = proxy?
575 &data->state.proxyneg:&data->state.negotiate;
578 #ifdef CURL_DISABLE_CRYPTO_AUTH
584 negdata->state = GSS_AUTHNONE;
585 if((authstatus->picked == CURLAUTH_NEGOTIATE) &&
586 negdata->context && !GSS_ERROR(negdata->status)) {
588 result = Curl_output_negotiate(conn, proxy);
591 authstatus->done = TRUE;
592 negdata->state = GSS_AUTHSENT;
597 if(authstatus->picked == CURLAUTH_NTLM) {
599 result = Curl_output_ntlm(conn, proxy);
605 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
606 if(authstatus->picked == CURLAUTH_NTLM_WB) {
608 result = Curl_output_ntlm_wb(conn, proxy);
614 #ifndef CURL_DISABLE_CRYPTO_AUTH
615 if(authstatus->picked == CURLAUTH_DIGEST) {
617 result = Curl_output_digest(conn,
619 (const unsigned char *)request,
620 (const unsigned char *)path);
626 if(authstatus->picked == CURLAUTH_BASIC) {
628 if((proxy && conn->bits.proxy_user_passwd &&
629 !Curl_checkProxyheaders(conn, "Proxy-authorization:")) ||
630 (!proxy && conn->bits.user_passwd &&
631 !Curl_checkheaders(conn, "Authorization:"))) {
633 result = http_output_basic(conn, proxy);
637 /* NOTE: this function should set 'done' TRUE, as the other auth
638 functions work that way */
639 authstatus->done = TRUE;
643 infof(data, "%s auth using %s with user '%s'\n",
644 proxy?"Proxy":"Server", auth,
645 proxy?(conn->proxyuser?conn->proxyuser:""):
646 (conn->user?conn->user:""));
647 authstatus->multi = (!authstatus->done) ? TRUE : FALSE;
650 authstatus->multi = FALSE;
656 * Curl_http_output_auth() setups the authentication headers for the
657 * host/proxy and the correct authentication
658 * method. conn->data->state.authdone is set to TRUE when authentication is
661 * @param conn all information about the current connection
662 * @param request pointer to the request keyword
663 * @param path pointer to the requested path
664 * @param proxytunnel boolean if this is the request setting up a "proxy
670 Curl_http_output_auth(struct connectdata *conn,
673 bool proxytunnel) /* TRUE if this is the request setting
674 up the proxy tunnel */
676 CURLcode result = CURLE_OK;
677 struct SessionHandle *data = conn->data;
678 struct auth *authhost;
679 struct auth *authproxy;
683 authhost = &data->state.authhost;
684 authproxy = &data->state.authproxy;
686 if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
687 conn->bits.user_passwd)
688 /* continue please */;
690 authhost->done = TRUE;
691 authproxy->done = TRUE;
692 return CURLE_OK; /* no authentication with no user or password */
695 if(authhost->want && !authhost->picked)
696 /* The app has selected one or more methods, but none has been picked
697 so far by a server round-trip. Then we set the picked one to the
698 want one, and if this is one single bit it'll be used instantly. */
699 authhost->picked = authhost->want;
701 if(authproxy->want && !authproxy->picked)
702 /* The app has selected one or more methods, but none has been picked so
703 far by a proxy round-trip. Then we set the picked one to the want one,
704 and if this is one single bit it'll be used instantly. */
705 authproxy->picked = authproxy->want;
707 #ifndef CURL_DISABLE_PROXY
708 /* Send proxy authentication header if needed */
709 if(conn->bits.httpproxy &&
710 (conn->bits.tunnel_proxy == proxytunnel)) {
711 result = output_auth_headers(conn, authproxy, request, path, TRUE);
718 #endif /* CURL_DISABLE_PROXY */
719 /* we have no proxy so let's pretend we're done authenticating
721 authproxy->done = TRUE;
723 /* To prevent the user+password to get sent to other than the original
724 host due to a location-follow, we do some weirdo checks here */
725 if(!data->state.this_is_a_follow ||
727 !data->state.first_host ||
728 data->set.http_disable_hostname_check_before_authentication ||
729 Curl_raw_equal(data->state.first_host, conn->host.name)) {
730 result = output_auth_headers(conn, authhost, request, path, FALSE);
733 authhost->done = TRUE;
740 * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
741 * headers. They are dealt with both in the transfer.c main loop and in the
742 * proxy CONNECT loop.
745 CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
746 const char *auth) /* the first non-space */
749 * This resource requires authentication
751 struct SessionHandle *data = conn->data;
754 struct negotiatedata *negdata = proxy?
755 &data->state.proxyneg:&data->state.negotiate;
757 unsigned long *availp;
761 availp = &data->info.proxyauthavail;
762 authp = &data->state.authproxy;
765 availp = &data->info.httpauthavail;
766 authp = &data->state.authhost;
770 * Here we check if we want the specific single authentication (using ==) and
771 * if we do, we initiate usage of it.
773 * If the provided authentication is wanted as one out of several accepted
774 * types (using &), we OR this authentication type to the authavail
779 * ->picked is first set to the 'want' value (one or more bits) before the
780 * request is sent, and then it is again set _after_ all response 401/407
781 * headers have been received but then only to a single preferred method
788 if(checkprefix("Negotiate", auth)) {
789 *availp |= CURLAUTH_NEGOTIATE;
790 authp->avail |= CURLAUTH_NEGOTIATE;
792 if(authp->picked == CURLAUTH_NEGOTIATE) {
793 if(negdata->state == GSS_AUTHSENT || negdata->state == GSS_AUTHNONE) {
794 CURLcode result = Curl_input_negotiate(conn, proxy, auth);
796 DEBUGASSERT(!data->req.newurl);
797 data->req.newurl = strdup(data->change.url);
798 if(!data->req.newurl)
799 return CURLE_OUT_OF_MEMORY;
800 data->state.authproblem = FALSE;
801 /* we received a GSS auth token and we dealt with it fine */
802 negdata->state = GSS_AUTHRECV;
805 data->state.authproblem = TRUE;
812 /* NTLM support requires the SSL crypto libs */
813 if(checkprefix("NTLM", auth)) {
814 *availp |= CURLAUTH_NTLM;
815 authp->avail |= CURLAUTH_NTLM;
816 if(authp->picked == CURLAUTH_NTLM ||
817 authp->picked == CURLAUTH_NTLM_WB) {
818 /* NTLM authentication is picked and activated */
819 CURLcode result = Curl_input_ntlm(conn, proxy, auth);
821 data->state.authproblem = FALSE;
822 #ifdef NTLM_WB_ENABLED
823 if(authp->picked == CURLAUTH_NTLM_WB) {
824 *availp &= ~CURLAUTH_NTLM;
825 authp->avail &= ~CURLAUTH_NTLM;
826 *availp |= CURLAUTH_NTLM_WB;
827 authp->avail |= CURLAUTH_NTLM_WB;
829 /* Get the challenge-message which will be passed to
830 * ntlm_auth for generating the type 3 message later */
831 while(*auth && ISSPACE(*auth))
833 if(checkprefix("NTLM", auth)) {
834 auth += strlen("NTLM");
835 while(*auth && ISSPACE(*auth))
838 if((conn->challenge_header = strdup(auth)) == NULL)
839 return CURLE_OUT_OF_MEMORY;
845 infof(data, "Authentication problem. Ignoring this.\n");
846 data->state.authproblem = TRUE;
852 #ifndef CURL_DISABLE_CRYPTO_AUTH
853 if(checkprefix("Digest", auth)) {
854 if((authp->avail & CURLAUTH_DIGEST) != 0) {
855 infof(data, "Ignoring duplicate digest auth header.\n");
859 *availp |= CURLAUTH_DIGEST;
860 authp->avail |= CURLAUTH_DIGEST;
862 /* We call this function on input Digest headers even if Digest
863 * authentication isn't activated yet, as we need to store the
864 * incoming data from this header in case we are gonna use
866 result = Curl_input_digest(conn, proxy, auth);
868 infof(data, "Authentication problem. Ignoring this.\n");
869 data->state.authproblem = TRUE;
875 if(checkprefix("Basic", auth)) {
876 *availp |= CURLAUTH_BASIC;
877 authp->avail |= CURLAUTH_BASIC;
878 if(authp->picked == CURLAUTH_BASIC) {
879 /* We asked for Basic authentication but got a 40X back
880 anyway, which basically means our name+password isn't
882 authp->avail = CURLAUTH_NONE;
883 infof(data, "Authentication problem. Ignoring this.\n");
884 data->state.authproblem = TRUE;
888 /* there may be multiple methods on one line, so keep reading */
889 while(*auth && *auth != ',') /* read up to the next comma */
891 if(*auth == ',') /* if we're on a comma, skip it */
893 while(*auth && ISSPACE(*auth))
900 * http_should_fail() determines whether an HTTP response has gotten us
901 * into an error state or not.
903 * @param conn all information about the current connection
905 * @retval 0 communications should continue
907 * @retval 1 communications should not continue
909 static int http_should_fail(struct connectdata *conn)
911 struct SessionHandle *data;
918 httpcode = data->req.httpcode;
921 ** If we haven't been asked to fail on error,
924 if(!data->set.http_fail_on_error)
928 ** Any code < 400 is never terminal.
934 ** Any code >= 400 that's not 401 or 407 is always
937 if((httpcode != 401) &&
942 ** All we have left to deal with is 401 and 407
944 DEBUGASSERT((httpcode == 401) || (httpcode == 407));
947 ** Examine the current authentication state to see if this
948 ** is an error. The idea is for this function to get
949 ** called after processing all the headers in a response
950 ** message. So, if we've been to asked to authenticate a
951 ** particular stage, and we've done it, we're OK. But, if
952 ** we're already completely authenticated, it's not OK to
953 ** get another 401 or 407.
955 ** It is possible for authentication to go stale such that
956 ** the client needs to reauthenticate. Once that info is
957 ** available, use it here.
961 ** Either we're not authenticating, or we're supposed to
962 ** be authenticating something else. This is an error.
964 if((httpcode == 401) && !conn->bits.user_passwd)
966 if((httpcode == 407) && !conn->bits.proxy_user_passwd)
969 return data->state.authproblem;
973 * readmoredata() is a "fread() emulation" to provide POST and/or request
974 * data. It is used when a huge POST is to be made and the entire chunk wasn't
975 * sent in the first send(). This function will then be called from the
976 * transfer.c loop when more data is to be sent to the peer.
978 * Returns the amount of bytes it filled the buffer with.
980 static size_t readmoredata(char *buffer,
985 struct connectdata *conn = (struct connectdata *)userp;
986 struct HTTP *http = conn->data->req.protop;
987 size_t fullsize = size * nitems;
989 if(0 == http->postsize)
990 /* nothing to return */
993 /* make sure that a HTTP request is never sent away chunked! */
994 conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
996 if(http->postsize <= (curl_off_t)fullsize) {
997 memcpy(buffer, http->postdata, (size_t)http->postsize);
998 fullsize = (size_t)http->postsize;
1000 if(http->backup.postsize) {
1001 /* move backup data into focus and continue on that */
1002 http->postdata = http->backup.postdata;
1003 http->postsize = http->backup.postsize;
1004 conn->data->set.fread_func = http->backup.fread_func;
1005 conn->data->set.in = http->backup.fread_in;
1007 http->sending++; /* move one step up */
1009 http->backup.postsize=0;
1017 memcpy(buffer, http->postdata, fullsize);
1018 http->postdata += fullsize;
1019 http->postsize -= fullsize;
1024 /* ------------------------------------------------------------------------- */
1025 /* add_buffer functions */
1028 * Curl_add_buffer_init() sets up and returns a fine buffer struct
1030 Curl_send_buffer *Curl_add_buffer_init(void)
1032 return calloc(1, sizeof(Curl_send_buffer));
1036 * Curl_add_buffer_free() frees all associated resources.
1038 void Curl_add_buffer_free(Curl_send_buffer *buff)
1040 if(buff) /* deal with NULL input */
1046 * Curl_add_buffer_send() sends a header buffer and frees all associated
1047 * memory. Body data may be appended to the header data if desired.
1051 CURLcode Curl_add_buffer_send(Curl_send_buffer *in,
1052 struct connectdata *conn,
1054 /* add the number of sent bytes to this
1056 long *bytes_written,
1058 /* how much of the buffer contains body data */
1059 size_t included_body_bytes,
1067 struct HTTP *http = conn->data->req.protop;
1069 curl_socket_t sockfd;
1072 DEBUGASSERT(socketindex <= SECONDARYSOCKET);
1074 sockfd = conn->sock[socketindex];
1076 /* The looping below is required since we use non-blocking sockets, but due
1077 to the circumstances we will just loop and try again and again etc */
1080 size = in->size_used;
1082 headersize = size - included_body_bytes; /* the initial part that isn't body
1085 DEBUGASSERT(size > included_body_bytes);
1087 result = Curl_convert_to_network(conn->data, ptr, headersize);
1088 /* Curl_convert_to_network calls failf if unsuccessful */
1090 /* conversion failed, free memory and return to the caller */
1091 Curl_add_buffer_free(in);
1096 if(conn->handler->flags & PROTOPT_SSL) {
1097 /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
1098 when we speak HTTPS, as if only a fraction of it is sent now, this data
1099 needs to fit into the normal read-callback buffer later on and that
1100 buffer is using this size.
1103 sendsize= (size > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:size;
1105 /* OpenSSL is very picky and we must send the SAME buffer pointer to the
1106 library when we attempt to re-send this buffer. Sending the same data
1107 is not enough, we must use the exact same address. For this reason, we
1108 must copy the data to the uploadbuffer first, since that is the buffer
1109 we will be using if this send is retried later.
1111 memcpy(conn->data->state.uploadbuffer, ptr, sendsize);
1112 ptr = conn->data->state.uploadbuffer;
1117 result = Curl_write(conn, sockfd, ptr, sendsize, &amount);
1121 * Note that we may not send the entire chunk at once, and we have a set
1122 * number of data bytes at the end of the big buffer (out of which we may
1123 * only send away a part).
1125 /* how much of the header that was sent */
1126 size_t headlen = (size_t)amount>headersize?headersize:(size_t)amount;
1127 size_t bodylen = amount - headlen;
1129 if(conn->data->set.verbose) {
1130 /* this data _may_ contain binary stuff */
1131 Curl_debug(conn->data, CURLINFO_HEADER_OUT, ptr, headlen, conn);
1133 /* there was body data sent beyond the initial header part, pass that
1134 on to the debug callback too */
1135 Curl_debug(conn->data, CURLINFO_DATA_OUT,
1136 ptr+headlen, bodylen, conn);
1140 /* since we sent a piece of the body here, up the byte counter for it
1142 http->writebytecount += bodylen;
1144 /* 'amount' can never be a very large value here so typecasting it so a
1145 signed 31 bit value should not cause problems even if ssize_t is
1147 *bytes_written += (long)amount;
1150 if((size_t)amount != size) {
1151 /* The whole request could not be sent in one system call. We must
1152 queue it up and send it later when we get the chance. We must not
1153 loop here and wait until it might work again. */
1157 ptr = in->buffer + amount;
1159 /* backup the currently set pointers */
1160 http->backup.fread_func = conn->data->set.fread_func;
1161 http->backup.fread_in = conn->data->set.in;
1162 http->backup.postdata = http->postdata;
1163 http->backup.postsize = http->postsize;
1165 /* set the new pointers for the request-sending */
1166 conn->data->set.fread_func = (curl_read_callback)readmoredata;
1167 conn->data->set.in = (void *)conn;
1168 http->postdata = ptr;
1169 http->postsize = (curl_off_t)size;
1171 http->send_buffer = in;
1172 http->sending = HTTPSEND_REQUEST;
1176 http->sending = HTTPSEND_BODY;
1177 /* the full buffer was sent, clean up and return */
1180 if((size_t)amount != size)
1181 /* We have no continue-send mechanism now, fail. This can only happen
1182 when this function is used from the CONNECT sending function. We
1183 currently (stupidly) assume that the whole request is always sent
1184 away in the first single chunk.
1188 return CURLE_SEND_ERROR;
1190 Curl_pipeline_leave_write(conn);
1193 Curl_add_buffer_free(in);
1200 * add_bufferf() add the formatted input to the buffer.
1202 CURLcode Curl_add_bufferf(Curl_send_buffer *in, const char *fmt, ...)
1207 s = vaprintf(fmt, ap); /* this allocs a new string to append */
1211 CURLcode result = Curl_add_buffer(in, s, strlen(s));
1215 /* If we failed, we cleanup the whole buffer and return error */
1218 return CURLE_OUT_OF_MEMORY;
1222 * add_buffer() appends a memory chunk to the existing buffer
1224 CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size)
1229 if(~size < in->size_used) {
1230 /* If resulting used size of send buffer would wrap size_t, cleanup
1231 the whole buffer and return error. Otherwise the required buffer
1232 size will fit into a single allocatable memory chunk */
1233 Curl_safefree(in->buffer);
1235 return CURLE_OUT_OF_MEMORY;
1239 ((in->size_used + size) > (in->size_max - 1))) {
1241 /* If current buffer size isn't enough to hold the result, use a
1242 buffer size that doubles the required size. If this new size
1243 would wrap size_t, then just use the largest possible one */
1245 if((size > (size_t)-1/2) || (in->size_used > (size_t)-1/2) ||
1246 (~(size*2) < (in->size_used*2)))
1247 new_size = (size_t)-1;
1249 new_size = (in->size_used+size)*2;
1252 /* we have a buffer, enlarge the existing one */
1253 new_rb = realloc(in->buffer, new_size);
1255 /* create a new buffer */
1256 new_rb = malloc(new_size);
1259 /* If we failed, we cleanup the whole buffer and return error */
1260 Curl_safefree(in->buffer);
1262 return CURLE_OUT_OF_MEMORY;
1265 in->buffer = new_rb;
1266 in->size_max = new_size;
1268 memcpy(&in->buffer[in->size_used], inptr, size);
1270 in->size_used += size;
1275 /* end of the add_buffer functions */
1276 /* ------------------------------------------------------------------------- */
1281 * Curl_compareheader()
1283 * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
1284 * Pass headers WITH the colon.
1287 Curl_compareheader(const char *headerline, /* line to check */
1288 const char *header, /* header keyword _with_ colon */
1289 const char *content) /* content string to find */
1291 /* RFC2616, section 4.2 says: "Each header field consists of a name followed
1292 * by a colon (":") and the field value. Field names are case-insensitive.
1293 * The field value MAY be preceded by any amount of LWS, though a single SP
1296 size_t hlen = strlen(header);
1302 if(!Curl_raw_nequal(headerline, header, hlen))
1303 return FALSE; /* doesn't start with header */
1305 /* pass the header */
1306 start = &headerline[hlen];
1308 /* pass all white spaces */
1309 while(*start && ISSPACE(*start))
1312 /* find the end of the header line */
1313 end = strchr(start, '\r'); /* lines end with CRLF */
1315 /* in case there's a non-standard compliant line here */
1316 end = strchr(start, '\n');
1319 /* hm, there's no line ending here, use the zero byte! */
1320 end = strchr(start, '\0');
1323 len = end-start; /* length of the content part of the input line */
1324 clen = strlen(content); /* length of the word to find */
1326 /* find the content string in the rest of the line */
1327 for(;len>=clen;len--, start++) {
1328 if(Curl_raw_nequal(start, content, clen))
1329 return TRUE; /* match! */
1332 return FALSE; /* no match */
1336 * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
1337 * the generic Curl_connect().
1339 CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
1343 /* We default to persistent connections. We set this already in this connect
1344 function to make the re-use checks properly be able to check this bit. */
1345 connkeep(conn, "HTTP default");
1347 /* the CONNECT procedure might not have been completed */
1348 result = Curl_proxy_connect(conn);
1352 if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
1353 /* nothing else to do except wait right now - we're not done here. */
1356 if(conn->given->flags & PROTOPT_SSL) {
1357 /* perform SSL initialization */
1358 result = https_connecting(conn, done);
1368 /* this returns the socket to wait for in the DO and DOING state for the multi
1369 interface and then we're always _sending_ a request and thus we wait for
1370 the single socket to become writable only */
1371 static int http_getsock_do(struct connectdata *conn,
1372 curl_socket_t *socks,
1376 (void)numsocks; /* unused, we trust it to be at least 1 */
1377 socks[0] = conn->sock[FIRSTSOCKET];
1378 return GETSOCK_WRITESOCK(0);
1382 static CURLcode https_connecting(struct connectdata *conn, bool *done)
1385 DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
1387 /* perform SSL initialization for this socket */
1388 result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
1390 connclose(conn, "Failed HTTPS connection");
1396 #if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
1397 defined(USE_DARWINSSL) || defined(USE_POLARSSL) || defined(USE_NSS)
1398 /* This function is for OpenSSL, GnuTLS, darwinssl, schannel and polarssl only.
1399 It should be made to query the generic SSL layer instead. */
1400 static int https_getsock(struct connectdata *conn,
1401 curl_socket_t *socks,
1404 if(conn->handler->flags & PROTOPT_SSL) {
1405 struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
1408 return GETSOCK_BLANK;
1410 if(connssl->connecting_state == ssl_connect_2_writing) {
1412 socks[0] = conn->sock[FIRSTSOCKET];
1413 return GETSOCK_WRITESOCK(0);
1415 else if(connssl->connecting_state == ssl_connect_2_reading) {
1417 socks[0] = conn->sock[FIRSTSOCKET];
1418 return GETSOCK_READSOCK(0);
1425 static int https_getsock(struct connectdata *conn,
1426 curl_socket_t *socks,
1432 return GETSOCK_BLANK;
1434 #endif /* USE_SSL */
1435 #endif /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL */
1438 * Curl_http_done() gets called from Curl_done() after a single HTTP request
1439 * has been performed.
1442 CURLcode Curl_http_done(struct connectdata *conn,
1443 CURLcode status, bool premature)
1445 struct SessionHandle *data = conn->data;
1446 struct HTTP *http = data->req.protop;
1448 struct http_conn *httpc = &conn->proto.httpc;
1451 Curl_unencode_cleanup(conn);
1454 if(data->state.proxyneg.state == GSS_AUTHSENT ||
1455 data->state.negotiate.state == GSS_AUTHSENT) {
1456 /* add forbid re-use if http-code != 401/407 as a WA only needed for
1457 * 401/407 that signal auth failure (empty) otherwise state will be RECV
1458 * with current code */
1459 if((data->req.httpcode != 401) && (data->req.httpcode != 407))
1460 connclose(conn, "Negotiate transfer completed");
1461 Curl_cleanup_negotiate(data);
1465 /* set the proper values (possibly modified on POST) */
1466 conn->seek_func = data->set.seek_func; /* restore */
1467 conn->seek_client = data->set.seek_client; /* restore */
1472 if(http->send_buffer) {
1473 Curl_add_buffer_free(http->send_buffer);
1474 http->send_buffer = NULL; /* clear the pointer */
1478 if(http->header_recvbuf) {
1479 DEBUGF(infof(data, "free header_recvbuf!!\n"));
1480 Curl_add_buffer_free(http->header_recvbuf);
1481 http->header_recvbuf = NULL; /* clear the pointer */
1482 for(; http->push_headers_used > 0; --http->push_headers_used) {
1483 free(http->push_headers[http->push_headers_used - 1]);
1485 free(http->push_headers);
1486 http->push_headers = NULL;
1488 if(http->stream_id) {
1489 nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0);
1490 http->stream_id = 0;
1494 if(HTTPREQ_POST_FORM == data->set.httpreq) {
1495 data->req.bytecount = http->readbytecount + http->writebytecount;
1497 Curl_formclean(&http->sendit); /* Now free that whole lot */
1499 /* a file being uploaded was left opened, close it! */
1500 fclose(http->form.fp);
1501 http->form.fp = NULL;
1504 else if(HTTPREQ_PUT == data->set.httpreq)
1505 data->req.bytecount = http->readbytecount + http->writebytecount;
1510 if(!premature && /* this check is pointless when DONE is called before the
1511 entire operation is complete */
1512 !conn->bits.retry &&
1513 !data->set.connect_only &&
1514 ((http->readbytecount +
1515 data->req.headerbytecount -
1516 data->req.deductheadercount)) <= 0) {
1517 /* If this connection isn't simply closed to be retried, AND nothing was
1518 read from the HTTP server (that counts), this can't be right so we
1519 return an error here */
1520 failf(data, "Empty reply from server");
1521 return CURLE_GOT_NOTHING;
1529 * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
1530 * to avoid it include:
1532 * - if the user specifically requested HTTP 1.0
1533 * - if the server we are connected to only supports 1.0
1534 * - if any server previously contacted to handle this request only supports
1537 static bool use_http_1_1plus(const struct SessionHandle *data,
1538 const struct connectdata *conn)
1540 return ((data->set.httpversion >= CURL_HTTP_VERSION_1_1) ||
1541 ((data->set.httpversion != CURL_HTTP_VERSION_1_0) &&
1542 ((conn->httpversion == 11) ||
1543 ((conn->httpversion != 10) &&
1544 (data->state.httpversion != 10))))) ? TRUE : FALSE;
1547 /* check and possibly add an Expect: header */
1548 static CURLcode expect100(struct SessionHandle *data,
1549 struct connectdata *conn,
1550 Curl_send_buffer *req_buffer)
1552 CURLcode result = CURLE_OK;
1554 data->state.expect100header = FALSE; /* default to false unless it is set
1556 if(use_http_1_1plus(data, conn) &&
1557 (conn->httpversion != 20)) {
1558 /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an
1559 Expect: 100-continue to the headers which actually speeds up post
1560 operations (as there is one packet coming back from the web server) */
1561 ptr = Curl_checkheaders(conn, "Expect:");
1563 data->state.expect100header =
1564 Curl_compareheader(ptr, "Expect:", "100-continue");
1567 result = Curl_add_bufferf(req_buffer,
1568 "Expect: 100-continue\r\n");
1570 data->state.expect100header = TRUE;
1577 HEADER_SERVER, /* direct to server */
1578 HEADER_PROXY, /* regular request to proxy */
1579 HEADER_CONNECT /* sending CONNECT to a proxy */
1582 CURLcode Curl_add_custom_headers(struct connectdata *conn,
1584 Curl_send_buffer *req_buffer)
1587 struct curl_slist *h[2];
1588 struct curl_slist *headers;
1589 int numlists=1; /* by default */
1590 struct SessionHandle *data = conn->data;
1593 enum proxy_use proxy;
1596 proxy = HEADER_CONNECT;
1598 proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
1599 HEADER_PROXY:HEADER_SERVER;
1603 h[0] = data->set.headers;
1606 h[0] = data->set.headers;
1607 if(data->set.sep_headers) {
1608 h[1] = data->set.proxyheaders;
1612 case HEADER_CONNECT:
1613 if(data->set.sep_headers)
1614 h[0] = data->set.proxyheaders;
1616 h[0] = data->set.headers;
1620 /* loop through one or two lists */
1621 for(i=0; i < numlists; i++) {
1625 ptr = strchr(headers->data, ':');
1627 /* we require a colon for this to be a true header */
1629 ptr++; /* pass the colon */
1630 while(*ptr && ISSPACE(*ptr))
1634 /* only send this if the contents was non-blank */
1636 if(conn->allocptr.host &&
1637 /* a Host: header was sent already, don't pass on any custom Host:
1638 header as that will produce *two* in the same request! */
1639 checkprefix("Host:", headers->data))
1641 else if(data->set.httpreq == HTTPREQ_POST_FORM &&
1642 /* this header (extended by formdata.c) is sent later */
1643 checkprefix("Content-Type:", headers->data))
1645 else if(conn->bits.authneg &&
1646 /* while doing auth neg, don't allow the custom length since
1647 we will force length zero then */
1648 checkprefix("Content-Length", headers->data))
1650 else if(conn->allocptr.te &&
1651 /* when asking for Transfer-Encoding, don't pass on a custom
1653 checkprefix("Connection", headers->data))
1656 CURLcode result = Curl_add_bufferf(req_buffer, "%s\r\n",
1664 ptr = strchr(headers->data, ';');
1667 ptr++; /* pass the semicolon */
1668 while(*ptr && ISSPACE(*ptr))
1672 /* this may be used for something else in the future */
1675 if(*(--ptr) == ';') {
1678 /* send no-value custom header if terminated by semicolon */
1680 result = Curl_add_bufferf(req_buffer, "%s\r\n",
1688 headers = headers->next;
1694 CURLcode Curl_add_timecondition(struct SessionHandle *data,
1695 Curl_send_buffer *req_buffer)
1697 const struct tm *tm;
1698 char *buf = data->state.buffer;
1700 CURLcode result = Curl_gmtime(data->set.timevalue, &keeptime);
1702 failf(data, "Invalid TIMEVALUE");
1707 /* The If-Modified-Since header family should have their times set in
1708 * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
1709 * represented in Greenwich Mean Time (GMT), without exception. For the
1710 * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
1711 * Time)." (see page 20 of RFC2616).
1714 /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
1715 snprintf(buf, BUFSIZE-1,
1716 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1717 Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
1719 Curl_month[tm->tm_mon],
1725 switch(data->set.timecondition) {
1726 case CURL_TIMECOND_IFMODSINCE:
1728 result = Curl_add_bufferf(req_buffer,
1729 "If-Modified-Since: %s\r\n", buf);
1731 case CURL_TIMECOND_IFUNMODSINCE:
1732 result = Curl_add_bufferf(req_buffer,
1733 "If-Unmodified-Since: %s\r\n", buf);
1735 case CURL_TIMECOND_LASTMOD:
1736 result = Curl_add_bufferf(req_buffer,
1737 "Last-Modified: %s\r\n", buf);
1745 * Curl_http() gets called from the generic Curl_do() function when a HTTP
1746 * request is to be performed. This creates and sends a properly constructed
1749 CURLcode Curl_http(struct connectdata *conn, bool *done)
1751 struct SessionHandle *data = conn->data;
1752 CURLcode result = CURLE_OK;
1754 const char *ppath = data->state.path;
1755 bool paste_ftp_userpwd = FALSE;
1756 char ftp_typecode[sizeof("/;type=?")] = "";
1757 const char *host = conn->host.name;
1758 const char *te = ""; /* transfer-encoding */
1760 const char *request;
1761 Curl_HttpReq httpreq = data->set.httpreq;
1762 #if !defined(CURL_DISABLE_COOKIES)
1763 char *addcookies = NULL;
1765 curl_off_t included_body = 0;
1766 const char *httpstring;
1767 Curl_send_buffer *req_buffer;
1768 curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
1769 int seekerr = CURL_SEEKFUNC_OK;
1771 /* Always consider the DO phase done after this function call, even if there
1772 may be parts of the request that is not yet sent, since we can deal with
1773 the rest of the request in the PERFORM phase. */
1776 if(conn->httpversion < 20) { /* unless the connection is re-used and already
1778 switch(conn->negnpn) {
1779 case CURL_HTTP_VERSION_2_0:
1780 conn->httpversion = 20; /* we know we're on HTTP/2 now */
1781 result = Curl_http2_init(conn);
1785 result = Curl_http2_setup(conn);
1789 result = Curl_http2_switched(conn, NULL, 0);
1793 case CURL_HTTP_VERSION_1_1:
1794 /* continue with HTTP/1.1 when explicitly requested */
1797 /* and as fallback */
1802 /* prepare for a http2 request */
1803 result = Curl_http2_setup(conn);
1808 http = data->req.protop;
1810 if(!data->state.this_is_a_follow) {
1811 /* Free to avoid leaking memory on multiple requests*/
1812 free(data->state.first_host);
1814 data->state.first_host = strdup(conn->host.name);
1815 if(!data->state.first_host)
1816 return CURLE_OUT_OF_MEMORY;
1818 http->writebytecount = http->readbytecount = 0;
1820 if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
1822 httpreq = HTTPREQ_PUT;
1825 /* Now set the 'request' pointer to the proper request string */
1826 if(data->set.str[STRING_CUSTOMREQUEST])
1827 request = data->set.str[STRING_CUSTOMREQUEST];
1829 if(data->set.opt_no_body)
1832 DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
1835 case HTTPREQ_POST_FORM:
1841 default: /* this should never happen */
1852 /* The User-Agent string might have been allocated in url.c already, because
1853 it might have been used in the proxy connect, but if we have got a header
1854 with the user-agent string specified, we erase the previously made string
1856 if(Curl_checkheaders(conn, "User-Agent:")) {
1857 free(conn->allocptr.uagent);
1858 conn->allocptr.uagent=NULL;
1861 /* setup the authentication headers */
1862 result = Curl_http_output_auth(conn, request, ppath, FALSE);
1866 if((data->state.authhost.multi || data->state.authproxy.multi) &&
1867 (httpreq != HTTPREQ_GET) &&
1868 (httpreq != HTTPREQ_HEAD)) {
1869 /* Auth is required and we are not authenticated yet. Make a PUT or POST
1870 with content-length zero as a "probe". */
1871 conn->bits.authneg = TRUE;
1874 conn->bits.authneg = FALSE;
1876 Curl_safefree(conn->allocptr.ref);
1877 if(data->change.referer && !Curl_checkheaders(conn, "Referer:")) {
1878 conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
1879 if(!conn->allocptr.ref)
1880 return CURLE_OUT_OF_MEMORY;
1883 conn->allocptr.ref = NULL;
1885 #if !defined(CURL_DISABLE_COOKIES)
1886 if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie:"))
1887 addcookies = data->set.str[STRING_COOKIE];
1890 if(!Curl_checkheaders(conn, "Accept-Encoding:") &&
1891 data->set.str[STRING_ENCODING]) {
1892 Curl_safefree(conn->allocptr.accept_encoding);
1893 conn->allocptr.accept_encoding =
1894 aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
1895 if(!conn->allocptr.accept_encoding)
1896 return CURLE_OUT_OF_MEMORY;
1900 /* we only consider transfer-encoding magic if libz support is built-in */
1902 if(!Curl_checkheaders(conn, "TE:") &&
1903 data->set.http_transfer_encoding) {
1904 /* When we are to insert a TE: header in the request, we must also insert
1905 TE in a Connection: header, so we need to merge the custom provided
1906 Connection: header and prevent the original to get sent. Note that if
1907 the user has inserted his/hers own TE: header we don't do this magic
1908 but then assume that the user will handle it all! */
1909 char *cptr = Curl_checkheaders(conn, "Connection:");
1910 #define TE_HEADER "TE: gzip\r\n"
1912 Curl_safefree(conn->allocptr.te);
1914 /* Create the (updated) Connection: header */
1915 conn->allocptr.te = cptr? aprintf("%s, TE\r\n" TE_HEADER, cptr):
1916 strdup("Connection: TE\r\n" TE_HEADER);
1918 if(!conn->allocptr.te)
1919 return CURLE_OUT_OF_MEMORY;
1923 if(conn->httpversion == 20)
1924 /* In HTTP2 forbids Transfer-Encoding: chunked */
1927 ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
1929 /* Some kind of TE is requested, check if 'chunked' is chosen */
1930 data->req.upload_chunky =
1931 Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
1934 if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
1936 (data->state.infilesize == -1)) {
1937 if(conn->bits.authneg)
1938 /* don't enable chunked during auth neg */
1940 else if(use_http_1_1plus(data, conn)) {
1941 /* HTTP, upload, unknown file size and not HTTP 1.0 */
1942 data->req.upload_chunky = TRUE;
1945 failf(data, "Chunky upload is not supported by HTTP 1.0");
1946 return CURLE_UPLOAD_FAILED;
1950 /* else, no chunky upload */
1951 data->req.upload_chunky = FALSE;
1954 if(data->req.upload_chunky)
1955 te = "Transfer-Encoding: chunked\r\n";
1959 Curl_safefree(conn->allocptr.host);
1961 ptr = Curl_checkheaders(conn, "Host:");
1962 if(ptr && (!data->state.this_is_a_follow ||
1963 Curl_raw_equal(data->state.first_host, conn->host.name))) {
1964 #if !defined(CURL_DISABLE_COOKIES)
1965 /* If we have a given custom Host: header, we extract the host name in
1966 order to possibly use it for cookie reasons later on. We only allow the
1967 custom Host: header if this is NOT a redirect, as setting Host: in the
1968 redirected request is being out on thin ice. Except if the host name
1969 is the same as the first one! */
1970 char *cookiehost = Curl_copy_header_value(ptr);
1972 return CURLE_OUT_OF_MEMORY;
1974 /* ignore empty data */
1977 /* If the host begins with '[', we start searching for the port after
1978 the bracket has been closed */
1979 int startsearch = 0;
1980 if(*cookiehost == '[') {
1981 char *closingbracket;
1982 /* since the 'cookiehost' is an allocated memory area that will be
1983 freed later we cannot simply increment the pointer */
1984 memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
1985 closingbracket = strchr(cookiehost, ']');
1987 *closingbracket = 0;
1990 char *colon = strchr(cookiehost + startsearch, ':');
1992 *colon = 0; /* The host must not include an embedded port number */
1994 Curl_safefree(conn->allocptr.cookiehost);
1995 conn->allocptr.cookiehost = cookiehost;
1999 if(strcmp("Host:", ptr)) {
2000 conn->allocptr.host = aprintf("%s\r\n", ptr);
2001 if(!conn->allocptr.host)
2002 return CURLE_OUT_OF_MEMORY;
2005 /* when clearing the header */
2006 conn->allocptr.host = NULL;
2009 /* When building Host: headers, we must put the host name within
2010 [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
2012 if(((conn->given->protocol&CURLPROTO_HTTPS) &&
2013 (conn->remote_port == PORT_HTTPS)) ||
2014 ((conn->given->protocol&CURLPROTO_HTTP) &&
2015 (conn->remote_port == PORT_HTTP)) )
2016 /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
2017 the port number in the host string */
2018 conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
2019 conn->bits.ipv6_ip?"[":"",
2021 conn->bits.ipv6_ip?"]":"");
2023 conn->allocptr.host = aprintf("Host: %s%s%s:%hu\r\n",
2024 conn->bits.ipv6_ip?"[":"",
2026 conn->bits.ipv6_ip?"]":"",
2029 if(!conn->allocptr.host)
2030 /* without Host: we can't make a nice request */
2031 return CURLE_OUT_OF_MEMORY;
2034 #ifndef CURL_DISABLE_PROXY
2035 if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
2036 /* Using a proxy but does not tunnel through it */
2038 /* The path sent to the proxy is in fact the entire URL. But if the remote
2039 host is a IDN-name, we must make sure that the request we produce only
2040 uses the encoded host name! */
2041 if(conn->host.dispname != conn->host.name) {
2042 char *url = data->change.url;
2043 ptr = strstr(url, conn->host.dispname);
2045 /* This is where the display name starts in the URL, now replace this
2046 part with the encoded name. TODO: This method of replacing the host
2047 name is rather crude as I believe there's a slight risk that the
2048 user has entered a user name or password that contain the host name
2050 size_t currlen = strlen(conn->host.dispname);
2051 size_t newlen = strlen(conn->host.name);
2052 size_t urllen = strlen(url);
2056 newurl = malloc(urllen + newlen - currlen + 1);
2058 /* copy the part before the host name */
2059 memcpy(newurl, url, ptr - url);
2060 /* append the new host name instead of the old */
2061 memcpy(newurl + (ptr - url), conn->host.name, newlen);
2062 /* append the piece after the host name */
2063 memcpy(newurl + newlen + (ptr - url),
2064 ptr + currlen, /* copy the trailing zero byte too */
2065 urllen - (ptr-url) - currlen + 1);
2066 if(data->change.url_alloc) {
2067 Curl_safefree(data->change.url);
2068 data->change.url_alloc = FALSE;
2070 data->change.url = newurl;
2071 data->change.url_alloc = TRUE;
2074 return CURLE_OUT_OF_MEMORY;
2077 ppath = data->change.url;
2078 if(checkprefix("ftp://", ppath)) {
2079 if(data->set.proxy_transfer_mode) {
2080 /* when doing ftp, append ;type=<a|i> if not present */
2081 char *type = strstr(ppath, ";type=");
2082 if(type && type[6] && type[7] == 0) {
2083 switch (Curl_raw_toupper(type[6])) {
2093 char *p = ftp_typecode;
2094 /* avoid sending invalid URLs like ftp://example.com;type=i if the
2095 * user specified ftp://example.com without the slash */
2096 if(!*data->state.path && ppath[strlen(ppath) - 1] != '/') {
2099 snprintf(p, sizeof(ftp_typecode) - 1, ";type=%c",
2100 data->set.prefer_ascii ? 'a' : 'i');
2103 if(conn->bits.user_passwd && !conn->bits.userpwd_in_url)
2104 paste_ftp_userpwd = TRUE;
2107 #endif /* CURL_DISABLE_PROXY */
2109 if(HTTPREQ_POST_FORM == httpreq) {
2110 /* we must build the whole post sequence first, so that we have a size of
2111 the whole transfer before we start to send it */
2112 result = Curl_getformdata(data, &http->sendit, data->set.httppost,
2113 Curl_checkheaders(conn, "Content-Type:"),
2119 http->p_accept = Curl_checkheaders(conn, "Accept:")?NULL:"Accept: */*\r\n";
2121 if(( (HTTPREQ_POST == httpreq) ||
2122 (HTTPREQ_POST_FORM == httpreq) ||
2123 (HTTPREQ_PUT == httpreq) ) &&
2124 data->state.resume_from) {
2125 /**********************************************************************
2126 * Resuming upload in HTTP means that we PUT or POST and that we have
2127 * got a resume_from value set. The resume value has already created
2128 * a Range: header that will be passed along. We need to "fast forward"
2129 * the file the given number of bytes and decrease the assume upload
2130 * file size before we continue this venture in the dark lands of HTTP.
2131 *********************************************************************/
2133 if(data->state.resume_from < 0 ) {
2135 * This is meant to get the size of the present remote-file by itself.
2136 * We don't support this now. Bail out!
2138 data->state.resume_from = 0;
2141 if(data->state.resume_from && !data->state.this_is_a_follow) {
2142 /* do we still game? */
2144 /* Now, let's read off the proper amount of bytes from the
2146 if(conn->seek_func) {
2147 seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
2151 if(seekerr != CURL_SEEKFUNC_OK) {
2152 if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
2153 failf(data, "Could not seek stream");
2154 return CURLE_READ_ERROR;
2156 /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
2158 curl_off_t passed=0;
2160 size_t readthisamountnow =
2161 (data->state.resume_from - passed > CURL_OFF_T_C(BUFSIZE)) ?
2162 BUFSIZE : curlx_sotouz(data->state.resume_from - passed);
2164 size_t actuallyread =
2165 data->set.fread_func(data->state.buffer, 1, readthisamountnow,
2168 passed += actuallyread;
2169 if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
2170 /* this checks for greater-than only to make sure that the
2171 CURL_READFUNC_ABORT return code still aborts */
2172 failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T
2173 " bytes from the input", passed);
2174 return CURLE_READ_ERROR;
2176 } while(passed < data->state.resume_from);
2180 /* now, decrease the size of the read */
2181 if(data->state.infilesize>0) {
2182 data->state.infilesize -= data->state.resume_from;
2184 if(data->state.infilesize <= 0) {
2185 failf(data, "File already completely uploaded");
2186 return CURLE_PARTIAL_FILE;
2189 /* we've passed, proceed as normal */
2192 if(data->state.use_range) {
2194 * A range is selected. We use different headers whether we're downloading
2195 * or uploading and we always let customized headers override our internal
2196 * ones if any such are specified.
2198 if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
2199 !Curl_checkheaders(conn, "Range:")) {
2200 /* if a line like this was already allocated, free the previous one */
2201 free(conn->allocptr.rangeline);
2202 conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n",
2205 else if((httpreq != HTTPREQ_GET) &&
2206 !Curl_checkheaders(conn, "Content-Range:")) {
2208 /* if a line like this was already allocated, free the previous one */
2209 free(conn->allocptr.rangeline);
2211 if(data->set.set_resume_from < 0) {
2212 /* Upload resume was asked for, but we don't know the size of the
2213 remote part so we tell the server (and act accordingly) that we
2214 upload the whole file (again) */
2215 conn->allocptr.rangeline =
2216 aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T
2217 "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
2218 data->state.infilesize - 1, data->state.infilesize);
2221 else if(data->state.resume_from) {
2222 /* This is because "resume" was selected */
2223 curl_off_t total_expected_size=
2224 data->state.resume_from + data->state.infilesize;
2225 conn->allocptr.rangeline =
2226 aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
2227 "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
2228 data->state.range, total_expected_size-1,
2229 total_expected_size);
2232 /* Range was selected and then we just pass the incoming range and
2233 append total size */
2234 conn->allocptr.rangeline =
2235 aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n",
2236 data->state.range, data->state.infilesize);
2238 if(!conn->allocptr.rangeline)
2239 return CURLE_OUT_OF_MEMORY;
2243 /* Use 1.1 unless the user specifically asked for 1.0 or the server only
2245 httpstring= use_http_1_1plus(data, conn)?"1.1":"1.0";
2247 /* initialize a dynamic send-buffer */
2248 req_buffer = Curl_add_buffer_init();
2251 return CURLE_OUT_OF_MEMORY;
2253 /* add the main request stuff */
2254 /* GET/HEAD/POST/PUT */
2255 result = Curl_add_bufferf(req_buffer, "%s ", request);
2260 if(paste_ftp_userpwd)
2261 result = Curl_add_bufferf(req_buffer, "ftp://%s:%s@%s",
2262 conn->user, conn->passwd,
2263 ppath + sizeof("ftp://") - 1);
2265 result = Curl_add_buffer(req_buffer, ppath, strlen(ppath));
2270 Curl_add_bufferf(req_buffer,
2271 "%s" /* ftp typecode (;type=x) */
2272 " HTTP/%s\r\n" /* HTTP version */
2274 "%s" /* proxyuserpwd */
2277 "%s" /* user agent */
2280 "%s" /* accept-encoding */
2282 "%s" /* Proxy-Connection */
2283 "%s",/* transfer-encoding */
2287 (conn->allocptr.host?conn->allocptr.host:""),
2288 conn->allocptr.proxyuserpwd?
2289 conn->allocptr.proxyuserpwd:"",
2290 conn->allocptr.userpwd?conn->allocptr.userpwd:"",
2291 (data->state.use_range && conn->allocptr.rangeline)?
2292 conn->allocptr.rangeline:"",
2293 (data->set.str[STRING_USERAGENT] &&
2294 *data->set.str[STRING_USERAGENT] &&
2295 conn->allocptr.uagent)?
2296 conn->allocptr.uagent:"",
2297 http->p_accept?http->p_accept:"",
2298 conn->allocptr.te?conn->allocptr.te:"",
2299 (data->set.str[STRING_ENCODING] &&
2300 *data->set.str[STRING_ENCODING] &&
2301 conn->allocptr.accept_encoding)?
2302 conn->allocptr.accept_encoding:"",
2303 (data->change.referer && conn->allocptr.ref)?
2304 conn->allocptr.ref:"" /* Referer: <data> */,
2305 (conn->bits.httpproxy &&
2306 !conn->bits.tunnel_proxy &&
2307 !Curl_checkProxyheaders(conn, "Proxy-Connection:"))?
2308 "Proxy-Connection: Keep-Alive\r\n":"",
2312 /* clear userpwd to avoid re-using credentials from re-used connections */
2313 Curl_safefree(conn->allocptr.userpwd);
2316 * Free proxyuserpwd for Negotiate/NTLM. Cannot reuse as it is associated
2317 * with the connection and shouldn't be repeated over it either.
2319 switch (data->state.authproxy.picked) {
2320 case CURLAUTH_NEGOTIATE:
2322 case CURLAUTH_NTLM_WB:
2323 Curl_safefree(conn->allocptr.proxyuserpwd);
2330 if(!(conn->handler->flags&PROTOPT_SSL) &&
2331 conn->httpversion != 20 &&
2332 (data->set.httpversion == CURL_HTTP_VERSION_2_0)) {
2333 /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done
2335 result = Curl_http2_request_upgrade(req_buffer, conn);
2340 #if !defined(CURL_DISABLE_COOKIES)
2341 if(data->cookies || addcookies) {
2342 struct Cookie *co=NULL; /* no cookies from start */
2346 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
2347 co = Curl_cookie_getlist(data->cookies,
2348 conn->allocptr.cookiehost?
2349 conn->allocptr.cookiehost:host,
2351 (conn->handler->protocol&CURLPROTO_HTTPS)?
2353 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
2356 struct Cookie *store=co;
2357 /* now loop through all cookies that matched */
2361 result = Curl_add_bufferf(req_buffer, "Cookie: ");
2365 result = Curl_add_bufferf(req_buffer,
2366 "%s%s=%s", count?"; ":"",
2367 co->name, co->value);
2372 co = co->next; /* next cookie please */
2374 Curl_cookie_freelist(store, FALSE); /* free the cookie list */
2376 if(addcookies && !result) {
2378 result = Curl_add_bufferf(req_buffer, "Cookie: ");
2380 result = Curl_add_bufferf(req_buffer, "%s%s", count?"; ":"",
2385 if(count && !result)
2386 result = Curl_add_buffer(req_buffer, "\r\n", 2);
2393 if(data->set.timecondition) {
2394 result = Curl_add_timecondition(data, req_buffer);
2399 result = Curl_add_custom_headers(conn, FALSE, req_buffer);
2403 http->postdata = NULL; /* nothing to post at this point */
2404 Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */
2406 /* If 'authdone' is FALSE, we must not set the write socket index to the
2407 Curl_transfer() call below, as we're not ready to actually upload any
2412 case HTTPREQ_POST_FORM:
2413 if(!http->sendit || conn->bits.authneg) {
2414 /* nothing to post! */
2415 result = Curl_add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
2419 result = Curl_add_buffer_send(req_buffer, conn,
2420 &data->info.request_size, 0, FIRSTSOCKET);
2422 failf(data, "Failed sending POST request");
2424 /* setup variables for the upcoming transfer */
2425 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
2430 if(Curl_FormInit(&http->form, http->sendit)) {
2431 failf(data, "Internal HTTP POST error!");
2432 return CURLE_HTTP_POST_ERROR;
2435 /* Get the currently set callback function pointer and store that in the
2436 form struct since we might want the actual user-provided callback later
2437 on. The data->set.fread_func pointer itself will be changed for the
2438 multipart case to the function that returns a multipart formatted
2440 http->form.fread_func = data->set.fread_func;
2442 /* Set the read function to read from the generated form data */
2443 data->set.fread_func = (curl_read_callback)Curl_FormReader;
2444 data->set.in = &http->form;
2446 http->sending = HTTPSEND_BODY;
2448 if(!data->req.upload_chunky &&
2449 !Curl_checkheaders(conn, "Content-Length:")) {
2450 /* only add Content-Length if not uploading chunked */
2451 result = Curl_add_bufferf(req_buffer,
2452 "Content-Length: %" CURL_FORMAT_CURL_OFF_T
2453 "\r\n", http->postsize);
2458 result = expect100(data, conn, req_buffer);
2464 /* Get Content-Type: line from Curl_formpostheader.
2467 size_t linelength=0;
2468 contentType = Curl_formpostheader((void *)&http->form,
2471 failf(data, "Could not get Content-Type header line!");
2472 return CURLE_HTTP_POST_ERROR;
2475 result = Curl_add_buffer(req_buffer, contentType, linelength);
2480 /* make the request end in a true CRLF */
2481 result = Curl_add_buffer(req_buffer, "\r\n", 2);
2485 /* set upload size to the progress meter */
2486 Curl_pgrsSetUploadSize(data, http->postsize);
2488 /* fire away the whole request to the server */
2489 result = Curl_add_buffer_send(req_buffer, conn,
2490 &data->info.request_size, 0, FIRSTSOCKET);
2492 failf(data, "Failed sending POST request");
2494 /* setup variables for the upcoming transfer */
2495 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2496 &http->readbytecount, FIRSTSOCKET,
2497 &http->writebytecount);
2500 Curl_formclean(&http->sendit); /* free that whole lot */
2504 /* convert the form data */
2505 result = Curl_convert_form(data, http->sendit);
2507 Curl_formclean(&http->sendit); /* free that whole lot */
2513 case HTTPREQ_PUT: /* Let's PUT the data to the server! */
2515 if(conn->bits.authneg)
2518 postsize = data->state.infilesize;
2520 if((postsize != -1) && !data->req.upload_chunky &&
2521 !Curl_checkheaders(conn, "Content-Length:")) {
2522 /* only add Content-Length if not uploading chunked */
2523 result = Curl_add_bufferf(req_buffer,
2524 "Content-Length: %" CURL_FORMAT_CURL_OFF_T
2531 result = expect100(data, conn, req_buffer);
2536 result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
2540 /* set the upload size to the progress meter */
2541 Curl_pgrsSetUploadSize(data, postsize);
2543 /* this sends the buffer and frees all the buffer resources */
2544 result = Curl_add_buffer_send(req_buffer, conn,
2545 &data->info.request_size, 0, FIRSTSOCKET);
2547 failf(data, "Failed sending PUT request");
2549 /* prepare for transfer */
2550 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2551 &http->readbytecount, postsize?FIRSTSOCKET:-1,
2552 postsize?&http->writebytecount:NULL);
2558 /* this is the simple POST, using x-www-form-urlencoded style */
2560 if(conn->bits.authneg)
2563 /* figure out the size of the postfields */
2564 postsize = (data->state.infilesize != -1)?
2565 data->state.infilesize:
2566 (data->set.postfields? (curl_off_t)strlen(data->set.postfields):-1);
2569 /* We only set Content-Length and allow a custom Content-Length if
2570 we don't upload data chunked, as RFC2616 forbids us to set both
2571 kinds of headers (Transfer-Encoding: chunked and Content-Length) */
2572 if((postsize != -1) && !data->req.upload_chunky &&
2573 !Curl_checkheaders(conn, "Content-Length:")) {
2574 /* we allow replacing this header if not during auth negotiation,
2575 although it isn't very wise to actually set your own */
2576 result = Curl_add_bufferf(req_buffer,
2577 "Content-Length: %" CURL_FORMAT_CURL_OFF_T
2583 if(!Curl_checkheaders(conn, "Content-Type:")) {
2584 result = Curl_add_bufferf(req_buffer,
2585 "Content-Type: application/"
2586 "x-www-form-urlencoded\r\n");
2591 /* For really small posts we don't use Expect: headers at all, and for
2592 the somewhat bigger ones we allow the app to disable it. Just make
2593 sure that the expect100header is always set to the preferred value
2595 ptr = Curl_checkheaders(conn, "Expect:");
2597 data->state.expect100header =
2598 Curl_compareheader(ptr, "Expect:", "100-continue");
2600 else if(postsize > TINY_INITIAL_POST_SIZE || postsize < 0) {
2601 result = expect100(data, conn, req_buffer);
2606 data->state.expect100header = FALSE;
2608 if(data->set.postfields) {
2610 /* In HTTP2, we send request body in DATA frame regardless of
2612 if(conn->httpversion != 20 &&
2613 !data->state.expect100header &&
2614 (postsize < MAX_INITIAL_POST_SIZE)) {
2615 /* if we don't use expect: 100 AND
2616 postsize is less than MAX_INITIAL_POST_SIZE
2618 then append the post data to the HTTP request header. This limit
2619 is no magic limit but only set to prevent really huge POSTs to
2620 get the data duplicated with malloc() and family. */
2622 result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2626 if(!data->req.upload_chunky) {
2627 /* We're not sending it 'chunked', append it to the request
2628 already now to reduce the number if send() calls */
2629 result = Curl_add_buffer(req_buffer, data->set.postfields,
2631 included_body = postsize;
2635 /* Append the POST data chunky-style */
2636 result = Curl_add_bufferf(req_buffer, "%x\r\n", (int)postsize);
2638 result = Curl_add_buffer(req_buffer, data->set.postfields,
2641 result = Curl_add_buffer(req_buffer, "\r\n", 2);
2642 included_body = postsize + 2;
2646 result = Curl_add_buffer(req_buffer, "\x30\x0d\x0a\x0d\x0a", 5);
2652 /* Make sure the progress information is accurate */
2653 Curl_pgrsSetUploadSize(data, postsize);
2656 /* A huge POST coming up, do data separate from the request */
2657 http->postsize = postsize;
2658 http->postdata = data->set.postfields;
2660 http->sending = HTTPSEND_BODY;
2662 data->set.fread_func = (curl_read_callback)readmoredata;
2663 data->set.in = (void *)conn;
2665 /* set the upload size to the progress meter */
2666 Curl_pgrsSetUploadSize(data, http->postsize);
2668 result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2674 result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2678 if(data->req.upload_chunky && conn->bits.authneg) {
2679 /* Chunky upload is selected and we're negotiating auth still, send
2681 result = Curl_add_buffer(req_buffer,
2682 "\x30\x0d\x0a\x0d\x0a", 5);
2688 else if(data->state.infilesize) {
2689 /* set the upload size to the progress meter */
2690 Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
2692 /* set the pointer to mark that we will send the post body using the
2693 read callback, but only if we're not in authenticate
2695 if(!conn->bits.authneg) {
2696 http->postdata = (char *)&http->postdata;
2697 http->postsize = postsize;
2701 /* issue the request */
2702 result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size,
2703 (size_t)included_body, FIRSTSOCKET);
2706 failf(data, "Failed sending HTTP POST request");
2708 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2709 &http->readbytecount, http->postdata?FIRSTSOCKET:-1,
2710 http->postdata?&http->writebytecount:NULL);
2714 result = Curl_add_buffer(req_buffer, "\r\n", 2);
2718 /* issue the request */
2719 result = Curl_add_buffer_send(req_buffer, conn,
2720 &data->info.request_size, 0, FIRSTSOCKET);
2723 failf(data, "Failed sending HTTP request");
2725 /* HTTP GET/HEAD download: */
2726 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
2727 http->postdata?FIRSTSOCKET:-1,
2728 http->postdata?&http->writebytecount:NULL);
2733 if(http->writebytecount) {
2734 /* if a request-body has been sent off, we make sure this progress is noted
2736 Curl_pgrsSetUploadCounter(data, http->writebytecount);
2737 if(Curl_pgrsUpdate(conn))
2738 result = CURLE_ABORTED_BY_CALLBACK;
2740 if(http->writebytecount >= postsize) {
2741 /* already sent the entire request body, mark the "upload" as
2743 infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T
2744 " out of %" CURL_FORMAT_CURL_OFF_T " bytes\n",
2745 http->writebytecount, postsize);
2746 data->req.upload_done = TRUE;
2747 data->req.keepon &= ~KEEP_SEND; /* we're done writing */
2748 data->req.exp100 = EXP100_SEND_DATA; /* already sent */
2758 * Returns TRUE if member of the list matches prefix of string
2761 checkhttpprefix(struct SessionHandle *data,
2764 struct curl_slist *head = data->set.http200aliases;
2766 #ifdef CURL_DOES_CONVERSIONS
2767 /* convert from the network encoding using a scratch area */
2768 char *scratch = strdup(s);
2769 if(NULL == scratch) {
2770 failf (data, "Failed to allocate memory for conversion!");
2771 return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
2773 if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
2774 /* Curl_convert_from_network calls failf if unsuccessful */
2776 return FALSE; /* can't return CURLE_foobar so return FALSE */
2779 #endif /* CURL_DOES_CONVERSIONS */
2782 if(checkprefix(head->data, s)) {
2789 if(!rc && (checkprefix("HTTP/", s)))
2792 #ifdef CURL_DOES_CONVERSIONS
2794 #endif /* CURL_DOES_CONVERSIONS */
2798 #ifndef CURL_DISABLE_RTSP
2800 checkrtspprefix(struct SessionHandle *data,
2804 #ifdef CURL_DOES_CONVERSIONS
2805 /* convert from the network encoding using a scratch area */
2806 char *scratch = strdup(s);
2807 if(NULL == scratch) {
2808 failf (data, "Failed to allocate memory for conversion!");
2809 return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
2811 if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
2812 /* Curl_convert_from_network calls failf if unsuccessful */
2814 return FALSE; /* can't return CURLE_foobar so return FALSE */
2818 (void)data; /* unused */
2819 #endif /* CURL_DOES_CONVERSIONS */
2820 if(checkprefix("RTSP/", s))
2825 #endif /* CURL_DISABLE_RTSP */
2828 checkprotoprefix(struct SessionHandle *data, struct connectdata *conn,
2831 #ifndef CURL_DISABLE_RTSP
2832 if(conn->handler->protocol & CURLPROTO_RTSP)
2833 return checkrtspprefix(data, s);
2836 #endif /* CURL_DISABLE_RTSP */
2838 return checkhttpprefix(data, s);
2842 * header_append() copies a chunk of data to the end of the already received
2843 * header. We make sure that the full string fit in the allocated header
2844 * buffer, or else we enlarge it.
2846 static CURLcode header_append(struct SessionHandle *data,
2847 struct SingleRequest *k,
2850 if(k->hbuflen + length >= data->state.headersize) {
2851 /* We enlarge the header buffer as it is too small */
2856 if(k->hbuflen + length > CURL_MAX_HTTP_HEADER) {
2857 /* The reason to have a max limit for this is to avoid the risk of a bad
2858 server feeding libcurl with a never-ending header that will cause
2859 reallocs infinitely */
2860 failf (data, "Avoided giant realloc for header (max is %d)!",
2861 CURL_MAX_HTTP_HEADER);
2862 return CURLE_OUT_OF_MEMORY;
2865 newsize=CURLMAX((k->hbuflen+ length)*3/2, data->state.headersize*2);
2866 hbufp_index = k->hbufp - data->state.headerbuff;
2867 newbuff = realloc(data->state.headerbuff, newsize);
2869 failf (data, "Failed to alloc memory for big header!");
2870 return CURLE_OUT_OF_MEMORY;
2872 data->state.headersize=newsize;
2873 data->state.headerbuff = newbuff;
2874 k->hbufp = data->state.headerbuff + hbufp_index;
2876 memcpy(k->hbufp, k->str_start, length);
2878 k->hbuflen += length;
2884 static void print_http_error(struct SessionHandle *data)
2886 struct SingleRequest *k = &data->req;
2889 /* make sure that data->req.p points to the HTTP status line */
2890 if(!strncmp(beg, "HTTP", 4)) {
2892 /* skip to HTTP status code */
2893 beg = strchr(beg, ' ');
2896 /* find trailing CR */
2897 char end_char = '\r';
2898 char *end = strchr(beg, end_char);
2900 /* try to find LF (workaround for non-compliant HTTP servers) */
2902 end = strchr(beg, end_char);
2906 /* temporarily replace CR or LF by NUL and print the error message */
2908 failf(data, "The requested URL returned error: %s", beg);
2910 /* restore the previously replaced CR or LF */
2917 /* fall-back to printing the HTTP status code only */
2918 failf(data, "The requested URL returned error: %d", k->httpcode);
2922 * Read any HTTP header lines from the server and pass them to the client app.
2924 CURLcode Curl_http_readwrite_headers(struct SessionHandle *data,
2925 struct connectdata *conn,
2930 struct SingleRequest *k = &data->req;
2932 /* header line within buffer loop */
2938 /* str_start is start of line within buf */
2939 k->str_start = k->str;
2941 /* data is in network encoding so use 0x0a instead of '\n' */
2942 k->end_ptr = memchr(k->str_start, 0x0a, *nread);
2945 /* Not a complete header line within buffer, append the data to
2946 the end of the headerbuff. */
2947 result = header_append(data, k, *nread);
2951 if(!k->headerline && (k->hbuflen>5)) {
2952 /* make a first check that this looks like a protocol header */
2953 if(!checkprotoprefix(data, conn, data->state.headerbuff)) {
2954 /* this is not the beginning of a protocol first header line */
2956 k->badheader = HEADER_ALLBAD;
2961 break; /* read more and try again */
2964 /* decrease the size of the remaining (supposed) header line */
2965 rest_length = (k->end_ptr - k->str)+1;
2966 *nread -= (ssize_t)rest_length;
2968 k->str = k->end_ptr + 1; /* move past new line */
2970 full_length = k->str - k->str_start;
2972 result = header_append(data, k, full_length);
2976 k->end_ptr = k->hbufp;
2977 k->p = data->state.headerbuff;
2980 * We now have a FULL header line that p points to
2983 if(!k->headerline) {
2984 /* the first read header */
2985 if((k->hbuflen>5) &&
2986 !checkprotoprefix(data, conn, data->state.headerbuff)) {
2987 /* this is not the beginning of a protocol first header line */
2990 /* since there's more, this is a partial bad header */
2991 k->badheader = HEADER_PARTHEADER;
2993 /* this was all we read so it's all a bad header */
2994 k->badheader = HEADER_ALLBAD;
2995 *nread = (ssize_t)rest_length;
3001 /* headers are in network encoding so
3002 use 0x0a and 0x0d instead of '\n' and '\r' */
3003 if((0x0a == *k->p) || (0x0d == *k->p)) {
3005 /* Zero-length header line means end of headers! */
3007 #ifdef CURL_DOES_CONVERSIONS
3009 *k->p = '\r'; /* replace with CR in host encoding */
3010 k->p++; /* pass the CR byte */
3013 *k->p = '\n'; /* replace with LF in host encoding */
3014 k->p++; /* pass the LF byte */
3018 k->p++; /* pass the \r byte */
3020 k->p++; /* pass the \n byte */
3021 #endif /* CURL_DOES_CONVERSIONS */
3023 if(100 <= k->httpcode && 199 >= k->httpcode) {
3025 * We have made a HTTP PUT or POST and this is 1.1-lingo
3026 * that tells us that the server is OK with this and ready
3027 * to receive the data.
3028 * However, we'll get more headers now so we must get
3029 * back into the header-parsing state!
3032 k->headerline = 0; /* restart the header line counter */
3034 /* "A user agent MAY ignore unexpected 1xx status responses." */
3035 switch(k->httpcode) {
3037 /* if we did wait for this do enable write now! */
3039 k->exp100 = EXP100_SEND_DATA;
3040 k->keepon |= KEEP_SEND;
3044 /* Switching Protocols */
3045 if(k->upgr101 == UPGR101_REQUESTED) {
3046 infof(data, "Received 101\n");
3047 k->upgr101 = UPGR101_RECEIVED;
3049 /* switch to http2 now. The bytes after response headers
3050 are also processed here, otherwise they are lost. */
3051 result = Curl_http2_switched(conn, k->str, *nread);
3062 k->header = FALSE; /* no more header to parse! */
3064 if((k->size == -1) && !k->chunk && !conn->bits.close &&
3065 (conn->httpversion == 11) &&
3066 !(conn->handler->protocol & CURLPROTO_RTSP) &&
3067 data->set.httpreq != HTTPREQ_HEAD) {
3068 /* On HTTP 1.1, when connection is not to get closed, but no
3069 Content-Length nor Content-Encoding chunked have been
3070 received, according to RFC2616 section 4.4 point 5, we
3071 assume that the server will close the connection to
3072 signal the end of the document. */
3073 infof(data, "no chunk, no close, no size. Assume close to "
3075 connclose(conn, "HTTP: No end-of-message indicator");
3079 /* At this point we have some idea about the fate of the connection.
3080 If we are closing the connection it may result auth failure. */
3081 #if defined(USE_NTLM)
3082 if(conn->bits.close &&
3083 (((data->req.httpcode == 401) &&
3084 (conn->ntlm.state == NTLMSTATE_TYPE2)) ||
3085 ((data->req.httpcode == 407) &&
3086 (conn->proxyntlm.state == NTLMSTATE_TYPE2)))) {
3087 infof(data, "Connection closure while negotiating auth (HTTP 1.0?)\n");
3088 data->state.authproblem = TRUE;
3093 * When all the headers have been parsed, see if we should give
3094 * up and return an error.
3096 if(http_should_fail(conn)) {
3097 failf (data, "The requested URL returned error: %d",
3099 return CURLE_HTTP_RETURNED_ERROR;
3102 /* now, only output this if the header AND body are requested:
3104 writetype = CLIENTWRITE_HEADER;
3105 if(data->set.include_header)
3106 writetype |= CLIENTWRITE_BODY;
3108 headerlen = k->p - data->state.headerbuff;
3110 result = Curl_client_write(conn, writetype,
3111 data->state.headerbuff,
3116 data->info.header_size += (long)headerlen;
3117 data->req.headerbytecount += (long)headerlen;
3119 data->req.deductheadercount =
3120 (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
3122 if(!*stop_reading) {
3123 /* Curl_http_auth_act() checks what authentication methods
3124 * that are available and decides which one (if any) to
3125 * use. It will set 'newurl' if an auth method was picked. */
3126 result = Curl_http_auth_act(conn);
3131 if(k->httpcode >= 300) {
3132 if((!conn->bits.authneg) && !conn->bits.close &&
3133 !conn->bits.rewindaftersend) {
3135 * General treatment of errors when about to send data. Including :
3136 * "417 Expectation Failed", while waiting for 100-continue.
3138 * The check for close above is done simply because of something
3139 * else has already deemed the connection to get closed then
3140 * something else should've considered the big picture and we
3143 * rewindaftersend indicates that something has told libcurl to
3144 * continue sending even if it gets discarded
3147 switch(data->set.httpreq) {
3150 case HTTPREQ_POST_FORM:
3151 /* We got an error response. If this happened before the whole
3152 * request body has been sent we stop sending and mark the
3153 * connection for closure after we've read the entire response.
3155 if(!k->upload_done) {
3156 infof(data, "HTTP error before end of send, stop sending\n");
3157 connclose(conn, "Stop sending data before everything sent");
3158 k->upload_done = TRUE;
3159 k->keepon &= ~KEEP_SEND; /* don't send */
3160 if(data->state.expect100header)
3161 k->exp100 = EXP100_FAILED;
3165 default: /* default label present to avoid compiler warnings */
3171 if(conn->bits.rewindaftersend) {
3172 /* We rewind after a complete send, so thus we continue
3174 infof(data, "Keep sending data to get tossed away!\n");
3175 k->keepon |= KEEP_SEND;
3181 * really end-of-headers.
3183 * If we requested a "no body", this is a good time to get
3184 * out and return home.
3186 if(data->set.opt_no_body)
3187 *stop_reading = TRUE;
3189 /* If we know the expected size of this document, we set the
3190 maximum download size to the size of the expected
3191 document or else, we won't know when to stop reading!
3193 Note that we set the download maximum even if we read a
3194 "Connection: close" header, to make sure that
3195 "Content-Length: 0" still prevents us from attempting to
3196 read the (missing) response-body.
3198 /* According to RFC2616 section 4.4, we MUST ignore
3199 Content-Length: headers if we are now receiving data
3200 using chunked Transfer-Encoding.
3203 k->maxdownload = k->size = -1;
3206 /* We do this operation even if no_body is true, since this
3207 data might be retrieved later with curl_easy_getinfo()
3208 and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
3210 Curl_pgrsSetDownloadSize(data, k->size);
3211 k->maxdownload = k->size;
3214 /* If max download size is *zero* (nothing) we already
3215 have nothing and can safely return ok now! */
3216 if(0 == k->maxdownload)
3217 *stop_reading = TRUE;
3220 /* we make sure that this socket isn't read more now */
3221 k->keepon &= ~KEEP_RECV;
3224 if(data->set.verbose)
3225 Curl_debug(data, CURLINFO_HEADER_IN,
3226 k->str_start, headerlen, conn);
3227 break; /* exit header line loop */
3230 /* We continue reading headers, so reset the line-based
3231 header parsing variables hbufp && hbuflen */
3232 k->hbufp = data->state.headerbuff;
3238 * Checks for special headers coming up.
3241 if(!k->headerline++) {
3242 /* This is the first header, it MUST be the error code line
3243 or else we consider this to be the body right away! */
3244 int httpversion_major;
3245 int rtspversion_major;
3247 #ifdef CURL_DOES_CONVERSIONS
3248 #define HEADER1 scratch
3249 #define SCRATCHSIZE 21
3251 char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
3252 /* We can't really convert this yet because we
3253 don't know if it's the 1st header line or the body.
3254 So we do a partial conversion into a scratch area,
3255 leaving the data at k->p as-is.
3257 strncpy(&scratch[0], k->p, SCRATCHSIZE);
3258 scratch[SCRATCHSIZE] = 0; /* null terminate */
3259 res = Curl_convert_from_network(data,
3263 /* Curl_convert_from_network calls failf if unsuccessful */
3266 #define HEADER1 k->p /* no conversion needed, just use k->p */
3267 #endif /* CURL_DOES_CONVERSIONS */
3269 if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
3271 * https://tools.ietf.org/html/rfc7230#section-3.1.2
3273 * The reponse code is always a three-digit number in HTTP as the spec
3274 * says. We try to allow any number here, but we cannot make
3275 * guarantees on future behaviors since it isn't within the protocol.
3277 nc = sscanf(HEADER1,
3283 conn->httpversion += 10 * httpversion_major;
3285 if(k->upgr101 == UPGR101_RECEIVED) {
3286 /* supposedly upgraded to http2 now */
3287 if(conn->httpversion != 20)
3288 infof(data, "Lying server, not serving HTTP/2\n");
3292 /* this is the real world, not a Nirvana
3293 NCSA 1.5.x returns this crap when asked for HTTP/1.1
3295 nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
3296 conn->httpversion = 10;
3298 /* If user has set option HTTP200ALIASES,
3299 compare header line against list of aliases
3302 if(checkhttpprefix(data, k->p)) {
3305 conn->httpversion = 10;
3310 else if(conn->handler->protocol & CURLPROTO_RTSP) {
3311 nc = sscanf(HEADER1,
3317 conn->rtspversion += 10 * rtspversion_major;
3318 conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
3321 /* TODO: do we care about the other cases here? */
3327 data->info.httpcode = k->httpcode;
3329 data->info.httpversion = conn->httpversion;
3330 if(!data->state.httpversion ||
3331 data->state.httpversion > conn->httpversion)
3332 /* store the lowest server version we encounter */
3333 data->state.httpversion = conn->httpversion;
3336 * This code executes as part of processing the header. As a
3337 * result, it's not totally clear how to interpret the
3338 * response code yet as that depends on what other headers may
3339 * be present. 401 and 407 may be errors, but may be OK
3340 * depending on how authentication is working. Other codes
3341 * are definitely errors, so give up here.
3343 if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
3344 ((k->httpcode != 401) || !conn->bits.user_passwd) &&
3345 ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
3347 if(data->state.resume_from &&
3348 (data->set.httpreq==HTTPREQ_GET) &&
3349 (k->httpcode == 416)) {
3350 /* "Requested Range Not Satisfiable", just proceed and
3351 pretend this is no error */
3354 /* serious error, go home! */
3355 print_http_error(data);
3356 return CURLE_HTTP_RETURNED_ERROR;
3360 if(conn->httpversion == 10) {
3361 /* Default action for HTTP/1.0 must be to close, unless
3362 we get one of those fancy headers that tell us the
3363 server keeps it open for us! */
3364 infof(data, "HTTP 1.0, assume close after body\n");
3365 connclose(conn, "HTTP/1.0 close after body");
3367 else if(conn->httpversion == 20 ||
3368 (k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) {
3369 DEBUGF(infof(data, "HTTP/2 found, allow multiplexing\n"));
3371 /* HTTP/2 cannot blacklist multiplexing since it is a core
3372 functionality of the protocol */
3373 conn->bundle->multiuse = BUNDLE_MULTIPLEX;
3375 else if(conn->httpversion >= 11 &&
3376 !conn->bits.close) {
3377 /* If HTTP version is >= 1.1 and connection is persistent
3378 server supports pipelining. */
3380 "HTTP 1.1 or later with persistent connection, "
3381 "pipelining supported\n"));
3382 /* Activate pipelining if needed */
3384 if(!Curl_pipeline_site_blacklisted(data, conn))
3385 conn->bundle->multiuse = BUNDLE_PIPELINING;
3389 switch(k->httpcode) {
3391 /* (quote from RFC2616, section 10.2.5): The server has
3392 * fulfilled the request but does not need to return an
3393 * entity-body ... The 204 response MUST NOT include a
3394 * message-body, and thus is always terminated by the first
3395 * empty line after the header fields. */
3398 /* (quote from RFC2616, section 10.3.5): The 304 response
3399 * MUST NOT contain a message-body, and thus is always
3400 * terminated by the first empty line after the header
3402 if(data->set.timecondition)
3403 data->info.timecond = TRUE;
3406 k->ignorecl = TRUE; /* ignore Content-Length headers */
3414 k->header = FALSE; /* this is not a header line */
3419 result = Curl_convert_from_network(data, k->p, strlen(k->p));
3420 /* Curl_convert_from_network calls failf if unsuccessful */
3424 /* Check for Content-Length: header lines to get size */
3425 if(!k->ignorecl && !data->set.ignorecl &&
3426 checkprefix("Content-Length:", k->p)) {
3427 curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
3428 if(data->set.max_filesize &&
3429 contentlength > data->set.max_filesize) {
3430 failf(data, "Maximum file size exceeded");
3431 return CURLE_FILESIZE_EXCEEDED;
3433 if(contentlength >= 0) {
3434 k->size = contentlength;
3435 k->maxdownload = k->size;
3436 /* we set the progress download size already at this point
3437 just to make it easier for apps/callbacks to extract this
3438 info as soon as possible */
3439 Curl_pgrsSetDownloadSize(data, k->size);
3442 /* Negative Content-Length is really odd, and we know it
3443 happens for example when older Apache servers send large
3445 connclose(conn, "negative content-length");
3446 infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
3447 ", closing after transfer\n", contentlength);
3450 /* check for Content-Type: header lines to get the MIME-type */
3451 else if(checkprefix("Content-Type:", k->p)) {
3452 char *contenttype = Curl_copy_header_value(k->p);
3454 return CURLE_OUT_OF_MEMORY;
3456 /* ignore empty data */
3459 Curl_safefree(data->info.contenttype);
3460 data->info.contenttype = contenttype;
3463 else if(checkprefix("Server:", k->p)) {
3464 if(conn->httpversion < 20) {
3465 /* only do this for non-h2 servers */
3466 char *server_name = Curl_copy_header_value(k->p);
3468 /* Turn off pipelining if the server version is blacklisted */
3469 if(conn->bundle && (conn->bundle->multiuse == BUNDLE_PIPELINING)) {
3470 if(Curl_pipeline_server_blacklisted(data, server_name))
3471 conn->bundle->multiuse = BUNDLE_NO_MULTIUSE;
3476 else if((conn->httpversion == 10) &&
3477 conn->bits.httpproxy &&
3478 Curl_compareheader(k->p,
3479 "Proxy-Connection:", "keep-alive")) {
3481 * When a HTTP/1.0 reply comes when using a proxy, the
3482 * 'Proxy-Connection: keep-alive' line tells us the
3483 * connection will be kept alive for our pleasure.
3484 * Default action for 1.0 is to close.
3486 connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
3487 infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
3489 else if((conn->httpversion == 11) &&
3490 conn->bits.httpproxy &&
3491 Curl_compareheader(k->p,
3492 "Proxy-Connection:", "close")) {
3494 * We get a HTTP/1.1 response from a proxy and it says it'll
3495 * close down after this transfer.
3497 connclose(conn, "Proxy-Connection: asked to close after done");
3498 infof(data, "HTTP/1.1 proxy connection set close!\n");
3500 else if((conn->httpversion == 10) &&
3501 Curl_compareheader(k->p, "Connection:", "keep-alive")) {
3503 * A HTTP/1.0 reply with the 'Connection: keep-alive' line
3504 * tells us the connection will be kept alive for our
3505 * pleasure. Default action for 1.0 is to close.
3507 * [RFC2068, section 19.7.1] */
3508 connkeep(conn, "Connection keep-alive");
3509 infof(data, "HTTP/1.0 connection set to keep alive!\n");
3511 else if(Curl_compareheader(k->p, "Connection:", "close")) {
3513 * [RFC 2616, section 8.1.2.1]
3514 * "Connection: close" is HTTP/1.1 language and means that
3515 * the connection will close when this request has been
3518 connclose(conn, "Connection: close used");
3520 else if(checkprefix("Transfer-Encoding:", k->p)) {
3521 /* One or more encodings. We check for chunked and/or a compression
3524 * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
3525 * means that the server will send a series of "chunks". Each
3526 * chunk starts with line with info (including size of the
3527 * coming block) (terminated with CRLF), then a block of data
3528 * with the previously mentioned size. There can be any amount
3529 * of chunks, and a chunk-data set to zero signals the
3534 /* Find the first non-space letter */
3538 /* skip whitespaces and commas */
3539 while(*start && (ISSPACE(*start) || (*start == ',')))
3542 if(checkprefix("chunked", start)) {
3543 k->chunk = TRUE; /* chunks coming our way */
3545 /* init our chunky engine */
3546 Curl_httpchunk_init(conn);
3551 if(k->auto_decoding)
3552 /* TODO: we only support the first mentioned compression for now */
3555 if(checkprefix("identity", start)) {
3556 k->auto_decoding = IDENTITY;
3559 else if(checkprefix("deflate", start)) {
3560 k->auto_decoding = DEFLATE;
3563 else if(checkprefix("gzip", start)) {
3564 k->auto_decoding = GZIP;
3567 else if(checkprefix("x-gzip", start)) {
3568 k->auto_decoding = GZIP;
3578 else if(checkprefix("Content-Encoding:", k->p) &&
3579 (data->set.str[STRING_ENCODING] ||
3580 conn->httpversion == 20)) {
3582 * Process Content-Encoding. Look for the values: identity,
3583 * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
3584 * x-compress are the same as gzip and compress. (Sec 3.5 RFC
3585 * 2616). zlib cannot handle compress. However, errors are
3586 * handled further down when the response body is processed
3590 /* Find the first non-space letter */
3592 while(*start && ISSPACE(*start))
3595 /* Record the content-encoding for later use */
3596 if(checkprefix("identity", start))
3597 k->auto_decoding = IDENTITY;
3598 else if(checkprefix("deflate", start))
3599 k->auto_decoding = DEFLATE;
3600 else if(checkprefix("gzip", start)
3601 || checkprefix("x-gzip", start))
3602 k->auto_decoding = GZIP;
3604 else if(checkprefix("Content-Range:", k->p)) {
3605 /* Content-Range: bytes [num]-
3606 Content-Range: bytes: [num]-
3607 Content-Range: [num]-
3608 Content-Range: [asterisk]/[total]
3610 The second format was added since Sun's webserver
3611 JavaWebServer/1.1.1 obviously sends the header this way!
3612 The third added since some servers use that!
3613 The forth means the requested range was unsatisfied.
3616 char *ptr = k->p + 14;
3618 /* Move forward until first digit or asterisk */
3619 while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
3622 /* if it truly stopped on a digit */
3624 k->offset = curlx_strtoofft(ptr, NULL, 10);
3626 if(data->state.resume_from == k->offset)
3627 /* we asked for a resume and we got it */
3628 k->content_range = TRUE;
3631 data->state.resume_from = 0; /* get everything */
3633 #if !defined(CURL_DISABLE_COOKIES)
3634 else if(data->cookies &&
3635 checkprefix("Set-Cookie:", k->p)) {
3636 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
3637 CURL_LOCK_ACCESS_SINGLE);
3638 Curl_cookie_add(data,
3639 data->cookies, TRUE, k->p+11,
3640 /* If there is a custom-set Host: name, use it
3641 here, or else use real peer host name. */
3642 conn->allocptr.cookiehost?
3643 conn->allocptr.cookiehost:conn->host.name,
3645 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
3648 else if(checkprefix("Last-Modified:", k->p) &&
3649 (data->set.timecondition || data->set.get_filetime) ) {
3650 time_t secs=time(NULL);
3651 k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
3653 if(data->set.get_filetime)
3654 data->info.filetime = (long)k->timeofdoc;
3656 else if((checkprefix("WWW-Authenticate:", k->p) &&
3657 (401 == k->httpcode)) ||
3658 (checkprefix("Proxy-authenticate:", k->p) &&
3659 (407 == k->httpcode))) {
3661 bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
3662 char *auth = Curl_copy_header_value(k->p);
3664 return CURLE_OUT_OF_MEMORY;
3666 result = Curl_http_input_auth(conn, proxy, auth);
3673 else if((k->httpcode >= 300 && k->httpcode < 400) &&
3674 checkprefix("Location:", k->p) &&
3675 !data->req.location) {
3676 /* this is the URL that the server advises us to use instead */
3677 char *location = Curl_copy_header_value(k->p);
3679 return CURLE_OUT_OF_MEMORY;
3681 /* ignore empty data */
3684 data->req.location = location;
3686 if(data->set.http_follow_location) {
3687 DEBUGASSERT(!data->req.newurl);
3688 data->req.newurl = strdup(data->req.location); /* clone */
3689 if(!data->req.newurl)
3690 return CURLE_OUT_OF_MEMORY;
3692 /* some cases of POST and PUT etc needs to rewind the data
3693 stream at this point */
3694 result = http_perhapsrewind(conn);
3700 else if(conn->handler->protocol & CURLPROTO_RTSP) {
3701 result = Curl_rtsp_parseheader(conn, k->p);
3707 * End of header-checks. Write them to the client.
3710 writetype = CLIENTWRITE_HEADER;
3711 if(data->set.include_header)
3712 writetype |= CLIENTWRITE_BODY;
3714 if(data->set.verbose)
3715 Curl_debug(data, CURLINFO_HEADER_IN,
3716 k->p, (size_t)k->hbuflen, conn);
3718 result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
3722 data->info.header_size += (long)k->hbuflen;
3723 data->req.headerbytecount += (long)k->hbuflen;
3725 /* reset hbufp pointer && hbuflen */
3726 k->hbufp = data->state.headerbuff;
3729 while(!*stop_reading && *k->str); /* header line within buffer */
3731 /* We might have reached the end of the header part here, but
3732 there might be a non-header part left in the end of the read
3738 #endif /* CURL_DISABLE_HTTP */