Imported Upstream version 7.44.0
[platform/upstream/curl.git] / lib / http.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #ifndef CURL_DISABLE_HTTP
26
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
29 #endif
30
31 #ifdef HAVE_NETDB_H
32 #include <netdb.h>
33 #endif
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
36 #endif
37 #ifdef HAVE_NET_IF_H
38 #include <net/if.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43
44 #ifdef HAVE_SYS_PARAM_H
45 #include <sys/param.h>
46 #endif
47
48 #include "urldata.h"
49 #include <curl/curl.h>
50 #include "transfer.h"
51 #include "sendf.h"
52 #include "formdata.h"
53 #include "progress.h"
54 #include "curl_base64.h"
55 #include "cookie.h"
56 #include "strequal.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"
62 #include "url.h"
63 #include "share.h"
64 #include "hostip.h"
65 #include "http.h"
66 #include "select.h"
67 #include "parsedate.h" /* for the week day and month names */
68 #include "strtoofft.h"
69 #include "multiif.h"
70 #include "rawstr.h"
71 #include "content_encoding.h"
72 #include "http_proxy.h"
73 #include "warnless.h"
74 #include "non-ascii.h"
75 #include "conncache.h"
76 #include "pipeline.h"
77 #include "http2.h"
78 #include "connect.h"
79 #include "curl_printf.h"
80
81 /* The last #include files should be: */
82 #include "curl_memory.h"
83 #include "memdebug.h"
84
85 /*
86  * Forward declarations.
87  */
88
89 static int http_getsock_do(struct connectdata *conn,
90                            curl_socket_t *socks,
91                            int numsocks);
92 static int http_should_fail(struct connectdata *conn);
93
94 #ifdef USE_SSL
95 static CURLcode https_connecting(struct connectdata *conn, bool *done);
96 static int https_getsock(struct connectdata *conn,
97                          curl_socket_t *socks,
98                          int numsocks);
99 #else
100 #define https_connecting(x,y) CURLE_COULDNT_CONNECT
101 #endif
102
103 /*
104  * HTTP handler interface.
105  */
106 const struct Curl_handler Curl_handler_http = {
107   "HTTP",                               /* scheme */
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 */
124 };
125
126 #ifdef USE_SSL
127 /*
128  * HTTPS handler interface.
129  */
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 */
148 };
149 #endif
150
151
152 CURLcode Curl_http_setup_conn(struct connectdata *conn)
153 {
154   /* allocate the HTTP-specific struct for the SessionHandle, only to survive
155      during this request */
156   struct HTTP *http;
157   DEBUGASSERT(conn->data->req.protop == NULL);
158
159   http = calloc(1, sizeof(struct HTTP));
160   if(!http)
161     return CURLE_OUT_OF_MEMORY;
162
163   conn->data->req.protop = http;
164
165   Curl_http2_setup_conn(conn);
166   Curl_http2_setup_req(conn->data);
167
168   return CURLE_OK;
169 }
170
171 /*
172  * checkheaders() checks the linked list of custom HTTP headers for a
173  * particular header (prefix).
174  *
175  * Returns a pointer to the first matching header or NULL if none matched.
176  */
177 char *Curl_checkheaders(const struct connectdata *conn,
178                         const char *thisheader)
179 {
180   struct curl_slist *head;
181   size_t thislen = strlen(thisheader);
182   struct SessionHandle *data = conn->data;
183
184   for(head = data->set.headers;head; head=head->next) {
185     if(Curl_raw_nequal(head->data, thisheader, thislen))
186       return head->data;
187   }
188   return NULL;
189 }
190
191 /*
192  * checkProxyHeaders() checks the linked list of custom proxy headers
193  * if proxy headers are not available, then it will lookup into http header
194  * link list
195  *
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.
199  *
200  */
201 char *Curl_checkProxyheaders(const struct connectdata *conn,
202                              const char *thisheader)
203 {
204   struct curl_slist *head;
205   size_t thislen = strlen(thisheader);
206   struct SessionHandle *data = conn->data;
207
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))
212       return head->data;
213   }
214   return NULL;
215 }
216
217 /*
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.
222  */
223 char *Curl_copy_header_value(const char *header)
224 {
225   const char *start;
226   const char *end;
227   char *value;
228   size_t len;
229
230   DEBUGASSERT(header);
231
232   /* Find the end of the header name */
233   while(*header && (*header != ':'))
234     ++header;
235
236   if(*header)
237     /* Skip over colon */
238     ++header;
239
240   /* Find the first non-space letter */
241   start = header;
242   while(*start && ISSPACE(*start))
243     start++;
244
245   /* data is in the host encoding so
246      use '\r' and '\n' instead of 0x0d and 0x0a */
247   end = strchr(start, '\r');
248   if(!end)
249     end = strchr(start, '\n');
250   if(!end)
251     end = strchr(start, '\0');
252   if(!end)
253     return NULL;
254
255   /* skip all trailing space letters */
256   while((end > start) && ISSPACE(*end))
257     end--;
258
259   /* get length of the type */
260   len = end - start + 1;
261
262   value = malloc(len + 1);
263   if(!value)
264     return NULL;
265
266   memcpy(value, start, len);
267   value[len] = 0; /* zero terminate */
268
269   return value;
270 }
271
272 /*
273  * http_output_basic() sets up an Authorization: header (or the proxy version)
274  * for HTTP Basic authentication.
275  *
276  * Returns CURLcode.
277  */
278 static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
279 {
280   size_t size = 0;
281   char *authorization = NULL;
282   struct SessionHandle *data = conn->data;
283   char **userp;
284   const char *user;
285   const char *pwd;
286   CURLcode result;
287
288   if(proxy) {
289     userp = &conn->allocptr.proxyuserpwd;
290     user = conn->proxyuser;
291     pwd = conn->proxypasswd;
292   }
293   else {
294     userp = &conn->allocptr.userpwd;
295     user = conn->user;
296     pwd = conn->passwd;
297   }
298
299   snprintf(data->state.buffer, sizeof(data->state.buffer), "%s:%s", user, pwd);
300
301   result = Curl_base64_encode(data,
302                               data->state.buffer, strlen(data->state.buffer),
303                               &authorization, &size);
304   if(result)
305     return result;
306
307   if(!authorization)
308     return CURLE_REMOTE_ACCESS_DENIED;
309
310   free(*userp);
311   *userp = aprintf("%sAuthorization: Basic %s\r\n",
312                    proxy?"Proxy-":"",
313                    authorization);
314   free(authorization);
315   if(!*userp)
316     return CURLE_OUT_OF_MEMORY;
317
318   return CURLE_OK;
319 }
320
321 /* pickoneauth() selects the most favourable authentication method from the
322  * ones available and the ones we want.
323  *
324  * return TRUE if one was picked
325  */
326 static bool pickoneauth(struct auth *pick)
327 {
328   bool picked;
329   /* only deal with authentication we want */
330   unsigned long avail = pick->avail & pick->want;
331   picked = TRUE;
332
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;
345   else {
346     pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
347     picked = FALSE;
348   }
349   pick->avail = CURLAUTH_NONE; /* clear it here */
350
351   return picked;
352 }
353
354 /*
355  * Curl_http_perhapsrewind()
356  *
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
361  *     }
362  *     else {
363  *       If there is more than just a little data left to send, close
364  *       the current connection by force.
365  *     }
366  *   }
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
370  *     }
371  *     else {
372  *       rewind internally so that the operation can restart fine
373  *     }
374  *   }
375  * }
376  */
377 static CURLcode http_perhapsrewind(struct connectdata *conn)
378 {
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 */
383
384   if(!http)
385     /* If this is still NULL, we have not reach very far and we can safely
386        skip this rewinding stuff */
387     return CURLE_OK;
388
389   switch(data->set.httpreq) {
390   case HTTPREQ_GET:
391   case HTTPREQ_HEAD:
392     return CURLE_OK;
393   default:
394     break;
395   }
396
397   bytessent = http->writebytecount;
398
399   if(conn->bits.authneg) {
400     /* This is a state where we are known to be negotiating and we don't send
401        any data then. */
402     expectsend = 0;
403   }
404   else if(!conn->bits.protoconnstart) {
405     /* HTTP CONNECT in progress: there is no body */
406     expectsend = 0;
407   }
408   else {
409     /* figure out how much data we are expected to send */
410     switch(data->set.httpreq) {
411     case HTTPREQ_POST:
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);
416       break;
417     case HTTPREQ_PUT:
418       if(data->state.infilesize != -1)
419         expectsend = data->state.infilesize;
420       break;
421     case HTTPREQ_POST_FORM:
422       expectsend = http->postsize;
423       break;
424     default:
425       break;
426     }
427   }
428
429   conn->bits.rewindaftersend = FALSE; /* default */
430
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. */
443
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");
448         }
449
450         return CURLE_OK;
451       }
452
453       if(conn->bits.close)
454         /* this is already marked to get closed */
455         return CURLE_OK;
456
457       infof(data, "NTLM send, close instead of sending %"
458             CURL_FORMAT_CURL_OFF_T " bytes\n",
459             (curl_off_t)(expectsend - bytessent));
460     }
461 #endif
462
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 */
466
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 */
469   }
470
471   if(bytessent)
472     /* we rewind now at once since if we already sent something */
473     return Curl_readrewind(conn);
474
475   return CURLE_OK;
476 }
477
478 /*
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
482  * picked.
483  */
484
485 CURLcode Curl_http_auth_act(struct connectdata *conn)
486 {
487   struct SessionHandle *data = conn->data;
488   bool pickhost = FALSE;
489   bool pickproxy = FALSE;
490   CURLcode result = CURLE_OK;
491
492   if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
493     /* this is a transient response code, ignore */
494     return CURLE_OK;
495
496   if(data->state.authproblem)
497     return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
498
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);
503     if(!pickhost)
504       data->state.authproblem = TRUE;
505   }
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);
510     if(!pickproxy)
511       data->state.authproblem = TRUE;
512   }
513
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;
522
523     if((data->set.httpreq != HTTPREQ_GET) &&
524        (data->set.httpreq != HTTPREQ_HEAD) &&
525        !conn->bits.rewindaftersend) {
526       result = http_perhapsrewind(conn);
527       if(result)
528         return result;
529     }
530   }
531
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;
545     }
546   }
547   if(http_should_fail(conn)) {
548     failf (data, "The requested URL returned error: %d",
549            data->req.httpcode);
550     result = CURLE_HTTP_RETURNED_ERROR;
551   }
552
553   return result;
554 }
555
556
557 /*
558  * Output the correct authentication header depending on the auth type
559  * and whether or not it is to a proxy.
560  */
561 static CURLcode
562 output_auth_headers(struct connectdata *conn,
563                     struct auth *authstatus,
564                     const char *request,
565                     const char *path,
566                     bool proxy)
567 {
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;
572 #endif
573 #ifdef USE_SPNEGO
574   struct negotiatedata *negdata = proxy?
575     &data->state.proxyneg:&data->state.negotiate;
576 #endif
577
578 #ifdef CURL_DISABLE_CRYPTO_AUTH
579   (void)request;
580   (void)path;
581 #endif
582
583 #ifdef USE_SPNEGO
584   negdata->state = GSS_AUTHNONE;
585   if((authstatus->picked == CURLAUTH_NEGOTIATE) &&
586      negdata->context && !GSS_ERROR(negdata->status)) {
587     auth="Negotiate";
588     result = Curl_output_negotiate(conn, proxy);
589     if(result)
590       return result;
591     authstatus->done = TRUE;
592     negdata->state = GSS_AUTHSENT;
593   }
594   else
595 #endif
596 #ifdef USE_NTLM
597   if(authstatus->picked == CURLAUTH_NTLM) {
598     auth="NTLM";
599     result = Curl_output_ntlm(conn, proxy);
600     if(result)
601       return result;
602   }
603   else
604 #endif
605 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
606   if(authstatus->picked == CURLAUTH_NTLM_WB) {
607     auth="NTLM_WB";
608     result = Curl_output_ntlm_wb(conn, proxy);
609     if(result)
610       return result;
611   }
612   else
613 #endif
614 #ifndef CURL_DISABLE_CRYPTO_AUTH
615   if(authstatus->picked == CURLAUTH_DIGEST) {
616     auth="Digest";
617     result = Curl_output_digest(conn,
618                                 proxy,
619                                 (const unsigned char *)request,
620                                 (const unsigned char *)path);
621     if(result)
622       return result;
623   }
624   else
625 #endif
626   if(authstatus->picked == CURLAUTH_BASIC) {
627     /* 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:"))) {
632       auth="Basic";
633       result = http_output_basic(conn, proxy);
634       if(result)
635         return result;
636     }
637     /* NOTE: this function should set 'done' TRUE, as the other auth
638        functions work that way */
639     authstatus->done = TRUE;
640   }
641
642   if(auth) {
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;
648   }
649   else
650     authstatus->multi = FALSE;
651
652   return CURLE_OK;
653 }
654
655 /**
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
659  * done.
660  *
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
665  * tunnel"
666  *
667  * @returns CURLcode
668  */
669 CURLcode
670 Curl_http_output_auth(struct connectdata *conn,
671                       const char *request,
672                       const char *path,
673                       bool proxytunnel) /* TRUE if this is the request setting
674                                            up the proxy tunnel */
675 {
676   CURLcode result = CURLE_OK;
677   struct SessionHandle *data = conn->data;
678   struct auth *authhost;
679   struct auth *authproxy;
680
681   DEBUGASSERT(data);
682
683   authhost = &data->state.authhost;
684   authproxy = &data->state.authproxy;
685
686   if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
687      conn->bits.user_passwd)
688     /* continue please */;
689   else {
690     authhost->done = TRUE;
691     authproxy->done = TRUE;
692     return CURLE_OK; /* no authentication with no user or password */
693   }
694
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;
700
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;
706
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);
712     if(result)
713       return result;
714   }
715   else
716 #else
717   (void)proxytunnel;
718 #endif /* CURL_DISABLE_PROXY */
719     /* we have no proxy so let's pretend we're done authenticating
720        with it */
721     authproxy->done = TRUE;
722
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 ||
726      conn->bits.netrc ||
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);
731   }
732   else
733     authhost->done = TRUE;
734
735   return result;
736 }
737
738
739 /*
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.
743  */
744
745 CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
746                               const char *auth) /* the first non-space */
747 {
748   /*
749    * This resource requires authentication
750    */
751   struct SessionHandle *data = conn->data;
752
753 #ifdef USE_SPNEGO
754   struct negotiatedata *negdata = proxy?
755     &data->state.proxyneg:&data->state.negotiate;
756 #endif
757   unsigned long *availp;
758   struct auth *authp;
759
760   if(proxy) {
761     availp = &data->info.proxyauthavail;
762     authp = &data->state.authproxy;
763   }
764   else {
765     availp = &data->info.httpauthavail;
766     authp = &data->state.authhost;
767   }
768
769   /*
770    * Here we check if we want the specific single authentication (using ==) and
771    * if we do, we initiate usage of it.
772    *
773    * If the provided authentication is wanted as one out of several accepted
774    * types (using &), we OR this authentication type to the authavail
775    * variable.
776    *
777    * Note:
778    *
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
782    * (bit).
783    *
784    */
785
786   while(*auth) {
787 #ifdef USE_SPNEGO
788     if(checkprefix("Negotiate", auth)) {
789       *availp |= CURLAUTH_NEGOTIATE;
790       authp->avail |= CURLAUTH_NEGOTIATE;
791
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);
795           if(!result) {
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;
803           }
804           else
805             data->state.authproblem = TRUE;
806         }
807       }
808     }
809     else
810 #endif
811 #ifdef USE_NTLM
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);
820           if(!result) {
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;
828
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))
832                 auth++;
833               if(checkprefix("NTLM", auth)) {
834                 auth += strlen("NTLM");
835                 while(*auth && ISSPACE(*auth))
836                   auth++;
837                 if(*auth)
838                   if((conn->challenge_header = strdup(auth)) == NULL)
839                     return CURLE_OUT_OF_MEMORY;
840               }
841             }
842 #endif
843           }
844           else {
845             infof(data, "Authentication problem. Ignoring this.\n");
846             data->state.authproblem = TRUE;
847           }
848         }
849       }
850       else
851 #endif
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");
856           }
857           else {
858             CURLcode result;
859             *availp |= CURLAUTH_DIGEST;
860             authp->avail |= CURLAUTH_DIGEST;
861
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
865              * Digest. */
866             result = Curl_input_digest(conn, proxy, auth);
867             if(result) {
868               infof(data, "Authentication problem. Ignoring this.\n");
869               data->state.authproblem = TRUE;
870             }
871           }
872         }
873         else
874 #endif
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
881                  valid. */
882               authp->avail = CURLAUTH_NONE;
883               infof(data, "Authentication problem. Ignoring this.\n");
884               data->state.authproblem = TRUE;
885             }
886           }
887
888     /* there may be multiple methods on one line, so keep reading */
889     while(*auth && *auth != ',') /* read up to the next comma */
890       auth++;
891     if(*auth == ',') /* if we're on a comma, skip it */
892       auth++;
893     while(*auth && ISSPACE(*auth))
894       auth++;
895   }
896   return CURLE_OK;
897 }
898
899 /**
900  * http_should_fail() determines whether an HTTP response has gotten us
901  * into an error state or not.
902  *
903  * @param conn all information about the current connection
904  *
905  * @retval 0 communications should continue
906  *
907  * @retval 1 communications should not continue
908  */
909 static int http_should_fail(struct connectdata *conn)
910 {
911   struct SessionHandle *data;
912   int httpcode;
913
914   DEBUGASSERT(conn);
915   data = conn->data;
916   DEBUGASSERT(data);
917
918   httpcode = data->req.httpcode;
919
920   /*
921   ** If we haven't been asked to fail on error,
922   ** don't fail.
923   */
924   if(!data->set.http_fail_on_error)
925     return 0;
926
927   /*
928   ** Any code < 400 is never terminal.
929   */
930   if(httpcode < 400)
931     return 0;
932
933   /*
934   ** Any code >= 400 that's not 401 or 407 is always
935   ** a terminal error
936   */
937   if((httpcode != 401) &&
938       (httpcode != 407))
939     return 1;
940
941   /*
942   ** All we have left to deal with is 401 and 407
943   */
944   DEBUGASSERT((httpcode == 401) || (httpcode == 407));
945
946   /*
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.
954   **
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.
958   */
959
960   /*
961   ** Either we're not authenticating, or we're supposed to
962   ** be authenticating something else.  This is an error.
963   */
964   if((httpcode == 401) && !conn->bits.user_passwd)
965     return TRUE;
966   if((httpcode == 407) && !conn->bits.proxy_user_passwd)
967     return TRUE;
968
969   return data->state.authproblem;
970 }
971
972 /*
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.
977  *
978  * Returns the amount of bytes it filled the buffer with.
979  */
980 static size_t readmoredata(char *buffer,
981                            size_t size,
982                            size_t nitems,
983                            void *userp)
984 {
985   struct connectdata *conn = (struct connectdata *)userp;
986   struct HTTP *http = conn->data->req.protop;
987   size_t fullsize = size * nitems;
988
989   if(0 == http->postsize)
990     /* nothing to return */
991     return 0;
992
993   /* make sure that a HTTP request is never sent away chunked! */
994   conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
995
996   if(http->postsize <= (curl_off_t)fullsize) {
997     memcpy(buffer, http->postdata, (size_t)http->postsize);
998     fullsize = (size_t)http->postsize;
999
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;
1006
1007       http->sending++; /* move one step up */
1008
1009       http->backup.postsize=0;
1010     }
1011     else
1012       http->postsize = 0;
1013
1014     return fullsize;
1015   }
1016
1017   memcpy(buffer, http->postdata, fullsize);
1018   http->postdata += fullsize;
1019   http->postsize -= fullsize;
1020
1021   return fullsize;
1022 }
1023
1024 /* ------------------------------------------------------------------------- */
1025 /* add_buffer functions */
1026
1027 /*
1028  * Curl_add_buffer_init() sets up and returns a fine buffer struct
1029  */
1030 Curl_send_buffer *Curl_add_buffer_init(void)
1031 {
1032   return calloc(1, sizeof(Curl_send_buffer));
1033 }
1034
1035 /*
1036  * Curl_add_buffer_free() frees all associated resources.
1037  */
1038 void Curl_add_buffer_free(Curl_send_buffer *buff)
1039 {
1040   if(buff) /* deal with NULL input */
1041     free(buff->buffer);
1042   free(buff);
1043 }
1044
1045 /*
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.
1048  *
1049  * Returns CURLcode
1050  */
1051 CURLcode Curl_add_buffer_send(Curl_send_buffer *in,
1052                               struct connectdata *conn,
1053
1054                                /* add the number of sent bytes to this
1055                                   counter */
1056                               long *bytes_written,
1057
1058                                /* how much of the buffer contains body data */
1059                               size_t included_body_bytes,
1060                               int socketindex)
1061
1062 {
1063   ssize_t amount;
1064   CURLcode result;
1065   char *ptr;
1066   size_t size;
1067   struct HTTP *http = conn->data->req.protop;
1068   size_t sendsize;
1069   curl_socket_t sockfd;
1070   size_t headersize;
1071
1072   DEBUGASSERT(socketindex <= SECONDARYSOCKET);
1073
1074   sockfd = conn->sock[socketindex];
1075
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 */
1078
1079   ptr = in->buffer;
1080   size = in->size_used;
1081
1082   headersize = size - included_body_bytes; /* the initial part that isn't body
1083                                               is header */
1084
1085   DEBUGASSERT(size > included_body_bytes);
1086
1087   result = Curl_convert_to_network(conn->data, ptr, headersize);
1088   /* Curl_convert_to_network calls failf if unsuccessful */
1089   if(result) {
1090     /* conversion failed, free memory and return to the caller */
1091     Curl_add_buffer_free(in);
1092     return result;
1093   }
1094
1095
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.
1101     */
1102
1103     sendsize= (size > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:size;
1104
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.
1110     */
1111     memcpy(conn->data->state.uploadbuffer, ptr, sendsize);
1112     ptr = conn->data->state.uploadbuffer;
1113   }
1114   else
1115     sendsize = size;
1116
1117   result = Curl_write(conn, sockfd, ptr, sendsize, &amount);
1118
1119   if(!result) {
1120     /*
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).
1124      */
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;
1128
1129     if(conn->data->set.verbose) {
1130       /* this data _may_ contain binary stuff */
1131       Curl_debug(conn->data, CURLINFO_HEADER_OUT, ptr, headlen, conn);
1132       if(bodylen) {
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);
1137       }
1138     }
1139     if(bodylen)
1140       /* since we sent a piece of the body here, up the byte counter for it
1141          accordingly */
1142       http->writebytecount += bodylen;
1143
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
1146        64bit */
1147     *bytes_written += (long)amount;
1148
1149     if(http) {
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. */
1154
1155         size -= amount;
1156
1157         ptr = in->buffer + amount;
1158
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;
1164
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;
1170
1171         http->send_buffer = in;
1172         http->sending = HTTPSEND_REQUEST;
1173
1174         return CURLE_OK;
1175       }
1176       http->sending = HTTPSEND_BODY;
1177       /* the full buffer was sent, clean up and return */
1178     }
1179     else {
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.
1185
1186            This needs FIXing.
1187         */
1188         return CURLE_SEND_ERROR;
1189       else
1190         Curl_pipeline_leave_write(conn);
1191     }
1192   }
1193   Curl_add_buffer_free(in);
1194
1195   return result;
1196 }
1197
1198
1199 /*
1200  * add_bufferf() add the formatted input to the buffer.
1201  */
1202 CURLcode Curl_add_bufferf(Curl_send_buffer *in, const char *fmt, ...)
1203 {
1204   char *s;
1205   va_list ap;
1206   va_start(ap, fmt);
1207   s = vaprintf(fmt, ap); /* this allocs a new string to append */
1208   va_end(ap);
1209
1210   if(s) {
1211     CURLcode result = Curl_add_buffer(in, s, strlen(s));
1212     free(s);
1213     return result;
1214   }
1215   /* If we failed, we cleanup the whole buffer and return error */
1216   free(in->buffer);
1217   free(in);
1218   return CURLE_OUT_OF_MEMORY;
1219 }
1220
1221 /*
1222  * add_buffer() appends a memory chunk to the existing buffer
1223  */
1224 CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size)
1225 {
1226   char *new_rb;
1227   size_t new_size;
1228
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);
1234     free(in);
1235     return CURLE_OUT_OF_MEMORY;
1236   }
1237
1238   if(!in->buffer ||
1239      ((in->size_used + size) > (in->size_max - 1))) {
1240
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 */
1244
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;
1248     else
1249       new_size = (in->size_used+size)*2;
1250
1251     if(in->buffer)
1252       /* we have a buffer, enlarge the existing one */
1253       new_rb = realloc(in->buffer, new_size);
1254     else
1255       /* create a new buffer */
1256       new_rb = malloc(new_size);
1257
1258     if(!new_rb) {
1259       /* If we failed, we cleanup the whole buffer and return error */
1260       Curl_safefree(in->buffer);
1261       free(in);
1262       return CURLE_OUT_OF_MEMORY;
1263     }
1264
1265     in->buffer = new_rb;
1266     in->size_max = new_size;
1267   }
1268   memcpy(&in->buffer[in->size_used], inptr, size);
1269
1270   in->size_used += size;
1271
1272   return CURLE_OK;
1273 }
1274
1275 /* end of the add_buffer functions */
1276 /* ------------------------------------------------------------------------- */
1277
1278
1279
1280 /*
1281  * Curl_compareheader()
1282  *
1283  * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
1284  * Pass headers WITH the colon.
1285  */
1286 bool
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 */
1290 {
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
1294    * is preferred." */
1295
1296   size_t hlen = strlen(header);
1297   size_t clen;
1298   size_t len;
1299   const char *start;
1300   const char *end;
1301
1302   if(!Curl_raw_nequal(headerline, header, hlen))
1303     return FALSE; /* doesn't start with header */
1304
1305   /* pass the header */
1306   start = &headerline[hlen];
1307
1308   /* pass all white spaces */
1309   while(*start && ISSPACE(*start))
1310     start++;
1311
1312   /* find the end of the header line */
1313   end = strchr(start, '\r'); /* lines end with CRLF */
1314   if(!end) {
1315     /* in case there's a non-standard compliant line here */
1316     end = strchr(start, '\n');
1317
1318     if(!end)
1319       /* hm, there's no line ending here, use the zero byte! */
1320       end = strchr(start, '\0');
1321   }
1322
1323   len = end-start; /* length of the content part of the input line */
1324   clen = strlen(content); /* length of the word to find */
1325
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! */
1330   }
1331
1332   return FALSE; /* no match */
1333 }
1334
1335 /*
1336  * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
1337  * the generic Curl_connect().
1338  */
1339 CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
1340 {
1341   CURLcode result;
1342
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");
1346
1347   /* the CONNECT procedure might not have been completed */
1348   result = Curl_proxy_connect(conn);
1349   if(result)
1350     return result;
1351
1352   if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
1353     /* nothing else to do except wait right now - we're not done here. */
1354     return CURLE_OK;
1355
1356   if(conn->given->flags & PROTOPT_SSL) {
1357     /* perform SSL initialization */
1358     result = https_connecting(conn, done);
1359     if(result)
1360       return result;
1361   }
1362   else
1363     *done = TRUE;
1364
1365   return CURLE_OK;
1366 }
1367
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,
1373                            int numsocks)
1374 {
1375   /* write mode */
1376   (void)numsocks; /* unused, we trust it to be at least 1 */
1377   socks[0] = conn->sock[FIRSTSOCKET];
1378   return GETSOCK_WRITESOCK(0);
1379 }
1380
1381 #ifdef USE_SSL
1382 static CURLcode https_connecting(struct connectdata *conn, bool *done)
1383 {
1384   CURLcode result;
1385   DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
1386
1387   /* perform SSL initialization for this socket */
1388   result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
1389   if(result)
1390     connclose(conn, "Failed HTTPS connection");
1391
1392   return result;
1393 }
1394 #endif
1395
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,
1402                          int numsocks)
1403 {
1404   if(conn->handler->flags & PROTOPT_SSL) {
1405     struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
1406
1407     if(!numsocks)
1408       return GETSOCK_BLANK;
1409
1410     if(connssl->connecting_state == ssl_connect_2_writing) {
1411       /* write mode */
1412       socks[0] = conn->sock[FIRSTSOCKET];
1413       return GETSOCK_WRITESOCK(0);
1414     }
1415     else if(connssl->connecting_state == ssl_connect_2_reading) {
1416       /* read mode */
1417       socks[0] = conn->sock[FIRSTSOCKET];
1418       return GETSOCK_READSOCK(0);
1419     }
1420   }
1421   return CURLE_OK;
1422 }
1423 #else
1424 #ifdef USE_SSL
1425 static int https_getsock(struct connectdata *conn,
1426                          curl_socket_t *socks,
1427                          int numsocks)
1428 {
1429   (void)conn;
1430   (void)socks;
1431   (void)numsocks;
1432   return GETSOCK_BLANK;
1433 }
1434 #endif /* USE_SSL */
1435 #endif /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL */
1436
1437 /*
1438  * Curl_http_done() gets called from Curl_done() after a single HTTP request
1439  * has been performed.
1440  */
1441
1442 CURLcode Curl_http_done(struct connectdata *conn,
1443                         CURLcode status, bool premature)
1444 {
1445   struct SessionHandle *data = conn->data;
1446   struct HTTP *http = data->req.protop;
1447 #ifdef USE_NGHTTP2
1448   struct http_conn *httpc = &conn->proto.httpc;
1449 #endif
1450
1451   Curl_unencode_cleanup(conn);
1452
1453 #ifdef USE_SPNEGO
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);
1462   }
1463 #endif
1464
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 */
1468
1469   if(http == NULL)
1470     return CURLE_OK;
1471
1472   if(http->send_buffer) {
1473     Curl_add_buffer_free(http->send_buffer);
1474     http->send_buffer = NULL; /* clear the pointer */
1475   }
1476
1477 #ifdef USE_NGHTTP2
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]);
1484     }
1485     free(http->push_headers);
1486     http->push_headers = NULL;
1487   }
1488   if(http->stream_id) {
1489     nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0);
1490     http->stream_id = 0;
1491   }
1492 #endif
1493
1494   if(HTTPREQ_POST_FORM == data->set.httpreq) {
1495     data->req.bytecount = http->readbytecount + http->writebytecount;
1496
1497     Curl_formclean(&http->sendit); /* Now free that whole lot */
1498     if(http->form.fp) {
1499       /* a file being uploaded was left opened, close it! */
1500       fclose(http->form.fp);
1501       http->form.fp = NULL;
1502     }
1503   }
1504   else if(HTTPREQ_PUT == data->set.httpreq)
1505     data->req.bytecount = http->readbytecount + http->writebytecount;
1506
1507   if(status)
1508     return status;
1509
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;
1522   }
1523
1524   return CURLE_OK;
1525 }
1526
1527
1528 /*
1529  * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
1530  * to avoid it include:
1531  *
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
1535  * 1.0.
1536  */
1537 static bool use_http_1_1plus(const struct SessionHandle *data,
1538                              const struct connectdata *conn)
1539 {
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;
1545 }
1546
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)
1551 {
1552   CURLcode result = CURLE_OK;
1553   const char *ptr;
1554   data->state.expect100header = FALSE; /* default to false unless it is set
1555                                           to TRUE below */
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:");
1562     if(ptr) {
1563       data->state.expect100header =
1564         Curl_compareheader(ptr, "Expect:", "100-continue");
1565     }
1566     else {
1567       result = Curl_add_bufferf(req_buffer,
1568                          "Expect: 100-continue\r\n");
1569       if(!result)
1570         data->state.expect100header = TRUE;
1571     }
1572   }
1573   return result;
1574 }
1575
1576 enum proxy_use {
1577   HEADER_SERVER,  /* direct to server */
1578   HEADER_PROXY,   /* regular request to proxy */
1579   HEADER_CONNECT  /* sending CONNECT to a proxy */
1580 };
1581
1582 CURLcode Curl_add_custom_headers(struct connectdata *conn,
1583                                  bool is_connect,
1584                                  Curl_send_buffer *req_buffer)
1585 {
1586   char *ptr;
1587   struct curl_slist *h[2];
1588   struct curl_slist *headers;
1589   int numlists=1; /* by default */
1590   struct SessionHandle *data = conn->data;
1591   int i;
1592
1593   enum proxy_use proxy;
1594
1595   if(is_connect)
1596     proxy = HEADER_CONNECT;
1597   else
1598     proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
1599       HEADER_PROXY:HEADER_SERVER;
1600
1601   switch(proxy) {
1602   case HEADER_SERVER:
1603     h[0] = data->set.headers;
1604     break;
1605   case HEADER_PROXY:
1606     h[0] = data->set.headers;
1607     if(data->set.sep_headers) {
1608       h[1] = data->set.proxyheaders;
1609       numlists++;
1610     }
1611     break;
1612   case HEADER_CONNECT:
1613     if(data->set.sep_headers)
1614       h[0] = data->set.proxyheaders;
1615     else
1616       h[0] = data->set.headers;
1617     break;
1618   }
1619
1620   /* loop through one or two lists */
1621   for(i=0; i < numlists; i++) {
1622     headers = h[i];
1623
1624     while(headers) {
1625       ptr = strchr(headers->data, ':');
1626       if(ptr) {
1627         /* we require a colon for this to be a true header */
1628
1629         ptr++; /* pass the colon */
1630         while(*ptr && ISSPACE(*ptr))
1631           ptr++;
1632
1633         if(*ptr) {
1634           /* only send this if the contents was non-blank */
1635
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))
1640             ;
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))
1644             ;
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))
1649             ;
1650           else if(conn->allocptr.te &&
1651                   /* when asking for Transfer-Encoding, don't pass on a custom
1652                      Connection: */
1653                   checkprefix("Connection", headers->data))
1654             ;
1655           else {
1656             CURLcode result = Curl_add_bufferf(req_buffer, "%s\r\n",
1657                                                headers->data);
1658             if(result)
1659               return result;
1660           }
1661         }
1662       }
1663       else {
1664         ptr = strchr(headers->data, ';');
1665         if(ptr) {
1666
1667           ptr++; /* pass the semicolon */
1668           while(*ptr && ISSPACE(*ptr))
1669             ptr++;
1670
1671           if(*ptr) {
1672             /* this may be used for something else in the future */
1673           }
1674           else {
1675             if(*(--ptr) == ';') {
1676               CURLcode result;
1677
1678               /* send no-value custom header if terminated by semicolon */
1679               *ptr = ':';
1680               result = Curl_add_bufferf(req_buffer, "%s\r\n",
1681                                         headers->data);
1682               if(result)
1683                 return result;
1684             }
1685           }
1686         }
1687       }
1688       headers = headers->next;
1689     }
1690   }
1691   return CURLE_OK;
1692 }
1693
1694 CURLcode Curl_add_timecondition(struct SessionHandle *data,
1695                                 Curl_send_buffer *req_buffer)
1696 {
1697   const struct tm *tm;
1698   char *buf = data->state.buffer;
1699   struct tm keeptime;
1700   CURLcode result = Curl_gmtime(data->set.timevalue, &keeptime);
1701   if(result) {
1702     failf(data, "Invalid TIMEVALUE");
1703     return result;
1704   }
1705   tm = &keeptime;
1706
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).
1712    */
1713
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],
1718            tm->tm_mday,
1719            Curl_month[tm->tm_mon],
1720            tm->tm_year + 1900,
1721            tm->tm_hour,
1722            tm->tm_min,
1723            tm->tm_sec);
1724
1725   switch(data->set.timecondition) {
1726   case CURL_TIMECOND_IFMODSINCE:
1727   default:
1728     result = Curl_add_bufferf(req_buffer,
1729                               "If-Modified-Since: %s\r\n", buf);
1730     break;
1731   case CURL_TIMECOND_IFUNMODSINCE:
1732     result = Curl_add_bufferf(req_buffer,
1733                               "If-Unmodified-Since: %s\r\n", buf);
1734     break;
1735   case CURL_TIMECOND_LASTMOD:
1736     result = Curl_add_bufferf(req_buffer,
1737                               "Last-Modified: %s\r\n", buf);
1738     break;
1739   }
1740
1741   return result;
1742 }
1743
1744 /*
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
1747  * HTTP request.
1748  */
1749 CURLcode Curl_http(struct connectdata *conn, bool *done)
1750 {
1751   struct SessionHandle *data = conn->data;
1752   CURLcode result = CURLE_OK;
1753   struct HTTP *http;
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 */
1759   const char *ptr;
1760   const char *request;
1761   Curl_HttpReq httpreq = data->set.httpreq;
1762 #if !defined(CURL_DISABLE_COOKIES)
1763   char *addcookies = NULL;
1764 #endif
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;
1770
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. */
1774   *done = TRUE;
1775
1776   if(conn->httpversion < 20) { /* unless the connection is re-used and already
1777                                   http2 */
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);
1782       if(result)
1783         return result;
1784
1785       result = Curl_http2_setup(conn);
1786       if(result)
1787         return result;
1788
1789       result = Curl_http2_switched(conn, NULL, 0);
1790       if(result)
1791         return result;
1792       break;
1793     case CURL_HTTP_VERSION_1_1:
1794       /* continue with HTTP/1.1 when explicitly requested */
1795       break;
1796     default:
1797       /* and as fallback */
1798       break;
1799     }
1800   }
1801   else {
1802     /* prepare for a http2 request */
1803     result = Curl_http2_setup(conn);
1804     if(result)
1805       return result;
1806   }
1807
1808   http = data->req.protop;
1809
1810   if(!data->state.this_is_a_follow) {
1811     /* Free to avoid leaking memory on multiple requests*/
1812     free(data->state.first_host);
1813
1814     data->state.first_host = strdup(conn->host.name);
1815     if(!data->state.first_host)
1816       return CURLE_OUT_OF_MEMORY;
1817   }
1818   http->writebytecount = http->readbytecount = 0;
1819
1820   if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
1821      data->set.upload) {
1822     httpreq = HTTPREQ_PUT;
1823   }
1824
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];
1828   else {
1829     if(data->set.opt_no_body)
1830       request = "HEAD";
1831     else {
1832       DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
1833       switch(httpreq) {
1834       case HTTPREQ_POST:
1835       case HTTPREQ_POST_FORM:
1836         request = "POST";
1837         break;
1838       case HTTPREQ_PUT:
1839         request = "PUT";
1840         break;
1841       default: /* this should never happen */
1842       case HTTPREQ_GET:
1843         request = "GET";
1844         break;
1845       case HTTPREQ_HEAD:
1846         request = "HEAD";
1847         break;
1848       }
1849     }
1850   }
1851
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
1855      here. */
1856   if(Curl_checkheaders(conn, "User-Agent:")) {
1857     free(conn->allocptr.uagent);
1858     conn->allocptr.uagent=NULL;
1859   }
1860
1861   /* setup the authentication headers */
1862   result = Curl_http_output_auth(conn, request, ppath, FALSE);
1863   if(result)
1864     return result;
1865
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;
1872   }
1873   else
1874     conn->bits.authneg = FALSE;
1875
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;
1881   }
1882   else
1883     conn->allocptr.ref = NULL;
1884
1885 #if !defined(CURL_DISABLE_COOKIES)
1886   if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie:"))
1887     addcookies = data->set.str[STRING_COOKIE];
1888 #endif
1889
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;
1897   }
1898
1899 #ifdef HAVE_LIBZ
1900   /* we only consider transfer-encoding magic if libz support is built-in */
1901
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"
1911
1912     Curl_safefree(conn->allocptr.te);
1913
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);
1917
1918     if(!conn->allocptr.te)
1919       return CURLE_OUT_OF_MEMORY;
1920   }
1921 #endif
1922
1923   if(conn->httpversion == 20)
1924     /* In HTTP2 forbids Transfer-Encoding: chunked */
1925     ptr = NULL;
1926   else {
1927     ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
1928     if(ptr) {
1929       /* Some kind of TE is requested, check if 'chunked' is chosen */
1930       data->req.upload_chunky =
1931         Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
1932     }
1933     else {
1934       if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
1935          data->set.upload &&
1936          (data->state.infilesize == -1)) {
1937         if(conn->bits.authneg)
1938           /* don't enable chunked during auth neg */
1939           ;
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;
1943         }
1944         else {
1945           failf(data, "Chunky upload is not supported by HTTP 1.0");
1946           return CURLE_UPLOAD_FAILED;
1947         }
1948       }
1949       else {
1950         /* else, no chunky upload */
1951         data->req.upload_chunky = FALSE;
1952       }
1953
1954       if(data->req.upload_chunky)
1955         te = "Transfer-Encoding: chunked\r\n";
1956     }
1957   }
1958
1959   Curl_safefree(conn->allocptr.host);
1960
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);
1971     if(!cookiehost)
1972       return CURLE_OUT_OF_MEMORY;
1973     if(!*cookiehost)
1974       /* ignore empty data */
1975       free(cookiehost);
1976     else {
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, ']');
1986         if(closingbracket)
1987           *closingbracket = 0;
1988       }
1989       else {
1990         char *colon = strchr(cookiehost + startsearch, ':');
1991         if(colon)
1992           *colon = 0; /* The host must not include an embedded port number */
1993       }
1994       Curl_safefree(conn->allocptr.cookiehost);
1995       conn->allocptr.cookiehost = cookiehost;
1996     }
1997 #endif
1998
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;
2003     }
2004     else
2005       /* when clearing the header */
2006       conn->allocptr.host = NULL;
2007   }
2008   else {
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. */
2011
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?"[":"",
2020                                     host,
2021                                     conn->bits.ipv6_ip?"]":"");
2022     else
2023       conn->allocptr.host = aprintf("Host: %s%s%s:%hu\r\n",
2024                                     conn->bits.ipv6_ip?"[":"",
2025                                     host,
2026                                     conn->bits.ipv6_ip?"]":"",
2027                                     conn->remote_port);
2028
2029     if(!conn->allocptr.host)
2030       /* without Host: we can't make a nice request */
2031       return CURLE_OUT_OF_MEMORY;
2032   }
2033
2034 #ifndef CURL_DISABLE_PROXY
2035   if(conn->bits.httpproxy && !conn->bits.tunnel_proxy)  {
2036     /* Using a proxy but does not tunnel through it */
2037
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);
2044       if(ptr) {
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
2049            string. */
2050         size_t currlen = strlen(conn->host.dispname);
2051         size_t newlen = strlen(conn->host.name);
2052         size_t urllen = strlen(url);
2053
2054         char *newurl;
2055
2056         newurl = malloc(urllen + newlen - currlen + 1);
2057         if(newurl) {
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;
2069           }
2070           data->change.url = newurl;
2071           data->change.url_alloc = TRUE;
2072         }
2073         else
2074           return CURLE_OUT_OF_MEMORY;
2075       }
2076     }
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])) {
2084           case 'A':
2085           case 'D':
2086           case 'I':
2087             break;
2088           default:
2089             type = NULL;
2090           }
2091         }
2092         if(!type) {
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] != '/') {
2097             *p++ = '/';
2098           }
2099           snprintf(p, sizeof(ftp_typecode) - 1, ";type=%c",
2100                    data->set.prefer_ascii ? 'a' : 'i');
2101         }
2102       }
2103       if(conn->bits.user_passwd && !conn->bits.userpwd_in_url)
2104         paste_ftp_userpwd = TRUE;
2105     }
2106   }
2107 #endif /* CURL_DISABLE_PROXY */
2108
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:"),
2114                               &http->postsize);
2115     if(result)
2116       return result;
2117   }
2118
2119   http->p_accept = Curl_checkheaders(conn, "Accept:")?NULL:"Accept: */*\r\n";
2120
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      *********************************************************************/
2132
2133     if(data->state.resume_from < 0 ) {
2134       /*
2135        * This is meant to get the size of the present remote-file by itself.
2136        * We don't support this now. Bail out!
2137        */
2138       data->state.resume_from = 0;
2139     }
2140
2141     if(data->state.resume_from && !data->state.this_is_a_follow) {
2142       /* do we still game? */
2143
2144       /* Now, let's read off the proper amount of bytes from the
2145          input. */
2146       if(conn->seek_func) {
2147         seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
2148                                   SEEK_SET);
2149       }
2150
2151       if(seekerr != CURL_SEEKFUNC_OK) {
2152         if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
2153           failf(data, "Could not seek stream");
2154           return CURLE_READ_ERROR;
2155         }
2156         /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
2157         else {
2158           curl_off_t passed=0;
2159           do {
2160             size_t readthisamountnow =
2161               (data->state.resume_from - passed > CURL_OFF_T_C(BUFSIZE)) ?
2162               BUFSIZE : curlx_sotouz(data->state.resume_from - passed);
2163
2164             size_t actuallyread =
2165               data->set.fread_func(data->state.buffer, 1, readthisamountnow,
2166                                    data->set.in);
2167
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;
2175             }
2176           } while(passed < data->state.resume_from);
2177         }
2178       }
2179
2180       /* now, decrease the size of the read */
2181       if(data->state.infilesize>0) {
2182         data->state.infilesize -= data->state.resume_from;
2183
2184         if(data->state.infilesize <= 0) {
2185           failf(data, "File already completely uploaded");
2186           return CURLE_PARTIAL_FILE;
2187         }
2188       }
2189       /* we've passed, proceed as normal */
2190     }
2191   }
2192   if(data->state.use_range) {
2193     /*
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.
2197      */
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",
2203                                          data->state.range);
2204     }
2205     else if((httpreq != HTTPREQ_GET) &&
2206             !Curl_checkheaders(conn, "Content-Range:")) {
2207
2208       /* if a line like this was already allocated, free the previous one */
2209       free(conn->allocptr.rangeline);
2210
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);
2219
2220       }
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);
2230       }
2231       else {
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);
2237       }
2238       if(!conn->allocptr.rangeline)
2239         return CURLE_OUT_OF_MEMORY;
2240     }
2241   }
2242
2243   /* Use 1.1 unless the user specifically asked for 1.0 or the server only
2244      supports 1.0 */
2245   httpstring= use_http_1_1plus(data, conn)?"1.1":"1.0";
2246
2247   /* initialize a dynamic send-buffer */
2248   req_buffer = Curl_add_buffer_init();
2249
2250   if(!req_buffer)
2251     return CURLE_OUT_OF_MEMORY;
2252
2253   /* add the main request stuff */
2254   /* GET/HEAD/POST/PUT */
2255   result = Curl_add_bufferf(req_buffer, "%s ", request);
2256   if(result)
2257     return result;
2258
2259   /* url */
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);
2264   else
2265     result = Curl_add_buffer(req_buffer, ppath, strlen(ppath));
2266   if(result)
2267     return result;
2268
2269   result =
2270     Curl_add_bufferf(req_buffer,
2271                      "%s" /* ftp typecode (;type=x) */
2272                      " HTTP/%s\r\n" /* HTTP version */
2273                      "%s" /* host */
2274                      "%s" /* proxyuserpwd */
2275                      "%s" /* userpwd */
2276                      "%s" /* range */
2277                      "%s" /* user agent */
2278                      "%s" /* accept */
2279                      "%s" /* TE: */
2280                      "%s" /* accept-encoding */
2281                      "%s" /* referer */
2282                      "%s" /* Proxy-Connection */
2283                      "%s",/* transfer-encoding */
2284
2285                      ftp_typecode,
2286                      httpstring,
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":"",
2309                      te
2310       );
2311
2312   /* clear userpwd to avoid re-using credentials from re-used connections */
2313   Curl_safefree(conn->allocptr.userpwd);
2314
2315   /*
2316    * Free proxyuserpwd for Negotiate/NTLM. Cannot reuse as it is associated
2317    * with the connection and shouldn't be repeated over it either.
2318    */
2319   switch (data->state.authproxy.picked) {
2320   case CURLAUTH_NEGOTIATE:
2321   case CURLAUTH_NTLM:
2322   case CURLAUTH_NTLM_WB:
2323     Curl_safefree(conn->allocptr.proxyuserpwd);
2324     break;
2325   }
2326
2327   if(result)
2328     return result;
2329
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
2334        over SSL */
2335     result = Curl_http2_request_upgrade(req_buffer, conn);
2336     if(result)
2337       return result;
2338   }
2339
2340 #if !defined(CURL_DISABLE_COOKIES)
2341   if(data->cookies || addcookies) {
2342     struct Cookie *co=NULL; /* no cookies from start */
2343     int count=0;
2344
2345     if(data->cookies) {
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,
2350                                data->state.path,
2351                                (conn->handler->protocol&CURLPROTO_HTTPS)?
2352                                TRUE:FALSE);
2353       Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
2354     }
2355     if(co) {
2356       struct Cookie *store=co;
2357       /* now loop through all cookies that matched */
2358       while(co) {
2359         if(co->value) {
2360           if(0 == count) {
2361             result = Curl_add_bufferf(req_buffer, "Cookie: ");
2362             if(result)
2363               break;
2364           }
2365           result = Curl_add_bufferf(req_buffer,
2366                                     "%s%s=%s", count?"; ":"",
2367                                     co->name, co->value);
2368           if(result)
2369             break;
2370           count++;
2371         }
2372         co = co->next; /* next cookie please */
2373       }
2374       Curl_cookie_freelist(store, FALSE); /* free the cookie list */
2375     }
2376     if(addcookies && !result) {
2377       if(!count)
2378         result = Curl_add_bufferf(req_buffer, "Cookie: ");
2379       if(!result) {
2380         result = Curl_add_bufferf(req_buffer, "%s%s", count?"; ":"",
2381                                   addcookies);
2382         count++;
2383       }
2384     }
2385     if(count && !result)
2386       result = Curl_add_buffer(req_buffer, "\r\n", 2);
2387
2388     if(result)
2389       return result;
2390   }
2391 #endif
2392
2393   if(data->set.timecondition) {
2394     result = Curl_add_timecondition(data, req_buffer);
2395     if(result)
2396       return result;
2397   }
2398
2399   result = Curl_add_custom_headers(conn, FALSE, req_buffer);
2400   if(result)
2401     return result;
2402
2403   http->postdata = NULL;  /* nothing to post at this point */
2404   Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */
2405
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
2408      data yet. */
2409
2410   switch(httpreq) {
2411
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");
2416       if(result)
2417         return result;
2418
2419       result = Curl_add_buffer_send(req_buffer, conn,
2420                                     &data->info.request_size, 0, FIRSTSOCKET);
2421       if(result)
2422         failf(data, "Failed sending POST request");
2423       else
2424         /* setup variables for the upcoming transfer */
2425         Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
2426                             -1, NULL);
2427       break;
2428     }
2429
2430     if(Curl_FormInit(&http->form, http->sendit)) {
2431       failf(data, "Internal HTTP POST error!");
2432       return CURLE_HTTP_POST_ERROR;
2433     }
2434
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
2439        stream. */
2440     http->form.fread_func = data->set.fread_func;
2441
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;
2445
2446     http->sending = HTTPSEND_BODY;
2447
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);
2454       if(result)
2455         return result;
2456     }
2457
2458     result = expect100(data, conn, req_buffer);
2459     if(result)
2460       return result;
2461
2462     {
2463
2464       /* Get Content-Type: line from Curl_formpostheader.
2465        */
2466       char *contentType;
2467       size_t linelength=0;
2468       contentType = Curl_formpostheader((void *)&http->form,
2469                                         &linelength);
2470       if(!contentType) {
2471         failf(data, "Could not get Content-Type header line!");
2472         return CURLE_HTTP_POST_ERROR;
2473       }
2474
2475       result = Curl_add_buffer(req_buffer, contentType, linelength);
2476       if(result)
2477         return result;
2478     }
2479
2480     /* make the request end in a true CRLF */
2481     result = Curl_add_buffer(req_buffer, "\r\n", 2);
2482     if(result)
2483       return result;
2484
2485     /* set upload size to the progress meter */
2486     Curl_pgrsSetUploadSize(data, http->postsize);
2487
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);
2491     if(result)
2492       failf(data, "Failed sending POST request");
2493     else
2494       /* setup variables for the upcoming transfer */
2495       Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2496                           &http->readbytecount, FIRSTSOCKET,
2497                           &http->writebytecount);
2498
2499     if(result) {
2500       Curl_formclean(&http->sendit); /* free that whole lot */
2501       return result;
2502     }
2503
2504     /* convert the form data */
2505     result = Curl_convert_form(data, http->sendit);
2506     if(result) {
2507       Curl_formclean(&http->sendit); /* free that whole lot */
2508       return result;
2509     }
2510
2511     break;
2512
2513   case HTTPREQ_PUT: /* Let's PUT the data to the server! */
2514
2515     if(conn->bits.authneg)
2516       postsize = 0;
2517     else
2518       postsize = data->state.infilesize;
2519
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
2525                                 "\r\n", postsize);
2526       if(result)
2527         return result;
2528     }
2529
2530     if(postsize != 0) {
2531       result = expect100(data, conn, req_buffer);
2532       if(result)
2533         return result;
2534     }
2535
2536     result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
2537     if(result)
2538       return result;
2539
2540     /* set the upload size to the progress meter */
2541     Curl_pgrsSetUploadSize(data, postsize);
2542
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);
2546     if(result)
2547       failf(data, "Failed sending PUT request");
2548     else
2549       /* prepare for transfer */
2550       Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2551                           &http->readbytecount, postsize?FIRSTSOCKET:-1,
2552                           postsize?&http->writebytecount:NULL);
2553     if(result)
2554       return result;
2555     break;
2556
2557   case HTTPREQ_POST:
2558     /* this is the simple POST, using x-www-form-urlencoded style */
2559
2560     if(conn->bits.authneg)
2561       postsize = 0;
2562     else {
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);
2567     }
2568
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
2578                                 "\r\n", postsize);
2579       if(result)
2580         return result;
2581     }
2582
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");
2587       if(result)
2588         return result;
2589     }
2590
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
2594        here. */
2595     ptr = Curl_checkheaders(conn, "Expect:");
2596     if(ptr) {
2597       data->state.expect100header =
2598         Curl_compareheader(ptr, "Expect:", "100-continue");
2599     }
2600     else if(postsize > TINY_INITIAL_POST_SIZE || postsize < 0) {
2601       result = expect100(data, conn, req_buffer);
2602       if(result)
2603         return result;
2604     }
2605     else
2606       data->state.expect100header = FALSE;
2607
2608     if(data->set.postfields) {
2609
2610       /* In HTTP2, we send request body in DATA frame regardless of
2611          its size. */
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
2617
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. */
2621
2622         result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2623         if(result)
2624           return result;
2625
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,
2630                                    (size_t)postsize);
2631           included_body = postsize;
2632         }
2633         else {
2634           if(postsize) {
2635             /* Append the POST data chunky-style */
2636             result = Curl_add_bufferf(req_buffer, "%x\r\n", (int)postsize);
2637             if(!result) {
2638               result = Curl_add_buffer(req_buffer, data->set.postfields,
2639                                        (size_t)postsize);
2640               if(!result)
2641                 result = Curl_add_buffer(req_buffer, "\r\n", 2);
2642               included_body = postsize + 2;
2643             }
2644           }
2645           if(!result)
2646             result = Curl_add_buffer(req_buffer, "\x30\x0d\x0a\x0d\x0a", 5);
2647           /* 0  CR  LF  CR  LF */
2648           included_body += 5;
2649         }
2650         if(result)
2651           return result;
2652         /* Make sure the progress information is accurate */
2653         Curl_pgrsSetUploadSize(data, postsize);
2654       }
2655       else {
2656         /* A huge POST coming up, do data separate from the request */
2657         http->postsize = postsize;
2658         http->postdata = data->set.postfields;
2659
2660         http->sending = HTTPSEND_BODY;
2661
2662         data->set.fread_func = (curl_read_callback)readmoredata;
2663         data->set.in = (void *)conn;
2664
2665         /* set the upload size to the progress meter */
2666         Curl_pgrsSetUploadSize(data, http->postsize);
2667
2668         result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2669         if(result)
2670           return result;
2671       }
2672     }
2673     else {
2674       result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
2675       if(result)
2676         return result;
2677
2678       if(data->req.upload_chunky && conn->bits.authneg) {
2679         /* Chunky upload is selected and we're negotiating auth still, send
2680            end-of-data only */
2681         result = Curl_add_buffer(req_buffer,
2682                                  "\x30\x0d\x0a\x0d\x0a", 5);
2683         /* 0  CR  LF  CR  LF */
2684         if(result)
2685           return result;
2686       }
2687
2688       else if(data->state.infilesize) {
2689         /* set the upload size to the progress meter */
2690         Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
2691
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
2694            negotiation  */
2695         if(!conn->bits.authneg) {
2696           http->postdata = (char *)&http->postdata;
2697           http->postsize = postsize;
2698         }
2699       }
2700     }
2701     /* issue the request */
2702     result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size,
2703                                   (size_t)included_body, FIRSTSOCKET);
2704
2705     if(result)
2706       failf(data, "Failed sending HTTP POST request");
2707     else
2708       Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
2709                           &http->readbytecount, http->postdata?FIRSTSOCKET:-1,
2710                           http->postdata?&http->writebytecount:NULL);
2711     break;
2712
2713   default:
2714     result = Curl_add_buffer(req_buffer, "\r\n", 2);
2715     if(result)
2716       return result;
2717
2718     /* issue the request */
2719     result = Curl_add_buffer_send(req_buffer, conn,
2720                                   &data->info.request_size, 0, FIRSTSOCKET);
2721
2722     if(result)
2723       failf(data, "Failed sending HTTP request");
2724     else
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);
2729   }
2730   if(result)
2731     return result;
2732
2733   if(http->writebytecount) {
2734     /* if a request-body has been sent off, we make sure this progress is noted
2735        properly */
2736     Curl_pgrsSetUploadCounter(data, http->writebytecount);
2737     if(Curl_pgrsUpdate(conn))
2738       result = CURLE_ABORTED_BY_CALLBACK;
2739
2740     if(http->writebytecount >= postsize) {
2741       /* already sent the entire request body, mark the "upload" as
2742          complete */
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 */
2749     }
2750   }
2751
2752   return result;
2753 }
2754
2755 /*
2756  * checkhttpprefix()
2757  *
2758  * Returns TRUE if member of the list matches prefix of string
2759  */
2760 static bool
2761 checkhttpprefix(struct SessionHandle *data,
2762                 const char *s)
2763 {
2764   struct curl_slist *head = data->set.http200aliases;
2765   bool rc = FALSE;
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 */
2772   }
2773   if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
2774     /* Curl_convert_from_network calls failf if unsuccessful */
2775     free(scratch);
2776     return FALSE; /* can't return CURLE_foobar so return FALSE */
2777   }
2778   s = scratch;
2779 #endif /* CURL_DOES_CONVERSIONS */
2780
2781   while(head) {
2782     if(checkprefix(head->data, s)) {
2783       rc = TRUE;
2784       break;
2785     }
2786     head = head->next;
2787   }
2788
2789   if(!rc && (checkprefix("HTTP/", s)))
2790     rc = TRUE;
2791
2792 #ifdef CURL_DOES_CONVERSIONS
2793   free(scratch);
2794 #endif /* CURL_DOES_CONVERSIONS */
2795   return rc;
2796 }
2797
2798 #ifndef CURL_DISABLE_RTSP
2799 static bool
2800 checkrtspprefix(struct SessionHandle *data,
2801                 const char *s)
2802 {
2803
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 */
2810   }
2811   if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
2812     /* Curl_convert_from_network calls failf if unsuccessful */
2813     free(scratch);
2814     return FALSE; /* can't return CURLE_foobar so return FALSE */
2815   }
2816   s = scratch;
2817 #else
2818   (void)data; /* unused */
2819 #endif /* CURL_DOES_CONVERSIONS */
2820   if(checkprefix("RTSP/", s))
2821     return TRUE;
2822   else
2823     return FALSE;
2824 }
2825 #endif /* CURL_DISABLE_RTSP */
2826
2827 static bool
2828 checkprotoprefix(struct SessionHandle *data, struct connectdata *conn,
2829                  const char *s)
2830 {
2831 #ifndef CURL_DISABLE_RTSP
2832   if(conn->handler->protocol & CURLPROTO_RTSP)
2833     return checkrtspprefix(data, s);
2834 #else
2835   (void)conn;
2836 #endif /* CURL_DISABLE_RTSP */
2837
2838   return checkhttpprefix(data, s);
2839 }
2840
2841 /*
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.
2845  */
2846 static CURLcode header_append(struct SessionHandle *data,
2847                               struct SingleRequest *k,
2848                               size_t length)
2849 {
2850   if(k->hbuflen + length >= data->state.headersize) {
2851     /* We enlarge the header buffer as it is too small */
2852     char *newbuff;
2853     size_t hbufp_index;
2854     size_t newsize;
2855
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;
2863     }
2864
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);
2868     if(!newbuff) {
2869       failf (data, "Failed to alloc memory for big header!");
2870       return CURLE_OUT_OF_MEMORY;
2871     }
2872     data->state.headersize=newsize;
2873     data->state.headerbuff = newbuff;
2874     k->hbufp = data->state.headerbuff + hbufp_index;
2875   }
2876   memcpy(k->hbufp, k->str_start, length);
2877   k->hbufp += length;
2878   k->hbuflen += length;
2879   *k->hbufp = 0;
2880
2881   return CURLE_OK;
2882 }
2883
2884 static void print_http_error(struct SessionHandle *data)
2885 {
2886   struct SingleRequest *k = &data->req;
2887   char *beg = k->p;
2888
2889   /* make sure that data->req.p points to the HTTP status line */
2890   if(!strncmp(beg, "HTTP", 4)) {
2891
2892     /* skip to HTTP status code */
2893     beg = strchr(beg, ' ');
2894     if(beg && *++beg) {
2895
2896       /* find trailing CR */
2897       char end_char = '\r';
2898       char *end = strchr(beg, end_char);
2899       if(!end) {
2900         /* try to find LF (workaround for non-compliant HTTP servers) */
2901         end_char = '\n';
2902         end = strchr(beg, end_char);
2903       }
2904
2905       if(end) {
2906         /* temporarily replace CR or LF by NUL and print the error message */
2907         *end = '\0';
2908         failf(data, "The requested URL returned error: %s", beg);
2909
2910         /* restore the previously replaced CR or LF */
2911         *end = end_char;
2912         return;
2913       }
2914     }
2915   }
2916
2917   /* fall-back to printing the HTTP status code only */
2918   failf(data, "The requested URL returned error: %d", k->httpcode);
2919 }
2920
2921 /*
2922  * Read any HTTP header lines from the server and pass them to the client app.
2923  */
2924 CURLcode Curl_http_readwrite_headers(struct SessionHandle *data,
2925                                        struct connectdata *conn,
2926                                        ssize_t *nread,
2927                                        bool *stop_reading)
2928 {
2929   CURLcode result;
2930   struct SingleRequest *k = &data->req;
2931
2932   /* header line within buffer loop */
2933   do {
2934     size_t rest_length;
2935     size_t full_length;
2936     int writetype;
2937
2938     /* str_start is start of line within buf */
2939     k->str_start = k->str;
2940
2941     /* data is in network encoding so use 0x0a instead of '\n' */
2942     k->end_ptr = memchr(k->str_start, 0x0a, *nread);
2943
2944     if(!k->end_ptr) {
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);
2948       if(result)
2949         return result;
2950
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 */
2955           k->header = FALSE;
2956           k->badheader = HEADER_ALLBAD;
2957           break;
2958         }
2959       }
2960
2961       break; /* read more and try again */
2962     }
2963
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;
2967
2968     k->str = k->end_ptr + 1; /* move past new line */
2969
2970     full_length = k->str - k->str_start;
2971
2972     result = header_append(data, k, full_length);
2973     if(result)
2974       return result;
2975
2976     k->end_ptr = k->hbufp;
2977     k->p = data->state.headerbuff;
2978
2979     /****
2980      * We now have a FULL header line that p points to
2981      *****/
2982
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 */
2988         k->header = FALSE;
2989         if(*nread)
2990           /* since there's more, this is a partial bad header */
2991           k->badheader = HEADER_PARTHEADER;
2992         else {
2993           /* this was all we read so it's all a bad header */
2994           k->badheader = HEADER_ALLBAD;
2995           *nread = (ssize_t)rest_length;
2996         }
2997         break;
2998       }
2999     }
3000
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)) {
3004       size_t headerlen;
3005       /* Zero-length header line means end of headers! */
3006
3007 #ifdef CURL_DOES_CONVERSIONS
3008       if(0x0d == *k->p) {
3009         *k->p = '\r'; /* replace with CR in host encoding */
3010         k->p++;       /* pass the CR byte */
3011       }
3012       if(0x0a == *k->p) {
3013         *k->p = '\n'; /* replace with LF in host encoding */
3014         k->p++;       /* pass the LF byte */
3015       }
3016 #else
3017       if('\r' == *k->p)
3018         k->p++; /* pass the \r byte */
3019       if('\n' == *k->p)
3020         k->p++; /* pass the \n byte */
3021 #endif /* CURL_DOES_CONVERSIONS */
3022
3023       if(100 <= k->httpcode && 199 >= k->httpcode) {
3024         /*
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!
3030          */
3031         k->header = TRUE;
3032         k->headerline = 0; /* restart the header line counter */
3033
3034         /* "A user agent MAY ignore unexpected 1xx status responses." */
3035         switch(k->httpcode) {
3036         case 100:
3037           /* if we did wait for this do enable write now! */
3038           if(k->exp100) {
3039             k->exp100 = EXP100_SEND_DATA;
3040             k->keepon |= KEEP_SEND;
3041           }
3042           break;
3043         case 101:
3044           /* Switching Protocols */
3045           if(k->upgr101 == UPGR101_REQUESTED) {
3046             infof(data, "Received 101\n");
3047             k->upgr101 = UPGR101_RECEIVED;
3048
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);
3052             if(result)
3053               return result;
3054             *nread = 0;
3055           }
3056           break;
3057         default:
3058           break;
3059         }
3060       }
3061       else {
3062         k->header = FALSE; /* no more header to parse! */
3063
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 "
3074                 "signal end\n");
3075           connclose(conn, "HTTP: No end-of-message indicator");
3076         }
3077       }
3078
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;
3089       }
3090 #endif
3091
3092       /*
3093        * When all the headers have been parsed, see if we should give
3094        * up and return an error.
3095        */
3096       if(http_should_fail(conn)) {
3097         failf (data, "The requested URL returned error: %d",
3098                k->httpcode);
3099         return CURLE_HTTP_RETURNED_ERROR;
3100       }
3101
3102       /* now, only output this if the header AND body are requested:
3103        */
3104       writetype = CLIENTWRITE_HEADER;
3105       if(data->set.include_header)
3106         writetype |= CLIENTWRITE_BODY;
3107
3108       headerlen = k->p - data->state.headerbuff;
3109
3110       result = Curl_client_write(conn, writetype,
3111                                  data->state.headerbuff,
3112                                  headerlen);
3113       if(result)
3114         return result;
3115
3116       data->info.header_size += (long)headerlen;
3117       data->req.headerbytecount += (long)headerlen;
3118
3119       data->req.deductheadercount =
3120         (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
3121
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);
3127
3128         if(result)
3129           return result;
3130
3131         if(k->httpcode >= 300) {
3132           if((!conn->bits.authneg) && !conn->bits.close &&
3133              !conn->bits.rewindaftersend) {
3134             /*
3135              * General treatment of errors when about to send data. Including :
3136              * "417 Expectation Failed", while waiting for 100-continue.
3137              *
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
3141              * avoid this check.
3142              *
3143              * rewindaftersend indicates that something has told libcurl to
3144              * continue sending even if it gets discarded
3145              */
3146
3147             switch(data->set.httpreq) {
3148             case HTTPREQ_PUT:
3149             case HTTPREQ_POST:
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.
3154                */
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;
3162               }
3163               break;
3164
3165             default: /* default label present to avoid compiler warnings */
3166               break;
3167             }
3168           }
3169         }
3170
3171         if(conn->bits.rewindaftersend) {
3172           /* We rewind after a complete send, so thus we continue
3173              sending now */
3174           infof(data, "Keep sending data to get tossed away!\n");
3175           k->keepon |= KEEP_SEND;
3176         }
3177       }
3178
3179       if(!k->header) {
3180         /*
3181          * really end-of-headers.
3182          *
3183          * If we requested a "no body", this is a good time to get
3184          * out and return home.
3185          */
3186         if(data->set.opt_no_body)
3187           *stop_reading = TRUE;
3188         else {
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!
3192
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.
3197           */
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.
3201           */
3202           if(k->chunk)
3203             k->maxdownload = k->size = -1;
3204         }
3205         if(-1 != k->size) {
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. */
3209
3210           Curl_pgrsSetDownloadSize(data, k->size);
3211           k->maxdownload = k->size;
3212         }
3213
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;
3218
3219         if(*stop_reading) {
3220           /* we make sure that this socket isn't read more now */
3221           k->keepon &= ~KEEP_RECV;
3222         }
3223
3224         if(data->set.verbose)
3225           Curl_debug(data, CURLINFO_HEADER_IN,
3226                      k->str_start, headerlen, conn);
3227         break;          /* exit header line loop */
3228       }
3229
3230       /* We continue reading headers, so reset the line-based
3231          header parsing variables hbufp && hbuflen */
3232       k->hbufp = data->state.headerbuff;
3233       k->hbuflen = 0;
3234       continue;
3235     }
3236
3237     /*
3238      * Checks for special headers coming up.
3239      */
3240
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;
3246       int nc = 0;
3247 #ifdef CURL_DOES_CONVERSIONS
3248 #define HEADER1 scratch
3249 #define SCRATCHSIZE 21
3250       CURLcode res;
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.
3256       */
3257       strncpy(&scratch[0], k->p, SCRATCHSIZE);
3258       scratch[SCRATCHSIZE] = 0; /* null terminate */
3259       res = Curl_convert_from_network(data,
3260                                       &scratch[0],
3261                                       SCRATCHSIZE);
3262       if(res)
3263         /* Curl_convert_from_network calls failf if unsuccessful */
3264         return res;
3265 #else
3266 #define HEADER1 k->p /* no conversion needed, just use k->p */
3267 #endif /* CURL_DOES_CONVERSIONS */
3268
3269       if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
3270         /*
3271          * https://tools.ietf.org/html/rfc7230#section-3.1.2
3272          *
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.
3276          */
3277         nc = sscanf(HEADER1,
3278                     " HTTP/%d.%d %d",
3279                     &httpversion_major,
3280                     &conn->httpversion,
3281                     &k->httpcode);
3282         if(nc==3) {
3283           conn->httpversion += 10 * httpversion_major;
3284
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");
3289           }
3290         }
3291         else {
3292           /* this is the real world, not a Nirvana
3293              NCSA 1.5.x returns this crap when asked for HTTP/1.1
3294           */
3295           nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
3296           conn->httpversion = 10;
3297
3298           /* If user has set option HTTP200ALIASES,
3299              compare header line against list of aliases
3300           */
3301           if(!nc) {
3302             if(checkhttpprefix(data, k->p)) {
3303               nc = 1;
3304               k->httpcode = 200;
3305               conn->httpversion = 10;
3306             }
3307           }
3308         }
3309       }
3310       else if(conn->handler->protocol & CURLPROTO_RTSP) {
3311         nc = sscanf(HEADER1,
3312                     " RTSP/%d.%d %3d",
3313                     &rtspversion_major,
3314                     &conn->rtspversion,
3315                     &k->httpcode);
3316         if(nc==3) {
3317           conn->rtspversion += 10 * rtspversion_major;
3318           conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
3319         }
3320         else {
3321           /* TODO: do we care about the other cases here? */
3322           nc = 0;
3323         }
3324       }
3325
3326       if(nc) {
3327         data->info.httpcode = k->httpcode;
3328
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;
3334
3335         /*
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.
3342          */
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) ) {
3346
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 */
3352           }
3353           else {
3354             /* serious error, go home! */
3355             print_http_error(data);
3356             return CURLE_HTTP_RETURNED_ERROR;
3357           }
3358         }
3359
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");
3366         }
3367         else if(conn->httpversion == 20 ||
3368                 (k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) {
3369           DEBUGF(infof(data, "HTTP/2 found, allow multiplexing\n"));
3370
3371           /* HTTP/2 cannot blacklist multiplexing since it is a core
3372              functionality of the protocol */
3373           conn->bundle->multiuse = BUNDLE_MULTIPLEX;
3374         }
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. */
3379           DEBUGF(infof(data,
3380                        "HTTP 1.1 or later with persistent connection, "
3381                        "pipelining supported\n"));
3382           /* Activate pipelining if needed */
3383           if(conn->bundle) {
3384             if(!Curl_pipeline_site_blacklisted(data, conn))
3385               conn->bundle->multiuse = BUNDLE_PIPELINING;
3386           }
3387         }
3388
3389         switch(k->httpcode) {
3390         case 204:
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. */
3396           /* FALLTHROUGH */
3397         case 304:
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
3401            * fields.  */
3402           if(data->set.timecondition)
3403             data->info.timecond = TRUE;
3404           k->size=0;
3405           k->maxdownload=0;
3406           k->ignorecl = TRUE; /* ignore Content-Length headers */
3407           break;
3408         default:
3409           /* nothing */
3410           break;
3411         }
3412       }
3413       else {
3414         k->header = FALSE;   /* this is not a header line */
3415         break;
3416       }
3417     }
3418
3419     result = Curl_convert_from_network(data, k->p, strlen(k->p));
3420     /* Curl_convert_from_network calls failf if unsuccessful */
3421     if(result)
3422       return result;
3423
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;
3432       }
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);
3440       }
3441       else {
3442         /* Negative Content-Length is really odd, and we know it
3443            happens for example when older Apache servers send large
3444            files */
3445         connclose(conn, "negative content-length");
3446         infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
3447               ", closing after transfer\n", contentlength);
3448       }
3449     }
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);
3453       if(!contenttype)
3454         return CURLE_OUT_OF_MEMORY;
3455       if(!*contenttype)
3456         /* ignore empty data */
3457         free(contenttype);
3458       else {
3459         Curl_safefree(data->info.contenttype);
3460         data->info.contenttype = contenttype;
3461       }
3462     }
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);
3467
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;
3472         }
3473         free(server_name);
3474       }
3475     }
3476     else if((conn->httpversion == 10) &&
3477             conn->bits.httpproxy &&
3478             Curl_compareheader(k->p,
3479                                "Proxy-Connection:", "keep-alive")) {
3480       /*
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.
3485        */
3486       connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
3487       infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
3488     }
3489     else if((conn->httpversion == 11) &&
3490             conn->bits.httpproxy &&
3491             Curl_compareheader(k->p,
3492                                "Proxy-Connection:", "close")) {
3493       /*
3494        * We get a HTTP/1.1 response from a proxy and it says it'll
3495        * close down after this transfer.
3496        */
3497       connclose(conn, "Proxy-Connection: asked to close after done");
3498       infof(data, "HTTP/1.1 proxy connection set close!\n");
3499     }
3500     else if((conn->httpversion == 10) &&
3501             Curl_compareheader(k->p, "Connection:", "keep-alive")) {
3502       /*
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.
3506        *
3507        * [RFC2068, section 19.7.1] */
3508       connkeep(conn, "Connection keep-alive");
3509       infof(data, "HTTP/1.0 connection set to keep alive!\n");
3510     }
3511     else if(Curl_compareheader(k->p, "Connection:", "close")) {
3512       /*
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
3516        * served.
3517        */
3518       connclose(conn, "Connection: close used");
3519     }
3520     else if(checkprefix("Transfer-Encoding:", k->p)) {
3521       /* One or more encodings. We check for chunked and/or a compression
3522          algorithm. */
3523       /*
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
3530        * end-of-chunks. */
3531
3532       char *start;
3533
3534       /* Find the first non-space letter */
3535       start = k->p + 18;
3536
3537       for(;;) {
3538         /* skip whitespaces and commas */
3539         while(*start && (ISSPACE(*start) || (*start == ',')))
3540           start++;
3541
3542         if(checkprefix("chunked", start)) {
3543           k->chunk = TRUE; /* chunks coming our way */
3544
3545           /* init our chunky engine */
3546           Curl_httpchunk_init(conn);
3547
3548           start += 7;
3549         }
3550
3551         if(k->auto_decoding)
3552           /* TODO: we only support the first mentioned compression for now */
3553           break;
3554
3555         if(checkprefix("identity", start)) {
3556           k->auto_decoding = IDENTITY;
3557           start += 8;
3558         }
3559         else if(checkprefix("deflate", start)) {
3560           k->auto_decoding = DEFLATE;
3561           start += 7;
3562         }
3563         else if(checkprefix("gzip", start)) {
3564           k->auto_decoding = GZIP;
3565           start += 4;
3566         }
3567         else if(checkprefix("x-gzip", start)) {
3568           k->auto_decoding = GZIP;
3569           start += 6;
3570         }
3571         else
3572           /* unknown! */
3573           break;
3574
3575       }
3576
3577     }
3578     else if(checkprefix("Content-Encoding:", k->p) &&
3579             (data->set.str[STRING_ENCODING] ||
3580              conn->httpversion == 20)) {
3581       /*
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
3587        */
3588       char *start;
3589
3590       /* Find the first non-space letter */
3591       start = k->p + 17;
3592       while(*start && ISSPACE(*start))
3593         start++;
3594
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;
3603     }
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]
3609
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.
3614       */
3615
3616       char *ptr = k->p + 14;
3617
3618       /* Move forward until first digit or asterisk */
3619       while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
3620         ptr++;
3621
3622       /* if it truly stopped on a digit */
3623       if(ISDIGIT(*ptr)) {
3624         k->offset = curlx_strtoofft(ptr, NULL, 10);
3625
3626         if(data->state.resume_from == k->offset)
3627           /* we asked for a resume and we got it */
3628           k->content_range = TRUE;
3629       }
3630       else
3631         data->state.resume_from = 0; /* get everything */
3632     }
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,
3644                       data->state.path);
3645       Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
3646     }
3647 #endif
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:"),
3652                                   &secs);
3653       if(data->set.get_filetime)
3654         data->info.filetime = (long)k->timeofdoc;
3655     }
3656     else if((checkprefix("WWW-Authenticate:", k->p) &&
3657              (401 == k->httpcode)) ||
3658             (checkprefix("Proxy-authenticate:", k->p) &&
3659              (407 == k->httpcode))) {
3660
3661       bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
3662       char *auth = Curl_copy_header_value(k->p);
3663       if(!auth)
3664         return CURLE_OUT_OF_MEMORY;
3665
3666       result = Curl_http_input_auth(conn, proxy, auth);
3667
3668       free(auth);
3669
3670       if(result)
3671         return result;
3672     }
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);
3678       if(!location)
3679         return CURLE_OUT_OF_MEMORY;
3680       if(!*location)
3681         /* ignore empty data */
3682         free(location);
3683       else {
3684         data->req.location = location;
3685
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;
3691
3692           /* some cases of POST and PUT etc needs to rewind the data
3693              stream at this point */
3694           result = http_perhapsrewind(conn);
3695           if(result)
3696             return result;
3697         }
3698       }
3699     }
3700     else if(conn->handler->protocol & CURLPROTO_RTSP) {
3701       result = Curl_rtsp_parseheader(conn, k->p);
3702       if(result)
3703         return result;
3704     }
3705
3706     /*
3707      * End of header-checks. Write them to the client.
3708      */
3709
3710     writetype = CLIENTWRITE_HEADER;
3711     if(data->set.include_header)
3712       writetype |= CLIENTWRITE_BODY;
3713
3714     if(data->set.verbose)
3715       Curl_debug(data, CURLINFO_HEADER_IN,
3716                  k->p, (size_t)k->hbuflen, conn);
3717
3718     result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
3719     if(result)
3720       return result;
3721
3722     data->info.header_size += (long)k->hbuflen;
3723     data->req.headerbytecount += (long)k->hbuflen;
3724
3725     /* reset hbufp pointer && hbuflen */
3726     k->hbufp = data->state.headerbuff;
3727     k->hbuflen = 0;
3728   }
3729   while(!*stop_reading && *k->str); /* header line within buffer */
3730
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
3733      buffer. */
3734
3735   return CURLE_OK;
3736 }
3737
3738 #endif /* CURL_DISABLE_HTTP */