Coverage Report

Created: 2026-12-01 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/http.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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 https://curl.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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
#include "urldata.h"
26
27
#ifndef CURL_DISABLE_HTTP
28
29
#ifdef HAVE_NETINET_IN_H
30
#include <netinet/in.h>
31
#endif
32
33
#ifdef HAVE_NETDB_H
34
#include <netdb.h>
35
#endif
36
#ifdef HAVE_ARPA_INET_H
37
#include <arpa/inet.h>
38
#endif
39
#ifdef HAVE_NET_IF_H
40
#include <net/if.h>
41
#endif
42
#ifdef HAVE_SYS_IOCTL_H
43
#include <sys/ioctl.h>
44
#endif
45
46
#ifdef HAVE_SYS_PARAM_H
47
#include <sys/param.h>
48
#endif
49
50
#include "transfer.h"
51
#include "sendf.h"
52
#include "curl_trc.h"
53
#include "formdata.h"
54
#include "mime.h"
55
#include "progress.h"
56
#include "curlx/base64.h"
57
#include "cookie.h"
58
#include "vauth/vauth.h"
59
#include "vquic/vquic.h"
60
#include "http_digest.h"
61
#include "http_negotiate.h"
62
#include "http_aws_sigv4.h"
63
#include "http_httpsig.h"
64
#include "url.h"
65
#include "urlapi-int.h"
66
#include "curl_share.h"
67
#include "dynhds.h"
68
#include "http.h"
69
#include "headers.h"
70
#include "select.h"
71
#include "parsedate.h" /* for the week day and month names */
72
#include "multiif.h"
73
#include "strcase.h"
74
#include "content_encoding.h"
75
#include "http_proxy.h"
76
#include "http2.h"
77
#include "cfilters.h"
78
#include "connect.h"
79
#include "curlx/strdup.h"
80
#include "altsvc.h"
81
#include "hsts.h"
82
#include "rtsp.h"
83
#include "ws.h"
84
#include "bufref.h"
85
#include "curlx/strparse.h"
86
87
void Curl_http_neg_init(struct Curl_easy *data, struct http_negotiation *neg)
88
9.67k
{
89
9.67k
  memset(neg, 0, sizeof(*neg));
90
9.67k
  neg->accept_09 = data->set.http09_allowed;
91
9.67k
  switch(data->set.httpwant) {
92
0
  case CURL_HTTP_VERSION_1_0:
93
0
    neg->wanted = neg->allowed = (CURL_HTTP_V1x);
94
0
    neg->only_10 = TRUE;
95
0
    break;
96
0
  case CURL_HTTP_VERSION_1_1:
97
0
    neg->wanted = neg->allowed = (CURL_HTTP_V1x);
98
0
    break;
99
0
  case CURL_HTTP_VERSION_2_0:
100
0
    neg->wanted = neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x);
101
0
    neg->h2_upgrade = TRUE;
102
0
    break;
103
0
  case CURL_HTTP_VERSION_2TLS:
104
0
    neg->wanted = neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x);
105
0
    break;
106
0
  case CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE:
107
0
    neg->wanted = neg->allowed = (CURL_HTTP_V2x);
108
0
    data->state.http_neg.h2_prior_knowledge = TRUE;
109
0
    break;
110
0
  case CURL_HTTP_VERSION_3:
111
0
    neg->wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x | CURL_HTTP_V3x);
112
0
    neg->allowed = neg->wanted;
113
0
    break;
114
9.67k
  case CURL_HTTP_VERSION_3ONLY:
115
9.67k
    neg->wanted = neg->allowed = (CURL_HTTP_V3x);
116
9.67k
    break;
117
0
  case CURL_HTTP_VERSION_NONE:
118
0
  default:
119
0
    neg->wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x);
120
0
    neg->allowed = (CURL_HTTP_V1x | CURL_HTTP_V2x | CURL_HTTP_V3x);
121
0
    break;
122
9.67k
  }
123
9.67k
}
124
125
#ifndef CURL_DISABLE_PROXY
126
/*
127
 * checkProxyHeaders() checks the linked list of custom proxy headers
128
 * if proxy headers are not available, then it will lookup into http header
129
 * link list
130
 *
131
 * It takes a connectdata struct as input to see if this is a proxy request or
132
 * not, as it then might check a different header list. Provide the header
133
 * prefix without colon!
134
 */
135
char *Curl_checkProxyheaders(struct Curl_easy *data,
136
                             const struct connectdata *conn,
137
                             const char *thisheader,
138
                             const size_t thislen)
139
21.8k
{
140
21.8k
  struct curl_slist *head;
141
142
21.8k
  for(head = (conn->http_proxy.peer && data->set.sep_headers) ?
143
21.8k
        data->set.proxyheaders : data->set.headers;
144
21.8k
      head; head = head->next) {
145
0
    if(curl_strnequal(head->data, thisheader, thislen) &&
146
0
       Curl_headersep(head->data[thislen]))
147
0
      return head->data;
148
0
  }
149
150
21.8k
  return NULL;
151
21.8k
}
152
#endif
153
154
/* If the header has a value, this function returns TRUE and the value is in
155
   'outp' with blanks trimmed off. */
156
static bool header_has_value(const char **headerp, struct Curl_str *outp)
157
0
{
158
0
  bool value = !curlx_str_cspn(headerp, outp, ";:") &&
159
0
    (!curlx_str_single(headerp, ':') || !curlx_str_single(headerp, ';'));
160
161
0
  if(value) {
162
0
    curlx_str_cspn(headerp, outp, "\r\n");
163
0
    curlx_str_trimblanks(outp);
164
0
  }
165
0
  return value;
166
0
}
167
168
static bool http_header_is_empty(const char *header)
169
0
{
170
0
  struct Curl_str out;
171
172
0
  if(header_has_value(&header, &out)) {
173
0
    return curlx_strlen(&out) == 0;
174
0
  }
175
0
  return TRUE; /* invalid header format, treat as empty */
176
0
}
177
178
/*
179
 * Strip off leading and trailing whitespace from the value in the given HTTP
180
 * header line and return a strdup-ed copy in 'valp' - returns an empty
181
 * string if the header value consists entirely of whitespace.
182
 *
183
 * If the header is provided as "name;", ending with a semicolon, it returns a
184
 * blank string.
185
 */
186
static CURLcode copy_custom_value(const char *header, char **valp)
187
0
{
188
0
  struct Curl_str out = { 0 };
189
190
  /* find the end of the header name */
191
0
  if(header_has_value(&header, &out)) {
192
0
    *valp = curlx_memdup0(curlx_str(&out), curlx_strlen(&out));
193
0
    if(*valp)
194
0
      return CURLE_OK;
195
0
    return CURLE_OUT_OF_MEMORY;
196
0
  }
197
  /* bad input */
198
0
  *valp = NULL;
199
0
  return CURLE_BAD_FUNCTION_ARGUMENT;
200
0
}
201
202
/*
203
 * Strip off leading and trailing whitespace from the value in the given HTTP
204
 * header line and return a strdup-ed copy in 'valp' - returns an empty
205
 * string if the header value consists entirely of whitespace.
206
 *
207
 * This function MUST be used after the header has already been confirmed to
208
 * lead with "word:".
209
 *
210
 * @unittest: 1626
211
 */
212
char *Curl_copy_header_value(const char *header)
213
18
{
214
18
  struct Curl_str out;
215
216
  /* find the end of the header name */
217
18
  if(!curlx_str_until(&header, &out, MAX_HTTP_RESP_HEADER_SIZE, ':') &&
218
18
     !curlx_str_single(&header, ':')) {
219
18
    curlx_str_untilnl(&header, &out, MAX_HTTP_RESP_HEADER_SIZE);
220
18
    curlx_str_trimblanks(&out);
221
18
    return curlx_memdup0(curlx_str(&out), curlx_strlen(&out));
222
18
  }
223
  /* bad input, should never happen */
224
0
  DEBUGASSERT(0);
225
0
  return NULL;
226
0
}
227
228
#ifndef CURL_DISABLE_HTTP_AUTH
229
230
#ifndef CURL_DISABLE_BASIC_AUTH
231
/*
232
 * http_output_basic() sets up an Authorization: header (or the proxy version)
233
 * for HTTP Basic authentication.
234
 *
235
 * Returns CURLcode.
236
 */
237
static CURLcode http_output_basic(struct Curl_easy *data,
238
                                  struct Curl_creds *creds,
239
                                  const char *hd_name,
240
                                  bool proxy)
241
263
{
242
263
  size_t size = 0;
243
263
  char *authorization = NULL;
244
263
  char **p_hd;
245
263
  CURLcode result;
246
263
  char *out;
247
248
  /* credentials are unique per transfer for HTTP, do not use the ones for the
249
     connection */
250
263
  if(proxy) {
251
252
#ifndef CURL_DISABLE_PROXY
252
252
    p_hd = &data->req.hd_proxy_auth;
253
#else
254
    return CURLE_NOT_BUILT_IN;
255
#endif
256
252
  }
257
11
  else {
258
11
    p_hd = &data->req.hd_auth;
259
11
  }
260
261
263
  if(!creds) {
262
0
    DEBUGASSERT(0);
263
0
    return CURLE_FAILED_INIT;
264
0
  }
265
266
263
  out = curl_maprintf("%s:%s", creds->user, creds->passwd);
267
263
  if(!out)
268
0
    return CURLE_OUT_OF_MEMORY;
269
270
263
  result = curlx_base64_encode((uint8_t *)out, strlen(out),
271
263
                               &authorization, &size);
272
263
  if(result)
273
1
    goto fail;
274
275
262
  if(!authorization) {
276
0
    result = CURLE_REMOTE_ACCESS_DENIED;
277
0
    goto fail;
278
0
  }
279
280
262
  curlx_free(*p_hd);
281
262
  *p_hd = curl_maprintf("%s: Basic %s\r\n", hd_name, authorization);
282
262
  curlx_free(authorization);
283
262
  if(!*p_hd) {
284
4
    result = CURLE_OUT_OF_MEMORY;
285
4
    goto fail;
286
4
  }
287
288
263
fail:
289
263
  curlx_free(out);
290
263
  return result;
291
262
}
292
293
#endif
294
295
#ifndef CURL_DISABLE_BEARER_AUTH
296
/* Sets up an Authorization: header for HTTP Bearer authentication. */
297
static CURLcode http_output_bearer(struct Curl_easy *data)
298
0
{
299
0
  curlx_free(data->req.hd_auth);
300
0
  if(!Curl_creds_has_oauth_bearer(data->state.creds)) {
301
0
    DEBUGASSERT(0); /* we should not have come here */
302
0
    return CURLE_FAILED_INIT;
303
0
  }
304
0
  data->req.hd_auth =
305
0
    curl_maprintf("Authorization: Bearer %s\r\n",
306
0
                  Curl_creds_oauth_bearer(data->state.creds));
307
308
0
  if(!data->req.hd_auth)
309
0
    return CURLE_OUT_OF_MEMORY;
310
0
  return CURLE_OK;
311
0
}
312
#endif
313
314
#endif
315
316
/* pickoneauth() selects the most favorable authentication method from the
317
 * ones available and the ones we want.
318
 *
319
 * return TRUE if one was picked
320
 */
321
static bool pickoneauth(struct auth *pick, unsigned long mask,
322
                        struct Curl_creds *creds)
323
6
{
324
6
  bool have_user_pass = Curl_creds_has_user_or_pass(creds);
325
6
  bool picked;
326
  /* only deal with authentication we want */
327
6
  unsigned long avail = pick->avail & pick->want & mask;
328
6
  picked = TRUE;
329
330
  /* The order of these checks is highly relevant, as this will be the order
331
     of preference in case of the existence of multiple accepted types. */
332
6
  if(avail & CURLAUTH_NEGOTIATE)  /* available on empty creds */
333
0
    pick->picked = CURLAUTH_NEGOTIATE;
334
6
#ifndef CURL_DISABLE_BEARER_AUTH
335
6
  else if((avail & CURLAUTH_BEARER) && Curl_creds_has_oauth_bearer(creds))
336
0
    pick->picked = CURLAUTH_BEARER;
337
6
#endif
338
6
#ifndef CURL_DISABLE_DIGEST_AUTH
339
6
  else if((avail & CURLAUTH_DIGEST) && have_user_pass)
340
0
    pick->picked = CURLAUTH_DIGEST;
341
6
#endif
342
6
#ifndef CURL_DISABLE_BASIC_AUTH
343
6
  else if((avail & CURLAUTH_BASIC) && have_user_pass)
344
0
    pick->picked = CURLAUTH_BASIC;
345
6
#endif
346
6
#ifndef CURL_DISABLE_AWS
347
6
  else if(avail & CURLAUTH_AWS_SIGV4)
348
0
    pick->picked = CURLAUTH_AWS_SIGV4;
349
6
#endif
350
6
#ifndef CURL_DISABLE_HTTPSIG
351
6
  else if(avail & CURLAUTH_HTTPSIG)
352
0
    pick->picked = CURLAUTH_HTTPSIG;
353
6
#endif
354
6
  else {
355
6
    pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
356
6
    picked = FALSE;
357
6
  }
358
6
  pick->avail = CURLAUTH_NONE; /* clear it here */
359
360
6
  return picked;
361
6
}
362
363
/*
364
 * http_perhapsrewind()
365
 *
366
 * The current request needs to be done again - maybe due to a follow
367
 * or authentication negotiation. Check if:
368
 * 1) a rewind of the data sent to the server is necessary
369
 * 2) the current transfer should continue or be stopped early
370
 */
371
static CURLcode http_perhapsrewind(struct Curl_easy *data,
372
                                   struct connectdata *conn)
373
0
{
374
0
  curl_off_t bytessent = data->req.writebytecount;
375
0
  curl_off_t expectsend = Curl_creader_total_length(data);
376
0
  curl_off_t upload_remain = (expectsend >= 0) ? (expectsend - bytessent) : -1;
377
0
  bool little_upload_remains = (upload_remain >= 0 && upload_remain < 2000);
378
0
  bool needs_rewind = Curl_creader_needs_rewind(data);
379
  /* By default, we would like to abort the transfer when little or unknown
380
   * amount remains. This may be overridden by authentications further
381
   * below! */
382
0
  bool abort_upload = (!data->req.upload_done && !little_upload_remains);
383
0
  VERBOSE(const char *ongoing_auth = NULL);
384
385
  /* We need a rewind before uploading client read data again. The
386
   * checks below influence of the upload is to be continued
387
   * or aborted early.
388
   * This depends on how much remains to be sent and in what state
389
   * the authentication is. Some auth schemes such as Negotiate do not work
390
   * for a new connection. */
391
0
  if(needs_rewind) {
392
0
    infof(data, "Need to rewind upload for next request");
393
0
    Curl_creader_set_rewind(data, TRUE);
394
0
  }
395
396
0
  if(conn->bits.close)
397
    /* If we already decided to close this connection, we cannot veto. */
398
0
    return CURLE_OK;
399
400
0
  if(abort_upload) {
401
    /* We would like to abort the upload - but should we? */
402
#ifdef USE_SPNEGO
403
    /* There is still data left to send */
404
    if((data->state.authproxy.picked == CURLAUTH_NEGOTIATE) ||
405
       (data->state.authhost.picked == CURLAUTH_NEGOTIATE)) {
406
      VERBOSE(ongoing_auth = "NEGOTIATE");
407
      if((conn->http_negotiate_state != CURL_NEGO_AUTH_NONE) ||
408
         (conn->proxy_negotiate_state != CURL_NEGO_AUTH_NONE)) {
409
        /* The NEGOTIATE-negotiation has started, keep on sending.
410
         * Need to do further work on same connection */
411
        abort_upload = FALSE;
412
      }
413
    }
414
#endif
415
0
  }
416
417
0
  if(abort_upload) {
418
0
    if(upload_remain >= 0)
419
0
      infof(data, "%s%sclose instead of sending %" FMT_OFF_T " more bytes",
420
0
            ongoing_auth ? ongoing_auth : "",
421
0
            ongoing_auth ? " send, " : "",
422
0
            upload_remain);
423
0
    else
424
0
      infof(data, "%s%sclose instead of sending unknown amount "
425
0
            "of more bytes",
426
0
            ongoing_auth ? ongoing_auth : "",
427
0
            ongoing_auth ? " send, " : "");
428
    /* We decided to abort the ongoing transfer */
429
0
    streamclose(conn);
430
0
    data->req.size = 0; /* do not download any more than 0 bytes */
431
0
    data->req.http_bodyless = TRUE;
432
0
  }
433
0
  return CURLE_OK;
434
0
}
435
436
/**
437
 * http_should_fail() determines whether an HTTP response code has gotten us
438
 * into an error state or not.
439
 *
440
 * @retval FALSE communications should continue
441
 *
442
 * @retval TRUE communications should not continue
443
 */
444
static bool http_should_fail(struct Curl_easy *data, int httpcode)
445
1.36k
{
446
1.36k
  DEBUGASSERT(data);
447
1.36k
  DEBUGASSERT(data->conn);
448
449
  /*
450
   * If we have not been asked to fail on error,
451
   * do not fail.
452
   */
453
1.36k
  if(!data->set.http_fail_on_error)
454
1.30k
    return FALSE;
455
456
  /*
457
   * Any code < 400 is never terminal.
458
   */
459
66
  if(httpcode < 400)
460
4
    return FALSE;
461
462
  /*
463
   * A 416 response to a resume request is presumably because the file is
464
   * already completely downloaded and thus not actually a fail.
465
   */
466
62
  if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET &&
467
55
     httpcode == 416)
468
3
    return FALSE;
469
470
  /*
471
   * Any code >= 400 that is not 401 or 407 is always
472
   * a terminal error
473
   */
474
59
  if((httpcode != 401) && (httpcode != 407))
475
30
    return TRUE;
476
477
  /*
478
   * All we have left to deal with is 401 and 407
479
   */
480
29
  DEBUGASSERT((httpcode == 401) || (httpcode == 407));
481
482
  /*
483
   * Examine the current authentication state to see if this is an error. The
484
   * idea is for this function to get called after processing all the headers
485
   * in a response message. If we have been asked to authenticate at
486
   * a particular stage, and we have done it, we are OK. If we are already
487
   * completely authenticated, it is not OK to get another 401 or 407.
488
   *
489
   * It is possible for authentication to go stale such that the client needs
490
   * to reauthenticate. Once that info is available, use it here.
491
   */
492
493
  /*
494
   * Either we are not authenticating, or we are supposed to be authenticating
495
   * something else. This is an error.
496
   */
497
29
  if((httpcode == 401) && !data->state.creds)
498
7
    return TRUE;
499
22
#ifndef CURL_DISABLE_PROXY
500
22
  if((httpcode == 407) && !data->conn->http_proxy.creds)
501
20
    return TRUE;
502
2
#endif
503
504
2
  return (bool)data->state.authproblem;
505
22
}
506
507
/*
508
 * Curl_http_auth_act() gets called when all HTTP headers have been received
509
 * and it checks what authentication methods that are available and decides
510
 * which one (if any) to use. It will set 'newurl' if an auth method was
511
 * picked.
512
 */
513
CURLcode Curl_http_auth_act(struct Curl_easy *data)
514
745
{
515
745
  struct connectdata *conn = data->conn;
516
745
  bool pickhost = FALSE;
517
745
  bool pickproxy = FALSE;
518
745
  CURLcode result = CURLE_OK;
519
745
  unsigned long authmask = ~0UL;
520
521
745
  if(!Curl_creds_has_oauth_bearer(data->state.creds))
522
742
    authmask &= (unsigned long)~CURLAUTH_BEARER;
523
524
745
  if(100 <= data->req.httpcode && data->req.httpcode <= 199)
525
    /* this is a transient response code, ignore */
526
13
    return CURLE_OK;
527
528
732
  if(data->state.authproblem)
529
0
    return data->set.http_fail_on_error ? CURLE_HTTP_RETURNED_ERROR : CURLE_OK;
530
531
732
  if(data->state.creds &&
532
17
     ((data->req.httpcode == 401) ||
533
14
      (data->req.authneg && data->req.httpcode < 300))) {
534
3
    pickhost = pickoneauth(&data->state.authhost, authmask, data->state.creds);
535
3
    if(!pickhost)
536
3
      data->state.authproblem = TRUE;
537
0
    else
538
0
      data->info.httpauthpicked = data->state.authhost.picked;
539
3
  }
540
732
#ifndef CURL_DISABLE_PROXY
541
732
  if(conn->http_proxy.creds &&
542
8
     ((data->req.httpcode == 407) ||
543
5
      (data->req.authneg && data->req.httpcode < 300))) {
544
3
    pickproxy = pickoneauth(&data->state.authproxy,
545
3
                            authmask & ~CURLAUTH_BEARER,
546
3
                            conn->http_proxy.creds);
547
3
    if(!pickproxy)
548
3
      data->state.authproblem = TRUE;
549
0
    else
550
0
      data->info.proxyauthpicked = data->state.authproxy.picked;
551
3
  }
552
732
#endif
553
554
732
  if(pickhost || pickproxy) {
555
0
    result = http_perhapsrewind(data, conn);
556
0
    if(result)
557
0
      return result;
558
559
    /* In case this is GSS auth, the newurl field is already allocated so
560
       we must make sure to free it before allocating a new one. As figured
561
       out in bug #2284386 */
562
0
    curlx_free(data->req.newurl);
563
    /* clone URL */
564
0
    data->req.newurl = Curl_bufref_dup(&data->state.url);
565
0
    if(!data->req.newurl)
566
0
      return CURLE_OUT_OF_MEMORY;
567
0
  }
568
732
  else if((data->req.httpcode < 300) &&
569
607
          !data->state.authhost.done &&
570
2
          data->req.authneg &&
571
          /* no (known) authentication available,
572
             authentication is not "done" yet and
573
             no authentication seems to be required and
574
             we did not try HEAD or GET */
575
0
          (data->state.httpreq != HTTPREQ_GET) &&
576
0
          (data->state.httpreq != HTTPREQ_HEAD)) {
577
    /* clone URL */
578
0
    data->req.newurl = Curl_bufref_dup(&data->state.url);
579
0
    if(!data->req.newurl)
580
0
      return CURLE_OUT_OF_MEMORY;
581
0
    data->state.authhost.done = TRUE;
582
0
  }
583
732
  if(http_should_fail(data, data->req.httpcode)) {
584
59
    failf(data, "The requested URL returned error: %d",
585
59
          data->req.httpcode);
586
59
    result = CURLE_HTTP_RETURNED_ERROR;
587
59
  }
588
589
732
  return result;
590
732
}
591
592
#ifndef CURL_DISABLE_HTTP_AUTH
593
/*
594
 * Output the correct authentication header depending on the auth type
595
 * and whether or not it is to a proxy.
596
 */
597
static CURLcode output_auth_headers(struct Curl_easy *data,
598
                                    struct connectdata *conn,
599
                                    struct auth *authstatus,
600
                                    const char *method,
601
                                    const char *path,
602
                                    bool proxy,
603
                                    struct Curl_creds *creds,
604
                                    const char *hd_name,
605
                                    size_t hd_len,
606
                                    const char **pauth_used)
607
647
{
608
647
  CURLcode result = CURLE_OK;
609
610
647
  *pauth_used = NULL;
611
647
  switch(authstatus->picked) {
612
613
0
#ifndef CURL_DISABLE_AWS
614
10
  case CURLAUTH_AWS_SIGV4:
615
10
    if(!proxy) {
616
      /* this method is never for proxy */
617
9
      *pauth_used = "AWS_SIGV4";
618
9
      result = Curl_output_aws_sigv4(data);
619
9
    }
620
10
    break;
621
0
#endif
622
623
0
#ifndef CURL_DISABLE_HTTPSIG
624
3
  case CURLAUTH_HTTPSIG:
625
3
    if(!proxy) {
626
      /* HTTPSIG uses its own configured key material rather than
627
         data->state.creds. Do not let unrelated credentials from a
628
         redirected URL bypass the cross-host auth boundary. */
629
2
      if(Curl_auth_allowed_to_host(data)) {
630
2
        *pauth_used = "HTTPSIG";
631
2
        result = Curl_output_httpsig(data);
632
2
      }
633
0
      else
634
0
        authstatus->done = TRUE;
635
2
    }
636
3
    break;
637
0
#endif
638
639
#ifdef USE_SPNEGO
640
  case CURLAUTH_NEGOTIATE:
641
    if(
642
#ifndef CURL_DISABLE_PROXY
643
      (proxy && !Curl_checkProxyheaders(data, conn, hd_name, hd_len)) ||
644
#endif
645
      (!proxy && !Curl_checkheaders(data, hd_name, hd_len) &&
646
       Curl_auth_allowed_to_host(data))) {
647
      *pauth_used = "Negotiate";
648
      result = Curl_output_negotiate(data, conn, hd_name, proxy);
649
    }
650
    else
651
      authstatus->done = TRUE;
652
    break;
653
#endif
654
655
0
#ifndef CURL_DISABLE_DIGEST_AUTH
656
6
  case CURLAUTH_DIGEST:
657
6
    *pauth_used = "Digest";
658
6
    result = Curl_output_digest(data, creds, hd_name, proxy,
659
6
                                (const unsigned char *)method,
660
6
                                (const unsigned char *)path);
661
6
    break;
662
0
#endif
663
664
0
#ifndef CURL_DISABLE_BASIC_AUTH
665
554
  case CURLAUTH_BASIC:
666
554
    if(creds && Curl_creds_has_user_or_pass(creds) && (
667
263
#ifndef CURL_DISABLE_PROXY
668
263
       (proxy && !Curl_checkProxyheaders(data, conn, hd_name, hd_len)) ||
669
11
#endif
670
263
       (!proxy && !Curl_checkheaders(data, hd_name, hd_len)))) {
671
263
      *pauth_used = "Basic";
672
263
      result = http_output_basic(data, creds, hd_name, proxy);
673
263
      if(result)
674
5
        return result;
675
263
    }
676
    /* NOTE: this function should set 'done' TRUE, as the other auth
677
       functions work that way */
678
549
    authstatus->done = TRUE;
679
549
    break;
680
0
#endif
681
682
0
#ifndef CURL_DISABLE_BEARER_AUTH
683
1
  case CURLAUTH_BEARER:
684
1
    if(!proxy && Curl_creds_has_oauth_bearer(creds) &&
685
0
       !Curl_checkheaders(data, hd_name, hd_len)) {
686
0
      *pauth_used = "Bearer";
687
0
      result = http_output_bearer(data);
688
0
      if(result)
689
0
        return result;
690
0
    }
691
    /* NOTE: this function should set 'done' TRUE, as the other auth
692
       functions work that way */
693
1
    authstatus->done = TRUE;
694
1
    break;
695
0
#endif
696
697
73
  default:
698
    /* a pick we do not support? */
699
73
    (void)conn;
700
#ifdef CURL_DISABLE_DIGEST_AUTH
701
    (void)method;
702
    (void)path;
703
#endif
704
73
    break;
705
647
  } /* end of switch */
706
707
642
  return result;
708
647
}
709
710
CURLcode Curl_http_output_auth(struct Curl_easy *data,
711
                               struct connectdata *conn,
712
                               Curl_HttpReq httpreq,
713
                               const char *method,
714
                               const char *path,
715
                               const char *query,
716
                               bool is_connect)
717
9.16k
{
718
9.16k
  CURLcode result = CURLE_OK;
719
9.16k
  struct auth *authhost;
720
9.16k
  struct auth *authproxy;
721
9.16k
  const char *path_and_query = path;
722
9.16k
  char *tmp_str = NULL;
723
9.16k
  const char *auth_used;
724
725
9.16k
  DEBUGASSERT(data);
726
9.16k
  authhost = &data->state.authhost;
727
9.16k
  authproxy = &data->state.authproxy;
728
729
9.16k
  if(
730
9.16k
#ifndef CURL_DISABLE_PROXY
731
9.16k
    (!conn->http_proxy.peer || !conn->http_proxy.creds) &&
732
8.80k
#endif
733
#ifdef USE_SPNEGO
734
    !(authhost->want & CURLAUTH_NEGOTIATE) &&
735
    !(authproxy->want & CURLAUTH_NEGOTIATE) &&
736
#endif
737
8.80k
#ifndef CURL_DISABLE_HTTPSIG
738
8.80k
    !(authhost->want & CURLAUTH_HTTPSIG) &&
739
8.70k
#endif
740
8.70k
    !data->state.creds) {
741
    /* no authentication with no user or password */
742
8.51k
    authhost->done = TRUE;
743
8.51k
    authproxy->done = TRUE;
744
8.51k
    result = CURLE_OK;
745
8.51k
    goto out;
746
8.51k
  }
747
748
647
  if(query) {
749
0
    tmp_str = curl_maprintf("%s?%s", path, query);
750
0
    if(!tmp_str) {
751
0
      result = CURLE_OUT_OF_MEMORY;
752
0
      goto out;
753
0
    }
754
0
    path_and_query = tmp_str;
755
0
  }
756
757
647
  if(authhost->want && !authhost->picked)
758
    /* The app has selected one or more methods, but none has been picked
759
       so far by a server round-trip. Then we set the picked one to the
760
       want one, and if this is one single bit it will be used instantly. */
761
644
    authhost->picked = authhost->want;
762
763
647
  if(authproxy->want && !authproxy->picked)
764
    /* The app has selected one or more methods, but none has been picked so
765
       far by a proxy round-trip. Then we set the picked one to the want one,
766
       and if this is one single bit it will be used instantly. */
767
640
    authproxy->picked = authproxy->want;
768
769
647
#ifndef CURL_DISABLE_PROXY
770
  /* Send proxy authentication header only with a forwarding proxy
771
   * or when doing a CONNECT* request. */
772
647
  if(conn->bits.origin_is_proxy || is_connect) {
773
593
    result = output_auth_headers(data, conn, authproxy,
774
593
                                 method, path_and_query,
775
593
                                 TRUE, conn->http_proxy.creds,
776
593
                                 STRCONST("Proxy-Authorization"),
777
593
                                 &auth_used);
778
593
    if(result)
779
5
      goto out;
780
588
    data->info.proxyauthpicked = auth_used ? authproxy->picked : 0;
781
588
    authproxy->multipass = auth_used ? !authproxy->done : FALSE;
782
588
    if(auth_used)
783
252
      infof(data, "Proxy auth using %s with user '%s'", auth_used,
784
588
            conn->http_proxy.creds ? conn->http_proxy.creds->user : "");
785
588
  }
786
54
  else
787
54
    authproxy->done = TRUE;
788
#else
789
  /* no proxy, pretend we are done authenticating with it */
790
  (void)is_connect;
791
  authproxy->done = TRUE;
792
#endif /* CURL_DISABLE_PROXY */
793
794
  /* Either we have credentials for the origin we talk to or
795
     performing authentication is allowed here */
796
642
  if(!is_connect &&
797
54
     (data->state.creds || Curl_auth_allowed_to_host(data))) {
798
54
    result = output_auth_headers(data, conn, authhost,
799
54
                                 method, path_and_query,
800
54
                                 FALSE, data->state.creds,
801
54
                                 STRCONST("Authorization"),
802
54
                                 &auth_used);
803
54
    if(result)
804
11
      goto out;
805
43
    data->info.httpauthpicked = auth_used ? authhost->picked : 0;
806
43
    authhost->multipass = auth_used ? !authhost->done : FALSE;
807
43
    if(auth_used)
808
12
      infof(data, "Server auth using %s with user '%s'", auth_used,
809
43
            data->state.creds ? data->state.creds->user : "");
810
43
  }
811
588
  else
812
588
    authhost->done = TRUE;
813
814
631
  if(((authhost->multipass && !authhost->done) ||
815
630
      (authproxy->multipass && !authproxy->done)) &&
816
6
     (httpreq != HTTPREQ_GET) &&
817
1
     (httpreq != HTTPREQ_HEAD)) {
818
    /* Auth is required and we are not authenticated yet. Make a PUT or POST
819
       with content-length zero as a "probe". */
820
1
    data->req.authneg = TRUE;
821
1
  }
822
630
  else
823
630
    data->req.authneg = FALSE;
824
825
9.16k
out:
826
9.16k
  curlx_free(tmp_str);
827
9.16k
  return result;
828
631
}
829
830
#else /* !CURL_DISABLE_HTTP_AUTH */
831
/* when disabled */
832
CURLcode Curl_http_output_auth(struct Curl_easy *data,
833
                               struct connectdata *conn,
834
                               Curl_HttpReq httpreq,
835
                               const char *method,
836
                               const char *path,
837
                               const char *query,
838
                               bool is_connect)
839
{
840
  (void)data;
841
  (void)conn;
842
  (void)httpreq;
843
  (void)method;
844
  (void)path;
845
  (void)query;
846
  (void)is_connect;
847
  return CURLE_OK;
848
}
849
#endif /* !CURL_DISABLE_HTTP_AUTH, else */
850
851
#if defined(USE_SPNEGO) || \
852
  !defined(CURL_DISABLE_DIGEST_AUTH) || \
853
  !defined(CURL_DISABLE_BASIC_AUTH) || \
854
  !defined(CURL_DISABLE_BEARER_AUTH)
855
static bool authcmp(const char *auth, const char *line)
856
0
{
857
  /* the auth string must not have an alnum following */
858
0
  size_t n = strlen(auth);
859
0
  return curl_strnequal(auth, line, n) && !ISALNUM(line[n]);
860
0
}
861
#endif
862
863
#ifdef USE_SPNEGO
864
static CURLcode auth_spnego(struct Curl_easy *data,
865
                            bool proxy,
866
                            const char *auth,
867
                            struct auth *authp,
868
                            uint32_t *availp)
869
{
870
  if((authp->avail & CURLAUTH_NEGOTIATE) || Curl_auth_is_spnego_supported()) {
871
    *availp |= CURLAUTH_NEGOTIATE;
872
    authp->avail |= CURLAUTH_NEGOTIATE;
873
874
    if(authp->picked == CURLAUTH_NEGOTIATE) {
875
      struct connectdata *conn = data->conn;
876
      CURLcode result = Curl_input_negotiate(data, conn, proxy, auth);
877
      uint8_t *negstate = proxy ? &conn->proxy_negotiate_state :
878
        &conn->http_negotiate_state;
879
      if(!result) {
880
        curlx_free(data->req.newurl);
881
        data->req.newurl = Curl_bufref_dup(&data->state.url);
882
        if(!data->req.newurl)
883
          return CURLE_OUT_OF_MEMORY;
884
        data->state.authproblem = FALSE;
885
        /* we received a GSS auth token and we dealt with it fine */
886
        *negstate = CURL_NEGO_AUTH_RECV;
887
      }
888
      else
889
        data->state.authproblem = TRUE;
890
    }
891
  }
892
  return CURLE_OK;
893
}
894
#endif
895
896
#ifndef CURL_DISABLE_DIGEST_AUTH
897
static CURLcode auth_digest(struct Curl_easy *data,
898
                            bool proxy,
899
                            const char *auth,
900
                            struct auth *authp,
901
                            uint32_t *availp)
902
0
{
903
0
  if(authp->avail & CURLAUTH_DIGEST) {
904
0
    *availp |= CURLAUTH_DIGEST;
905
0
    infof(data, "Ignoring duplicate digest auth header.");
906
0
  }
907
0
  else if(Curl_auth_is_digest_supported()) {
908
    /* We call this function on input Digest headers even if Digest
909
     * authentication is not activated yet, as we need to store the
910
     * incoming data from this header in case we are going to use
911
     * Digest */
912
0
    CURLcode result = Curl_input_digest(data, proxy, auth);
913
0
    if(result == CURLE_OUT_OF_MEMORY)
914
0
      return result;
915
0
    if(result == CURLE_NOT_BUILT_IN) {
916
0
      infof(data, "Ignoring unusable Digest algorithm.");
917
0
      return CURLE_OK;
918
0
    }
919
0
    *availp |= CURLAUTH_DIGEST;
920
0
    authp->avail |= CURLAUTH_DIGEST;
921
0
    if(result) {
922
0
      infof(data, "Digest authentication problem, ignoring.");
923
0
      data->state.authproblem = TRUE;
924
0
    }
925
0
  }
926
0
  return CURLE_OK;
927
0
}
928
#endif
929
930
#ifndef CURL_DISABLE_BASIC_AUTH
931
static CURLcode auth_basic(struct Curl_easy *data,
932
                           struct auth *authp,
933
                           uint32_t *availp)
934
0
{
935
0
  *availp |= CURLAUTH_BASIC;
936
0
  authp->avail |= CURLAUTH_BASIC;
937
0
  if(authp->picked == CURLAUTH_BASIC) {
938
    /* We asked for Basic authentication but got a 40X back anyway, which
939
       means our name+password is not valid. */
940
0
    authp->avail = CURLAUTH_NONE;
941
0
    infof(data, "Basic authentication problem, ignoring.");
942
0
    data->state.authproblem = TRUE;
943
0
  }
944
0
  return CURLE_OK;
945
0
}
946
#endif
947
948
#ifndef CURL_DISABLE_BEARER_AUTH
949
static CURLcode auth_bearer(struct Curl_easy *data,
950
                            struct auth *authp,
951
                            uint32_t *availp)
952
0
{
953
0
  *availp |= CURLAUTH_BEARER;
954
0
  authp->avail |= CURLAUTH_BEARER;
955
0
  if(authp->picked == CURLAUTH_BEARER) {
956
    /* We asked for Bearer authentication but got a 40X back anyway, which
957
       means our token is not valid. */
958
0
    authp->avail = CURLAUTH_NONE;
959
0
    infof(data, "Bearer authentication problem, ignoring.");
960
0
    data->state.authproblem = TRUE;
961
0
  }
962
0
  return CURLE_OK;
963
0
}
964
#endif
965
966
/*
967
 * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
968
 * headers. They are dealt with both in the transfer.c main loop and in the
969
 * proxy CONNECT loop.
970
 *
971
 * The 'auth' line ends with a NUL byte without CR or LF present.
972
 */
973
CURLcode Curl_http_input_auth(struct Curl_easy *data, bool proxy,
974
                              const char *auth) /* the first non-space */
975
0
{
976
  /*
977
   * This resource requires authentication
978
   */
979
0
#if defined(USE_SPNEGO) ||                      \
980
0
  !defined(CURL_DISABLE_DIGEST_AUTH) ||         \
981
0
  !defined(CURL_DISABLE_BASIC_AUTH) ||          \
982
0
  !defined(CURL_DISABLE_BEARER_AUTH)
983
984
0
  uint32_t *availp;
985
0
  struct auth *authp;
986
0
  CURLcode result = CURLE_OK;
987
0
  DEBUGASSERT(auth);
988
0
  DEBUGASSERT(data);
989
990
0
  if(proxy) {
991
0
    availp = &data->info.proxyauthavail;
992
0
    authp = &data->state.authproxy;
993
0
  }
994
0
  else {
995
0
    availp = &data->info.httpauthavail;
996
0
    authp = &data->state.authhost;
997
0
  }
998
999
  /*
1000
   * Here we check if we want the specific single authentication (using ==) and
1001
   * if we do, we initiate usage of it.
1002
   *
1003
   * If the provided authentication is wanted as one out of several accepted
1004
   * types (using &), we OR this authentication type to the authavail
1005
   * variable.
1006
   *
1007
   * Note:
1008
   *
1009
   * ->picked is first set to the 'want' value (one or more bits) before the
1010
   * request is sent, and then it is again set _after_ all response 401/407
1011
   * headers have been received but then only to a single preferred method
1012
   * (bit).
1013
   */
1014
1015
0
  while(*auth) {
1016
#ifdef USE_SPNEGO
1017
    if(authcmp("Negotiate", auth))
1018
      result = auth_spnego(data, proxy, auth, authp, availp);
1019
#endif
1020
0
#ifndef CURL_DISABLE_DIGEST_AUTH
1021
0
    if(!result && authcmp("Digest", auth))
1022
0
      result = auth_digest(data, proxy, auth, authp, availp);
1023
0
#endif
1024
0
#ifndef CURL_DISABLE_BASIC_AUTH
1025
0
    if(!result && authcmp("Basic", auth))
1026
0
      result = auth_basic(data, authp, availp);
1027
0
#endif
1028
0
#ifndef CURL_DISABLE_BEARER_AUTH
1029
0
    if(authcmp("Bearer", auth))
1030
0
      result = auth_bearer(data, authp, availp);
1031
0
#endif
1032
1033
0
    if(result)
1034
0
      break;
1035
1036
    /* there may be multiple methods on one line, so keep reading */
1037
0
    auth = strchr(auth, ',');
1038
0
    if(auth) /* if we are on a comma, skip it */
1039
0
      auth++;
1040
0
    else
1041
0
      break;
1042
0
    curlx_str_passblanks(&auth);
1043
0
  }
1044
0
  return result;
1045
#else
1046
  (void)data;
1047
  (void)proxy;
1048
  (void)auth;
1049
  /* nothing to do when disabled */
1050
  return CURLE_OK;
1051
#endif
1052
0
}
1053
1054
static void http_switch_to_get(struct Curl_easy *data, int code)
1055
0
{
1056
0
  const char *req = CURL_EASY_STR(data, STRING_CUSTOMREQUEST);
1057
1058
0
  if((req || data->state.httpreq != HTTPREQ_GET) &&
1059
0
     (data->set.http_follow_mode == CURLFOLLOW_OBEYCODE)) {
1060
0
    NOVERBOSE((void)code);
1061
0
    infof(data, "Switch to GET because of %d response", code);
1062
0
    data->state.http_ignorecustom = TRUE;
1063
0
  }
1064
0
  else if(req && (data->set.http_follow_mode != CURLFOLLOW_FIRSTONLY))
1065
0
    infof(data, "Stick to %s instead of GET", req);
1066
1067
0
  data->state.httpreq = HTTPREQ_GET;
1068
0
  Curl_creader_set_rewind(data, FALSE);
1069
0
}
1070
1071
#define HTTPREQ_IS_POST(data)                    \
1072
0
  ((data)->state.httpreq == HTTPREQ_POST ||      \
1073
0
   (data)->state.httpreq == HTTPREQ_POST_FORM || \
1074
0
   (data)->state.httpreq == HTTPREQ_POST_MIME)
1075
1076
static CURLcode set_auto_referer(struct Curl_easy *data)
1077
0
{
1078
0
  CURLU *u;
1079
0
  char *referer = NULL;
1080
0
  CURLUcode uc;
1081
1082
  /* We are asked to automatically set the previous URL as the referer
1083
     when we get the next URL. We pick the ->url field, which may or may
1084
     not be 100% correct */
1085
0
  Curl_bufref_free(&data->state.referer);
1086
1087
  /* Make a copy of the URL without credentials and fragment */
1088
0
  u = curl_url();
1089
0
  if(!u)
1090
0
    return CURLE_OUT_OF_MEMORY;
1091
1092
0
  uc = curl_url_set(u, CURLUPART_URL,
1093
0
                    Curl_bufref_ptr(&data->state.url), 0);
1094
0
  if(!uc)
1095
0
    uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0);
1096
0
  if(!uc)
1097
0
    uc = curl_url_set(u, CURLUPART_USER, NULL, 0);
1098
0
  if(!uc)
1099
0
    uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0);
1100
0
  if(!uc)
1101
0
    uc = curl_url_get(u, CURLUPART_URL, &referer, 0);
1102
1103
0
  curl_url_cleanup(u);
1104
1105
0
  if(uc || !referer)
1106
0
    return CURLE_OUT_OF_MEMORY;
1107
1108
0
  Curl_bufref_set(&data->state.referer, referer, 0, curl_free);
1109
0
  return CURLE_OK;
1110
0
}
1111
1112
static CURLcode follow_parse_url(struct Curl_easy *data, const char *newurl,
1113
                                 followtype type, char **follow_urlp,
1114
                                 CURLUcode *ucp)
1115
0
{
1116
0
  CURLUcode uc;
1117
1118
0
  DEBUGASSERT(data->state.uh);
1119
0
  uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, (unsigned int)
1120
0
                    ((type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME :
1121
0
                     ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) |
1122
0
                     CURLU_ALLOW_SPACE |
1123
0
                     (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)));
1124
0
  *ucp = uc;
1125
0
  if(uc) {
1126
0
    if((uc == CURLUE_OUT_OF_MEMORY) || (type != FOLLOW_FAKE)) {
1127
0
      failf(data, "The redirect target URL could not be parsed: %s",
1128
0
            curl_url_strerror(uc));
1129
0
      return Curl_uc_to_curlcode(uc);
1130
0
    }
1131
1132
    /* the URL could not be parsed for some reason, but since this is FAKE
1133
       mode, duplicate the field as-is */
1134
0
    *follow_urlp = curlx_strdup(newurl);
1135
0
    if(!*follow_urlp)
1136
0
      return CURLE_OUT_OF_MEMORY;
1137
0
  }
1138
0
  else {
1139
0
    CURLU *u = curl_url();
1140
0
    if(!u)
1141
0
      return CURLE_OUT_OF_MEMORY;
1142
0
    uc = curl_url_set(u, CURLUPART_URL,
1143
0
                      Curl_bufref_ptr(&data->state.url),
1144
0
                      CURLU_URLENCODE | CURLU_ALLOW_SPACE);
1145
0
    if(!uc)
1146
0
      uc = curl_url_get(data->state.uh, CURLUPART_URL, follow_urlp, 0);
1147
0
    if(uc) {
1148
0
      curl_url_cleanup(u);
1149
0
      return Curl_uc_to_curlcode(uc);
1150
0
    }
1151
1152
0
#ifndef CURL_DISABLE_DIGEST_AUTH
1153
0
    {
1154
0
      bool same_origin = Curl_url_same_origin(u, data->state.uh);
1155
0
      curl_url_cleanup(u);
1156
0
      if(!same_origin)
1157
0
        Curl_auth_digest_cleanup(&data->state.digest);
1158
0
    }
1159
#else
1160
    curl_url_cleanup(u);
1161
#endif
1162
0
  }
1163
0
  return CURLE_OK;
1164
0
}
1165
1166
static CURLcode follow_fake(struct Curl_easy *data, char *follow_url,
1167
                            CURLUcode uc, bool reachedmax)
1168
0
{
1169
  /* we are only figuring out the new URL if we would have followed locations
1170
     but now we are done so we can get out! */
1171
0
  if(!uc) {
1172
0
    CURLU *u = curl_url();
1173
0
    char *nocred = NULL;
1174
1175
0
    if(!u) {
1176
0
      curlx_free(follow_url);
1177
0
      return CURLE_OUT_OF_MEMORY;
1178
0
    }
1179
0
    if(!curl_url_set(u, CURLUPART_URL, follow_url,
1180
0
                     CURLU_NON_SUPPORT_SCHEME |
1181
0
                     (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)) &&
1182
0
       !curl_url_set(u, CURLUPART_USER, NULL, 0) &&
1183
0
       !curl_url_set(u, CURLUPART_PASSWORD, NULL, 0))
1184
0
      (void)curl_url_get(u, CURLUPART_URL, &nocred, CURLU_GET_EMPTY);
1185
0
    curl_url_cleanup(u);
1186
0
    if(nocred) {
1187
0
      curlx_free(follow_url);
1188
0
      follow_url = nocred;
1189
0
    }
1190
0
  }
1191
0
  data->info.wouldredirect = follow_url;
1192
1193
0
  if(reachedmax) {
1194
0
    failf(data, "Maximum (%d) redirects followed", data->set.maxredirs);
1195
0
    return CURLE_TOO_MANY_REDIRECTS;
1196
0
  }
1197
0
  return CURLE_OK;
1198
0
}
1199
1200
static bool follow_switch_get(struct Curl_easy *data)
1201
0
{
1202
  /*
1203
   * We get here when the HTTP code is 300-399 and 401 or 407. We need to
1204
   * perform differently based on exactly what return code there was.
1205
   */
1206
0
  switch(data->info.httpcode) {
1207
0
  case 301: /* Moved Permanently */
1208
    /* (quote from RFC7231, section 6.4.2)
1209
     *
1210
     * Note: For historical reasons, a user agent MAY change the request
1211
     * method from POST to GET for the subsequent request. If this
1212
     * behavior is undesired, the 307 (Temporary Redirect) status code
1213
     * can be used instead.
1214
     *
1215
     * ----
1216
     *
1217
     * Many webservers expect this, so these servers often answers to a POST
1218
     * request with an error page. To be sure that libcurl gets the page that
1219
     * most user agents would get, libcurl has to force GET.
1220
     *
1221
     * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1222
     * can be overridden with CURLOPT_POSTREDIR.
1223
     */
1224
0
    if(HTTPREQ_IS_POST(data) && !data->set.post301) {
1225
0
      http_switch_to_get(data, 301);
1226
0
      return TRUE;
1227
0
    }
1228
0
    break;
1229
0
  case 302: /* Found */
1230
    /* (quote from RFC7231, section 6.4.3)
1231
     *
1232
     * Note: For historical reasons, a user agent MAY change the request
1233
     * method from POST to GET for the subsequent request. If this
1234
     * behavior is undesired, the 307 (Temporary Redirect) status code
1235
     * can be used instead.
1236
     *
1237
     * ----
1238
     *
1239
     * Many webservers expect this, so these servers often answers to a POST
1240
     * request with an error page. To be sure that libcurl gets the page that
1241
     * most user agents would get, libcurl has to force GET.
1242
     *
1243
     * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and
1244
     * can be overridden with CURLOPT_POSTREDIR.
1245
     */
1246
0
    if(HTTPREQ_IS_POST(data) && !data->set.post302) {
1247
0
      http_switch_to_get(data, 302);
1248
0
      return TRUE;
1249
0
    }
1250
0
    break;
1251
0
  case 303: /* See Other */
1252
    /* 'See Other' location is not the resource but a substitute for the
1253
     * resource. In this case we switch the method to GET/HEAD, unless the
1254
     * method is POST and the user specified to keep it as POST.
1255
     */
1256
0
    if(!HTTPREQ_IS_POST(data) || !data->set.post303) {
1257
0
      http_switch_to_get(data, 303);
1258
0
      return TRUE;
1259
0
    }
1260
0
    break;
1261
1262
    /* 304 means we did a conditional request and it was "Not modified".
1263
     * We should not get any Location: header in this response!
1264
     */
1265
1266
    /* 305 (quote from RFC2616, section 10.3.6):
1267
     * "The requested resource MUST be accessed through the proxy given
1268
     * by the Location field. The Location field gives the URI of the
1269
     * proxy. The recipient is expected to repeat this single request
1270
     * via the proxy. 305 responses MUST only be generated by origin
1271
     * servers."
1272
     */
1273
0
  default:
1274
0
    break;
1275
0
  }
1276
0
  return FALSE;
1277
0
}
1278
1279
CURLcode Curl_http_follow(struct Curl_easy *data, const char *newurl,
1280
                          followtype type)
1281
0
{
1282
0
  bool disallowport = FALSE;
1283
0
  bool reachedmax = FALSE;
1284
0
  char *follow_url = NULL;
1285
0
  CURLUcode uc;
1286
0
  CURLcode result;
1287
0
  CURLcode rewind_result;
1288
0
  bool switch_to_get;
1289
1290
0
  DEBUGASSERT(type != FOLLOW_NONE);
1291
1292
0
  if(type != FOLLOW_FAKE)
1293
0
    data->state.requests++; /* count all real follows */
1294
0
  if(type == FOLLOW_REDIR) {
1295
0
    if((data->set.maxredirs != -1) &&
1296
0
       (data->state.followlocation >= data->set.maxredirs)) {
1297
0
      reachedmax = TRUE;
1298
0
      type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
1299
                             to URL */
1300
0
    }
1301
0
    else {
1302
0
      data->state.followlocation++; /* count redirect-followings, including
1303
                                       auth reloads */
1304
1305
0
      if(data->set.http_auto_referer) {
1306
0
        result = set_auto_referer(data);
1307
0
        if(result)
1308
0
          return result;
1309
0
      }
1310
0
    }
1311
0
  }
1312
1313
0
  if((type != FOLLOW_RETRY) &&
1314
0
     (data->req.httpcode != 401) && (data->req.httpcode != 407) &&
1315
0
     Curl_is_absolute_url(newurl, NULL, 0, FALSE)) {
1316
    /* If this is not redirect due to a 401 or 407 response and an absolute
1317
       URL: do not allow a custom port number */
1318
0
    disallowport = TRUE;
1319
0
  }
1320
1321
0
  result = follow_parse_url(data, newurl, type, &follow_url, &uc);
1322
0
  if(result)
1323
0
    return result;
1324
1325
0
  DEBUGASSERT(follow_url);
1326
1327
0
  if(type == FOLLOW_FAKE)
1328
0
    return follow_fake(data, follow_url, uc, reachedmax);
1329
1330
0
  if(disallowport)
1331
0
    data->state.allow_port = FALSE;
1332
1333
0
  Curl_bufref_set(&data->state.url, follow_url, 0, curl_free);
1334
0
  rewind_result = Curl_req_soft_reset(&data->req, data);
1335
0
  infof(data, "Issue another request to this URL: '%s'", follow_url);
1336
0
  if((data->set.http_follow_mode == CURLFOLLOW_FIRSTONLY) &&
1337
0
     !data->state.http_ignorecustom &&
1338
0
     CURL_EASY_STR(data, STRING_CUSTOMREQUEST)) {
1339
0
    data->state.http_ignorecustom = TRUE;
1340
0
    infof(data, "Drop custom request method for next request");
1341
0
  }
1342
1343
0
  switch_to_get = follow_switch_get(data);
1344
1345
  /* When rewind of upload data failed and we are not switching to GET,
1346
   * we need to fail the follow, as we cannot send the data again. */
1347
0
  if(rewind_result && !switch_to_get)
1348
0
    return rewind_result;
1349
1350
0
  Curl_pgrsTime(data, TIMER_REDIRECT);
1351
0
  Curl_pgrsResetTransferSizes(data);
1352
1353
0
  return CURLE_OK;
1354
0
}
1355
1356
/*
1357
 * Curl_compareheader()
1358
 *
1359
 * Returns TRUE if 'headerline' contains the 'header' with given 'content'
1360
 * (within a comma-separated list of tokens). Pass 'header' WITH the colon.
1361
 *
1362
 * @unittest: 1625
1363
 */
1364
bool Curl_compareheader(const char *headerline, /* line to check */
1365
                        const char *header, /* header keyword _with_ colon */
1366
                        const size_t hlen, /* len of the keyword in bytes */
1367
                        const char *content, /* content string to find */
1368
                        const size_t clen) /* len of the content in bytes */
1369
58.0k
{
1370
  /* RFC2616, section 4.2 says: "Each header field consists of a name followed
1371
   * by a colon (":") and the field value. Field names are case-insensitive.
1372
   * The field value MAY be preceded by any amount of LWS, though a single SP
1373
   * is preferred." */
1374
1375
58.0k
  const char *p;
1376
58.0k
  struct Curl_str val;
1377
58.0k
  DEBUGASSERT(hlen);
1378
58.0k
  DEBUGASSERT(clen);
1379
58.0k
  DEBUGASSERT(header);
1380
58.0k
  DEBUGASSERT(content);
1381
1382
58.0k
  if(!curl_strnequal(headerline, header, hlen))
1383
54.7k
    return FALSE; /* does not start with header */
1384
1385
  /* pass the header */
1386
3.36k
  p = &headerline[hlen];
1387
1388
3.36k
  if(curlx_str_cspn(&p, &val, "\r\n"))
1389
72
    return FALSE;
1390
3.29k
  curlx_str_trimblanks(&val);
1391
1392
  /* find the content string in the rest of the line */
1393
3.29k
  if(curlx_strlen(&val) >= clen) {
1394
2.86k
    size_t len;
1395
2.86k
    p = curlx_str(&val);
1396
4.16k
    for(len = curlx_strlen(&val); len >= clen;) {
1397
4.11k
      struct Curl_str next;
1398
4.11k
      const char *o = p;
1399
      /* after a match there must be a comma, space, newline or NUL byte */
1400
4.11k
      if(curl_strnequal(p, content, clen) &&
1401
1.92k
         ((p[clen] == ',') || ISBLANK(p[clen]) || ISNEWLINE(p[clen]) ||
1402
135
          !p[clen]))
1403
1.79k
        return TRUE; /* match! */
1404
      /* advance to the next comma */
1405
2.32k
      if(curlx_str_until(&p, &next, len, ',') ||
1406
1.52k
         curlx_str_single(&p, ','))
1407
803
        break; /* no comma, get out */
1408
1409
      /* if there are more dummy commas, move over them as well */
1410
1.52k
      do
1411
8.61k
        curlx_str_passblanks(&p);
1412
8.61k
      while(!curlx_str_single(&p, ','));
1413
      /* trailing blanks may move the parsing point past the value end,
1414
         then there is nothing left to match */
1415
1.52k
      if((size_t)(p - o) > len)
1416
214
        break;
1417
1.30k
      len -= (p - o);
1418
1.30k
    }
1419
2.86k
  }
1420
1.50k
  return FALSE; /* no match */
1421
3.29k
}
1422
1423
struct cr_exp100_ctx {
1424
  struct Curl_creader super;
1425
  struct curltime start; /* time started waiting */
1426
  enum expect100 state;
1427
};
1428
1429
/* Expect: 100-continue client reader, blocking uploads */
1430
1431
static void http_exp100_continue(struct Curl_easy *data,
1432
                                 struct Curl_creader *reader)
1433
0
{
1434
0
  struct cr_exp100_ctx *ctx = reader->ctx;
1435
0
  if(ctx->state > EXP100_SEND_DATA) {
1436
0
    ctx->state = EXP100_SEND_DATA;
1437
0
    Curl_expire_clear(data, EXPIRE_100_TIMEOUT);
1438
0
  }
1439
0
}
1440
1441
static CURLcode cr_exp100_read(struct Curl_easy *data,
1442
                               struct Curl_creader *reader,
1443
                               char *buf, size_t blen,
1444
                               size_t *nread, bool *eos)
1445
0
{
1446
0
  struct cr_exp100_ctx *ctx = reader->ctx;
1447
0
  timediff_t ms;
1448
1449
0
  switch(ctx->state) {
1450
0
  case EXP100_SENDING_REQUEST:
1451
0
    if(!Curl_req_sendbuf_empty(data)) {
1452
      /* The initial request data has not been fully sent yet. Do
1453
       * not start the timer yet. */
1454
0
      DEBUGF(infof(data, "cr_exp100_read, request not full sent yet"));
1455
0
      *nread = 0;
1456
0
      *eos = FALSE;
1457
0
      return CURLE_OK;
1458
0
    }
1459
    /* We are now waiting for a reply from the server or
1460
     * a timeout on our side IFF the request has been fully sent. */
1461
0
    DEBUGF(infof(data, "cr_exp100_read, start AWAITING_CONTINUE, "
1462
0
                 "timeout %dms", data->set.expect_100_timeout));
1463
0
    ctx->state = EXP100_AWAITING_CONTINUE;
1464
0
    ctx->start = *Curl_pgrs_now(data);
1465
0
    Curl_expire_set(data, EXPIRE_100_TIMEOUT,
1466
0
                    data->set.expect_100_timeout, &ctx->start);
1467
0
    *nread = 0;
1468
0
    *eos = FALSE;
1469
0
    return CURLE_OK;
1470
0
  case EXP100_FAILED:
1471
0
    DEBUGF(infof(data, "cr_exp100_read, expectation failed, error"));
1472
0
    *nread = 0;
1473
0
    *eos = FALSE;
1474
0
    return CURLE_READ_ERROR;
1475
0
  case EXP100_AWAITING_CONTINUE:
1476
0
    ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->start);
1477
0
    if(ms < data->set.expect_100_timeout) {
1478
0
      DEBUGF(infof(data, "cr_exp100_read, AWAITING_CONTINUE, not expired"));
1479
0
      *nread = 0;
1480
0
      *eos = FALSE;
1481
0
      return CURLE_OK;
1482
0
    }
1483
    /* we have waited long enough, continue anyway */
1484
0
    http_exp100_continue(data, reader);
1485
0
    infof(data, "Done waiting for 100-continue");
1486
0
    FALLTHROUGH();
1487
0
  default:
1488
0
    DEBUGF(infof(data, "cr_exp100_read, pass through"));
1489
0
    return Curl_creader_read(data, reader->next, buf, blen, nread, eos);
1490
0
  }
1491
0
}
1492
1493
static void cr_exp100_done(struct Curl_easy *data,
1494
                           struct Curl_creader *reader, int premature)
1495
0
{
1496
0
  struct cr_exp100_ctx *ctx = reader->ctx;
1497
0
  ctx->state = premature ? EXP100_FAILED : EXP100_SEND_DATA;
1498
0
  Curl_expire_clear(data, EXPIRE_100_TIMEOUT);
1499
0
}
1500
1501
static const struct Curl_crtype cr_exp100 = {
1502
  "cr-exp100",
1503
  Curl_creader_def_init,
1504
  cr_exp100_read,
1505
  Curl_creader_def_close,
1506
  Curl_creader_def_needs_rewind,
1507
  Curl_creader_def_total_length,
1508
  Curl_creader_def_resume_from,
1509
  Curl_creader_def_cntrl,
1510
  Curl_creader_def_is_paused,
1511
  cr_exp100_done,
1512
  sizeof(struct cr_exp100_ctx)
1513
};
1514
1515
static CURLcode http_exp100_add_reader(struct Curl_easy *data)
1516
0
{
1517
0
  struct Curl_creader *reader = NULL;
1518
0
  CURLcode result;
1519
1520
0
  result = Curl_creader_create(&reader, data, &cr_exp100, CURL_CR_PROTOCOL);
1521
0
  if(!result)
1522
0
    result = Curl_creader_add(data, reader);
1523
0
  if(!result) {
1524
0
    struct cr_exp100_ctx *ctx = reader->ctx;
1525
0
    ctx->state = EXP100_SENDING_REQUEST;
1526
0
  }
1527
1528
0
  if(result && reader)
1529
0
    Curl_creader_free(data, reader);
1530
0
  return result;
1531
0
}
1532
1533
static void http_exp100_got100(struct Curl_easy *data)
1534
9
{
1535
9
  struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100);
1536
9
  if(r)
1537
0
    http_exp100_continue(data, r);
1538
9
}
1539
1540
static bool http_exp100_is_waiting(struct Curl_easy *data)
1541
740
{
1542
740
  struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100);
1543
740
  if(r) {
1544
0
    struct cr_exp100_ctx *ctx = r->ctx;
1545
0
    return ctx->state == EXP100_AWAITING_CONTINUE;
1546
0
  }
1547
740
  return FALSE;
1548
740
}
1549
1550
static void http_exp100_send_anyway(struct Curl_easy *data)
1551
0
{
1552
0
  struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100);
1553
0
  if(r)
1554
0
    http_exp100_continue(data, r);
1555
0
}
1556
1557
static bool http_exp100_is_selected(struct Curl_easy *data)
1558
0
{
1559
0
  struct Curl_creader *r = Curl_creader_get_by_type(data, &cr_exp100);
1560
0
  return !!r;
1561
0
}
1562
1563
/* this returns the socket to wait for in the DO and DOING state for the multi
1564
   interface and then we are always _sending_ a request and thus we wait for
1565
   the single socket to become writable only */
1566
CURLcode Curl_http_doing_pollset(struct Curl_easy *data,
1567
                                 struct easy_pollset *ps)
1568
0
{
1569
  /* write mode */
1570
0
  return Curl_pollset_add_out(data, ps, data->conn->chain.sock);
1571
0
}
1572
1573
CURLcode Curl_http_perform_pollset(struct Curl_easy *data,
1574
                                   struct easy_pollset *ps)
1575
8.50k
{
1576
8.50k
  struct connectdata *conn = data->conn;
1577
8.50k
  CURLcode result = CURLE_OK;
1578
1579
8.50k
  if(CURL_REQ_WANT_RECV(data)) {
1580
8.50k
    result = Curl_pollset_add_in(data, ps, conn->chain.sock);
1581
8.50k
  }
1582
1583
  /* on a "Expect: 100-continue" timed wait, do not poll for outgoing */
1584
8.50k
  if(!result && Curl_req_want_send(data) && !http_exp100_is_waiting(data)) {
1585
740
    result = Curl_pollset_add_out(data, ps, conn->chain.sock);
1586
740
  }
1587
8.50k
  return result;
1588
8.50k
}
1589
1590
static CURLcode http_write_header(struct Curl_easy *data,
1591
                                  const char *hd, size_t hdlen)
1592
1.14k
{
1593
1.14k
  CURLcode result;
1594
1.14k
  int writetype;
1595
1596
  /* now, only output this if the header AND body are requested:
1597
   */
1598
1.14k
  Curl_debug(data, CURLINFO_HEADER_IN, hd, hdlen);
1599
1600
1.14k
  writetype = CLIENTWRITE_HEADER |
1601
1.14k
    ((data->req.httpcode / 100 == 1) ? CLIENTWRITE_1XX : 0);
1602
1603
1.14k
  result = Curl_client_write(data, writetype, hd, hdlen);
1604
1.14k
  if(result)
1605
0
    return result;
1606
1607
1.14k
  result = Curl_bump_headersize(data, hdlen, FALSE);
1608
1.14k
  if(result)
1609
0
    return result;
1610
1611
1.14k
  data->req.deductheadercount = (100 <= data->req.httpcode &&
1612
1.14k
                                 199 >= data->req.httpcode) ?
1613
634
    data->req.headerbytecount : 0;
1614
1.14k
  return result;
1615
1.14k
}
1616
1617
/*
1618
 * Curl_http_done() gets called after a single HTTP request has been
1619
 * performed.
1620
 */
1621
1622
CURLcode Curl_http_done(struct Curl_easy *data,
1623
                        CURLcode status, bool premature)
1624
1.95k
{
1625
1.95k
  struct connectdata *conn = data->conn;
1626
1627
  /* Clear multipass flag. If authentication is not done yet, then it will get
1628
   * a chance to be set back to true when we output the next auth header */
1629
1.95k
  data->state.authhost.multipass = FALSE;
1630
1.95k
  data->state.authproxy.multipass = FALSE;
1631
1632
1.95k
  if(curlx_dyn_len(&data->state.headerb)) {
1633
0
    (void)http_write_header(data, curlx_dyn_ptr(&data->state.headerb),
1634
0
                            curlx_dyn_len(&data->state.headerb));
1635
0
  }
1636
1.95k
  curlx_dyn_reset(&data->state.headerb);
1637
1638
1.95k
  if(status)
1639
619
    return status;
1640
1641
1.33k
  if(!premature && /* this check is pointless when DONE is called before the
1642
                      entire operation is complete */
1643
533
     !conn->bits.retry &&
1644
533
     !data->set.connect_only &&
1645
533
     (data->req.bytecount +
1646
533
      data->req.headerbytecount -
1647
533
      data->req.deductheadercount) <= 0) {
1648
    /* If this connection is not closed to be retried, AND nothing was
1649
       read from the HTTP server (that counts), this cannot be right so we
1650
       return an error here */
1651
0
    failf(data, "Empty reply from server");
1652
    /* Mark it as closed to avoid the "left intact" message */
1653
0
    streamclose(conn);
1654
0
    return CURLE_GOT_NOTHING;
1655
0
  }
1656
1657
1.33k
  return CURLE_OK;
1658
1.33k
}
1659
1660
/* Determine if we may use HTTP 1.1 for this request. */
1661
static bool http_may_use_1_1(const struct Curl_easy *data)
1662
0
{
1663
0
  const struct connectdata *conn = data->conn;
1664
  /* We have seen a previous response for *this* transfer with 1.0,
1665
   * on another connection or the same one. */
1666
0
  if(data->state.http_neg.rcvd_min == 10)
1667
0
    return FALSE;
1668
  /* We have seen a previous response on *this* connection with 1.0. */
1669
0
  if(conn && conn->httpversion_seen == 10)
1670
0
    return FALSE;
1671
  /* We want 1.0 and have seen no previous response on *this* connection
1672
     with a higher version (maybe no response at all yet). */
1673
0
  if(data->state.http_neg.only_10 &&
1674
0
     (!conn || conn->httpversion_seen <= 10))
1675
0
    return FALSE;
1676
  /* We are not restricted to use 1.0 only. */
1677
0
  return !data->state.http_neg.only_10;
1678
0
}
1679
1680
static unsigned char http_request_version(struct Curl_easy *data)
1681
1.94k
{
1682
1.94k
  unsigned char v = Curl_conn_http_version(data, data->conn);
1683
1.94k
  if(!v) {
1684
    /* No specific HTTP connection filter installed. */
1685
0
    v = http_may_use_1_1(data) ? 11 : 10;
1686
0
  }
1687
1.94k
  return v;
1688
1.94k
}
1689
1690
static const char *get_http_string(int httpversion)
1691
1.94k
{
1692
1.94k
  switch(httpversion) {
1693
1.94k
  case 30:
1694
1.94k
    return "3";
1695
0
  case 20:
1696
0
    return "2";
1697
0
  case 11:
1698
0
    return "1.1";
1699
0
  default:
1700
0
    return "1.0";
1701
1.94k
  }
1702
1.94k
}
1703
1704
struct http_custom_ctx {
1705
  struct Curl_easy *data;
1706
  struct dynbuf *req;
1707
  int httpversion;
1708
};
1709
1710
static CURLcode http_custom_treat(void *user_data,
1711
                                  struct Curl_str *name,
1712
                                  struct Curl_str *value,
1713
                                  const char *orig_data)
1714
68
{
1715
68
  struct http_custom_ctx *x = user_data;
1716
68
  CURLcode result;
1717
1718
68
  if(x->data->state.http_host &&
1719
     /* a Host: header was sent already, do not pass on any custom
1720
        Host: header as that will produce *two* in the same
1721
        request! */
1722
68
     curlx_str_casecompare2(name, STRCONST("Host")))
1723
0
    goto out;
1724
68
  else if(x->data->state.httpreq == HTTPREQ_POST_FORM &&
1725
          /* this header (extended by formdata.c) is sent later */
1726
0
          curlx_str_casecompare2(name, STRCONST("Content-Type")))
1727
0
    goto out;
1728
68
  else if(x->data->state.httpreq == HTTPREQ_POST_MIME &&
1729
          /* this header is sent later */
1730
33
          curlx_str_casecompare2(name, STRCONST("Content-Type")))
1731
0
    goto out;
1732
68
  else if(x->data->req.authneg &&
1733
          /* while doing auth neg, do not allow the custom length since
1734
             we will force length zero then */
1735
0
          curlx_str_casecompare2(name, STRCONST("Content-Length")))
1736
0
    goto out;
1737
68
  else if(curlx_str_casecompare2(name, STRCONST("Connection")))
1738
    /* Connection headers are handled specially */
1739
0
    goto out;
1740
68
  else if((x->httpversion >= 20) &&
1741
68
          curlx_str_casecompare2(name, STRCONST("Transfer-Encoding")))
1742
    /* HTTP/2 does not support chunked requests */
1743
0
    goto out;
1744
68
  else if((curlx_str_casecompare2(name, STRCONST("Authorization")) ||
1745
68
           curlx_str_casecompare2(name, STRCONST("Cookie"))) &&
1746
          /* be careful of sending this potentially sensitive header to
1747
             other hosts */
1748
0
          !Curl_auth_allowed_to_host(x->data))
1749
0
    goto out;
1750
1751
68
  if(!curlx_strlen(value)) {
1752
0
    result = curlx_dyn_addn(x->req, curlx_str(name), curlx_strlen(name));
1753
0
    if(!result)
1754
0
      result = curlx_dyn_addn(x->req, STRCONST(":\r\n"));
1755
0
  }
1756
68
  else
1757
68
    result = curlx_dyn_addf(x->req, "%s\r\n", orig_data);
1758
1759
68
  if(result)
1760
0
    return result;
1761
1762
68
out:
1763
68
  return CURLE_AGAIN;
1764
68
}
1765
1766
CURLcode Curl_add_custom_headers(struct Curl_easy *data,
1767
                                 int httpversion,
1768
                                 struct dynbuf *req)
1769
1.94k
{
1770
1.94k
  struct curl_slist *h[2];
1771
1.94k
  struct http_custom_ctx custom_ctx;
1772
1.94k
  int numlists = 0;
1773
1.94k
  int i;
1774
1775
1.94k
  h[numlists++] = data->set.headers;
1776
1.94k
#ifndef CURL_DISABLE_PROXY
1777
1.94k
  if(data->conn->bits.origin_is_proxy &&
1778
0
     data->set.sep_headers)
1779
0
      h[numlists++] = data->set.proxyheaders;
1780
1.94k
#endif
1781
1782
  /* loop through one or two lists */
1783
1.94k
  custom_ctx.data = data;
1784
1.94k
  custom_ctx.req = req;
1785
1.94k
  custom_ctx.httpversion = httpversion;
1786
3.89k
  for(i = 0; i < numlists; i++) {
1787
1.94k
    CURLcode result =
1788
1.94k
      Curl_dynhds_add_slist(NULL, h[i], http_custom_treat, &custom_ctx);
1789
1.94k
    if(result)
1790
0
      return result;
1791
1.94k
  }
1792
1793
1.94k
  return CURLE_OK;
1794
1.94k
}
1795
1796
#ifndef CURL_DISABLE_PARSEDATE
1797
CURLcode Curl_add_timecondition(struct Curl_easy *data,
1798
                                struct dynbuf *req)
1799
1.94k
{
1800
1.94k
  const struct tm *tm;
1801
1.94k
  struct tm keeptime;
1802
1.94k
  CURLcode result;
1803
1.94k
  char datestr[80];
1804
1.94k
  const char *condp;
1805
1.94k
  size_t len;
1806
1807
1.94k
  if(data->set.timecondition == CURL_TIMECOND_NONE)
1808
    /* no condition was asked for */
1809
1.94k
    return CURLE_OK;
1810
1811
0
  result = curlx_gmtime(data->set.timevalue, &keeptime);
1812
0
  if(result) {
1813
0
    failf(data, "Invalid TIMEVALUE");
1814
0
    return result;
1815
0
  }
1816
0
  tm = &keeptime;
1817
1818
0
  switch(data->set.timecondition) {
1819
0
  default:
1820
0
    DEBUGF(infof(data, "invalid time condition"));
1821
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
1822
1823
0
  case CURL_TIMECOND_IFMODSINCE:
1824
0
    condp = "If-Modified-Since";
1825
0
    len = 17;
1826
0
    break;
1827
0
  case CURL_TIMECOND_IFUNMODSINCE:
1828
0
    condp = "If-Unmodified-Since";
1829
0
    len = 19;
1830
0
    break;
1831
0
  case CURL_TIMECOND_LASTMOD:
1832
0
    condp = "Last-Modified";
1833
0
    len = 13;
1834
0
    break;
1835
0
  }
1836
1837
0
  if(Curl_checkheaders(data, condp, len)) {
1838
    /* A custom header was specified; it will be sent instead. */
1839
0
    return CURLE_OK;
1840
0
  }
1841
1842
  /* The If-Modified-Since header family should have their times set in
1843
   * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
1844
   * represented in Greenwich Mean Time (GMT), without exception. For the
1845
   * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
1846
   * Time)." (see page 20 of RFC2616).
1847
   */
1848
1849
  /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
1850
0
  curl_msnprintf(datestr, sizeof(datestr),
1851
0
                 "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
1852
0
                 condp,
1853
0
                 Curl_wkday[tm->tm_wday ? tm->tm_wday - 1 : 6],
1854
0
                 tm->tm_mday,
1855
0
                 Curl_month[tm->tm_mon],
1856
0
                 tm->tm_year + 1900,
1857
0
                 tm->tm_hour,
1858
0
                 tm->tm_min,
1859
0
                 tm->tm_sec);
1860
1861
0
  result = curlx_dyn_add(req, datestr);
1862
0
  return result;
1863
0
}
1864
#else
1865
/* disabled */
1866
CURLcode Curl_add_timecondition(struct Curl_easy *data,
1867
                                struct dynbuf *req)
1868
{
1869
  (void)data;
1870
  (void)req;
1871
  return CURLE_OK;
1872
}
1873
#endif
1874
1875
void Curl_http_method(struct Curl_easy *data,
1876
                      const char **method, Curl_HttpReq *reqp)
1877
1.95k
{
1878
1.95k
  Curl_HttpReq httpreq = (Curl_HttpReq)data->state.httpreq;
1879
1.95k
  const char *request;
1880
1.95k
#ifndef CURL_DISABLE_WEBSOCKETS
1881
1.95k
  if(data->conn->scheme->protocol & (CURLPROTO_WS | CURLPROTO_WSS))
1882
0
    httpreq = HTTPREQ_GET;
1883
1.95k
  else
1884
1.95k
#endif
1885
1.95k
  if((data->conn->scheme->protocol & (PROTO_FAMILY_HTTP | CURLPROTO_FTP)) &&
1886
1.95k
     data->state.upload)
1887
37
    httpreq = HTTPREQ_PUT;
1888
1889
  /* Now set the 'request' pointer to the proper request string */
1890
1.95k
  if(!data->state.http_ignorecustom &&
1891
1.95k
     CURL_EASY_STR(data, STRING_CUSTOMREQUEST)) {
1892
21
    request = CURL_EASY_STR(data, STRING_CUSTOMREQUEST);
1893
21
  }
1894
1.93k
  else {
1895
1.93k
    if(data->req.no_body)
1896
12
      request = "HEAD";
1897
1.92k
    else {
1898
1.92k
      DEBUGASSERT((httpreq >= HTTPREQ_GET) && (httpreq <= HTTPREQ_HEAD));
1899
1.92k
      switch(httpreq) {
1900
22
      case HTTPREQ_POST:
1901
22
      case HTTPREQ_POST_FORM:
1902
399
      case HTTPREQ_POST_MIME:
1903
399
        request = "POST";
1904
399
        break;
1905
36
      case HTTPREQ_PUT:
1906
36
        request = "PUT";
1907
36
        break;
1908
0
      default: /* this should never happen */
1909
1.49k
      case HTTPREQ_GET:
1910
1.49k
        request = "GET";
1911
1.49k
        break;
1912
0
      case HTTPREQ_HEAD:
1913
0
        request = "HEAD";
1914
0
        break;
1915
1.92k
      }
1916
1.92k
    }
1917
1.93k
  }
1918
1.95k
  *method = request;
1919
1.95k
  *reqp = httpreq;
1920
1.95k
}
1921
1922
static CURLcode http_set_aptr_host(struct Curl_easy *data)
1923
1.95k
{
1924
1.95k
  struct connectdata *conn = data->conn;
1925
1.95k
  const char *ptr = NULL;
1926
1927
1.95k
  curlx_safefree(data->state.http_host);
1928
1.95k
#ifndef CURL_DISABLE_COOKIES
1929
1.95k
  curlx_safefree(data->req.cookiehost);
1930
1.95k
#endif
1931
1932
1.95k
  if(Curl_peer_equal(data->state.initial_origin, data->state.origin))
1933
1.95k
    ptr = Curl_checkheaders(data, STRCONST("Host"));
1934
1935
1.95k
  if(ptr) {
1936
0
#ifndef CURL_DISABLE_COOKIES
1937
    /* If we have a given custom Host: header, we extract the hostname in
1938
       order to possibly use it for cookie reasons later on. We only allow the
1939
       custom Host: header if this is NOT a redirect, as setting Host: in the
1940
       redirected request is being out on thin ice. Except if the hostname
1941
       is the same as the first one! */
1942
0
    char *cookiehost;
1943
0
    CURLcode result = copy_custom_value(ptr, &cookiehost);
1944
0
    if(result)
1945
0
      return result;
1946
0
    if(!*cookiehost)
1947
      /* ignore empty data */
1948
0
      curlx_free(cookiehost);
1949
0
    else {
1950
      /* If the host begins with '[', we start searching for the port after
1951
         the bracket has been closed */
1952
0
      if(*cookiehost == '[') {
1953
0
        char *closingbracket;
1954
        /* since the 'cookiehost' is an allocated memory area that will be
1955
           freed later we cannot increment the pointer */
1956
0
        memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
1957
0
        closingbracket = strchr(cookiehost, ']');
1958
0
        if(closingbracket)
1959
0
          *closingbracket = 0;
1960
0
      }
1961
0
      else {
1962
0
        int startsearch = 0;
1963
0
        char *colon = strchr(cookiehost + startsearch, ':');
1964
0
        if(colon)
1965
0
          *colon = 0; /* The host must not include an embedded port number */
1966
0
      }
1967
0
      data->req.cookiehost = cookiehost;
1968
0
    }
1969
0
#endif
1970
1971
0
    if(!curl_strequal("Host:", ptr)) {
1972
0
      data->state.http_host = curl_maprintf("Host:%s", &ptr[5]);
1973
0
      if(!data->state.http_host)
1974
0
        return CURLE_OUT_OF_MEMORY;
1975
0
    }
1976
0
  }
1977
1.95k
  else {
1978
    /* This is the  HTTP Host: header, so we want
1979
     * - for IPv6 origins: "[ipv6-address]" where the IPv6 address is
1980
     *  found in origin->hostname, stripped of zoneid/scopeid.
1981
     * - the (IDN converted) origin->hostname (DNS name or IPv4) otherwise.
1982
     * Note: zoneid/scopeid  only applies to local routing and has no
1983
     * meaning on the remote HTTP server (eg. would confuse it). */
1984
1.95k
    bool ipv6 = (bool)data->state.origin->ipv6;
1985
1.95k
    struct dynbuf tmp;
1986
1.95k
    size_t hlen;
1987
1.95k
    CURLcode result;
1988
1989
1.95k
    curlx_dyn_init(&tmp, DYN_HTTP_REQUEST);
1990
1.95k
    result = curlx_dyn_addn(&tmp, STRCONST("Host: "));
1991
1.95k
    if(!result && ipv6)
1992
0
      result = curlx_dyn_addn(&tmp, STRCONST("["));
1993
1.95k
    if(!result)
1994
1.95k
      result = curlx_dyn_add(&tmp, data->state.origin->hostname);
1995
1.95k
    if(!result && ipv6)
1996
0
      result = curlx_dyn_addn(&tmp, STRCONST("]"));
1997
1.95k
    if(!result &&
1998
1.95k
       ((data->state.origin->port != data->state.origin->scheme->defport) ||
1999
1.95k
       (data->state.origin->scheme->family != conn->scheme->family))) {
2000
0
      result = curlx_dyn_addf(&tmp, ":%u", data->state.origin->port);
2001
0
    }
2002
2003
1.95k
    data->state.http_host = result ? NULL : curlx_dyn_take(&tmp, &hlen);
2004
1.95k
    curlx_dyn_free(&tmp);
2005
1.95k
    return result;
2006
1.95k
  }
2007
0
  return CURLE_OK;
2008
1.95k
}
2009
2010
/*
2011
 * Append the request-target to the HTTP request
2012
 */
2013
static CURLcode http_target(struct Curl_easy *data,
2014
                            struct dynbuf *r)
2015
1.94k
{
2016
1.94k
  CURLcode result = CURLE_OK;
2017
1.94k
  const char *path = data->state.up.path;
2018
1.94k
  const char *query = data->state.up.query;
2019
1.94k
#ifndef CURL_DISABLE_PROXY
2020
1.94k
  struct connectdata *conn = data->conn;
2021
1.94k
#endif
2022
2023
1.94k
  if(CURL_EASY_STR(data, STRING_TARGET)) {
2024
10
    path = CURL_EASY_STR(data, STRING_TARGET);
2025
10
    query = NULL;
2026
10
  }
2027
2028
1.94k
#ifndef CURL_DISABLE_PROXY
2029
1.94k
  if(conn->bits.origin_is_proxy) {
2030
    /* Using a proxy but does not tunnel through it */
2031
2032
    /* The path sent to the proxy is in fact the entire URL, but if the remote
2033
       host is a IDN-name, we must make sure that the request we produce only
2034
       uses the decoded hostname! */
2035
2036
    /* and no fragment part */
2037
0
    CURLUcode uc;
2038
0
    char *url;
2039
0
    CURLU *h = curl_url_dup(data->state.uh);
2040
0
    if(!h)
2041
0
      return CURLE_OUT_OF_MEMORY;
2042
2043
0
    if(!data->state.origin->ipv6 &&
2044
0
       (data->state.origin->user_hostname != data->state.origin->hostname)) {
2045
0
      uc = curl_url_set(h, CURLUPART_HOST, data->state.origin->hostname, 0);
2046
0
      if(uc) {
2047
0
        curl_url_cleanup(h);
2048
0
        return CURLE_OUT_OF_MEMORY;
2049
0
      }
2050
0
    }
2051
0
    uc = curl_url_set(h, CURLUPART_FRAGMENT, NULL, 0);
2052
0
    if(uc) {
2053
0
      curl_url_cleanup(h);
2054
0
      return CURLE_OUT_OF_MEMORY;
2055
0
    }
2056
2057
0
    if(data->state.origin->scheme == &Curl_scheme_http) {
2058
      /* when getting HTTP, we do not want the userinfo the URL */
2059
0
      uc = curl_url_set(h, CURLUPART_USER, NULL, 0);
2060
0
      if(uc) {
2061
0
        curl_url_cleanup(h);
2062
0
        return CURLE_OUT_OF_MEMORY;
2063
0
      }
2064
0
      uc = curl_url_set(h, CURLUPART_PASSWORD, NULL, 0);
2065
0
      if(uc) {
2066
0
        curl_url_cleanup(h);
2067
0
        return CURLE_OUT_OF_MEMORY;
2068
0
      }
2069
0
    }
2070
0
    else if(data->state.creds && (data->state.creds->source != CREDS_URL)) {
2071
        /* credentials not from the URL need to be set */
2072
0
      uc = curl_url_set(h, CURLUPART_USER,
2073
0
                        data->state.creds->user, CURLU_URLENCODE);
2074
0
      if(!uc)
2075
0
        uc = curl_url_set(h, CURLUPART_PASSWORD,
2076
0
                          data->state.creds->passwd, CURLU_URLENCODE);
2077
0
      if(uc) {
2078
0
        curl_url_cleanup(h);
2079
0
        return Curl_uc_to_curlcode(uc);
2080
0
      }
2081
0
    }
2082
2083
    /* Extract the URL to use in the request. */
2084
0
    uc = curl_url_get(h, CURLUPART_URL, &url, CURLU_NO_DEFAULT_PORT);
2085
0
    if(uc) {
2086
0
      curl_url_cleanup(h);
2087
0
      return CURLE_OUT_OF_MEMORY;
2088
0
    }
2089
2090
0
    curl_url_cleanup(h);
2091
2092
    /* target or URL */
2093
0
    result = curlx_dyn_add(r, CURL_EASY_STR(data, STRING_TARGET) ?
2094
0
      CURL_EASY_STR(data, STRING_TARGET) : url);
2095
0
    curlx_free(url);
2096
0
    if(result)
2097
0
      return result;
2098
2099
0
    if((data->state.origin->scheme == &Curl_scheme_ftp) &&
2100
0
       data->set.proxy_transfer_mode) {
2101
      /* when doing ftp, append ;type=<a|i> if not present */
2102
0
      size_t len = strlen(path);
2103
0
      bool type_present = FALSE;
2104
0
      if((len >= 7) && !memcmp(&path[len - 7], ";type=", 6)) {
2105
0
        switch(Curl_raw_toupper(path[len - 1])) {
2106
0
        case 'A':
2107
0
        case 'D':
2108
0
        case 'I':
2109
0
          type_present = TRUE;
2110
0
          break;
2111
0
        }
2112
0
      }
2113
0
      if(!type_present) {
2114
0
        result = curlx_dyn_addf(r, ";type=%c",
2115
0
                                data->state.prefer_ascii ? 'a' : 'i');
2116
0
        if(result)
2117
0
          return result;
2118
0
      }
2119
0
    }
2120
0
  }
2121
2122
1.94k
  else
2123
1.94k
#endif
2124
1.94k
  {
2125
1.94k
    result = curlx_dyn_add(r, path);
2126
1.94k
    if(result)
2127
0
      return result;
2128
1.94k
    if(query)
2129
14
      result = curlx_dyn_addf(r, "?%s", query);
2130
1.94k
  }
2131
2132
1.94k
  return result;
2133
1.94k
}
2134
2135
#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API)
2136
static CURLcode set_post_reader(struct Curl_easy *data, Curl_HttpReq httpreq)
2137
377
{
2138
377
  CURLcode result;
2139
2140
377
  switch(httpreq) {
2141
0
#ifndef CURL_DISABLE_MIME
2142
377
  case HTTPREQ_POST_MIME:
2143
377
    data->state.mimepost = data->set.a.mimepostp;
2144
377
    break;
2145
0
#endif
2146
0
#ifndef CURL_DISABLE_FORM_API
2147
0
  case HTTPREQ_POST_FORM:
2148
    /* Convert the form structure into a mime structure, then keep
2149
       the conversion */
2150
0
    if(!data->state.formp) {
2151
0
      data->state.formp = curlx_calloc(1, sizeof(curl_mimepart));
2152
0
      if(!data->state.formp)
2153
0
        return CURLE_OUT_OF_MEMORY;
2154
0
      Curl_mime_cleanpart(data->state.formp);
2155
0
      result = Curl_getformdata(data, data->state.formp, data->set.httppost,
2156
0
                                data->state.fread_func);
2157
0
      if(result) {
2158
0
        curlx_safefree(data->state.formp);
2159
0
        return result;
2160
0
      }
2161
0
      data->state.mimepost = data->state.formp;
2162
0
    }
2163
0
    break;
2164
0
#endif
2165
0
  default:
2166
0
    data->state.mimepost = NULL;
2167
0
    break;
2168
377
  }
2169
2170
377
  switch(httpreq) {
2171
0
  case HTTPREQ_POST_FORM:
2172
377
  case HTTPREQ_POST_MIME:
2173
    /* This is form posting using mime data. */
2174
377
#ifndef CURL_DISABLE_MIME
2175
377
    if(data->state.mimepost) {
2176
377
      const char *cthdr = Curl_checkheaders(data, STRCONST("Content-Type"));
2177
2178
      /* Read and seek body only. */
2179
377
      data->state.mimepost->flags |= MIME_BODY_ONLY;
2180
2181
      /* Prepare the mime structure headers & set content type. */
2182
2183
377
      if(cthdr)
2184
0
        for(cthdr += 13; *cthdr == ' '; cthdr++)
2185
0
          ;
2186
377
      else if(data->state.mimepost->kind == MIMEKIND_MULTIPART)
2187
377
        cthdr = "multipart/form-data";
2188
2189
377
      curl_mime_headers(data->state.mimepost, data->set.headers, 0);
2190
377
      result = Curl_mime_prepare_headers(data, data->state.mimepost, cthdr,
2191
377
                                         NULL, MIMESTRATEGY_FORM);
2192
377
      curl_mime_headers(data->state.mimepost, NULL, 0);
2193
377
      if(result)
2194
1
        return result;
2195
376
      result = Curl_creader_set_mime(data, data->state.mimepost);
2196
376
      if(result)
2197
0
        return result;
2198
376
    }
2199
0
    else
2200
0
#endif
2201
0
    {
2202
0
      result = Curl_creader_set_null(data);
2203
0
    }
2204
376
    data->state.infilesize = Curl_creader_total_length(data);
2205
376
    return result;
2206
2207
0
  default:
2208
0
    return Curl_creader_set_null(data);
2209
377
  }
2210
  /* never reached */
2211
377
}
2212
#endif
2213
2214
static CURLcode set_reader(struct Curl_easy *data, Curl_HttpReq httpreq)
2215
1.94k
{
2216
1.94k
  CURLcode result = CURLE_OK;
2217
1.94k
  curl_off_t postsize = data->state.infilesize;
2218
2219
1.94k
  DEBUGASSERT(data->conn);
2220
2221
1.94k
  if(data->req.authneg) {
2222
1
    return Curl_creader_set_null(data);
2223
1
  }
2224
2225
1.94k
  switch(httpreq) {
2226
36
  case HTTPREQ_PUT: /* Let's PUT the data to the server! */
2227
36
    return postsize ? Curl_creader_set_fread(data, postsize) :
2228
36
      Curl_creader_set_null(data);
2229
2230
0
#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API)
2231
0
  case HTTPREQ_POST_FORM:
2232
377
  case HTTPREQ_POST_MIME:
2233
377
    return set_post_reader(data, httpreq);
2234
0
#endif
2235
2236
22
  case HTTPREQ_POST:
2237
    /* this is the simple POST, using x-www-form-urlencoded style */
2238
    /* the size of the post body */
2239
22
    if(!postsize) {
2240
7
      result = Curl_creader_set_null(data);
2241
7
    }
2242
15
    else if(data->set.postfields) {
2243
7
      size_t plen = curlx_sotouz_range(postsize, 0, SIZE_MAX);
2244
7
      if(plen == SIZE_MAX)
2245
0
        return CURLE_OUT_OF_MEMORY;
2246
7
      else if(plen)
2247
7
        result = Curl_creader_set_buf(data, data->set.postfields, plen);
2248
0
      else
2249
0
        result = Curl_creader_set_null(data);
2250
7
    }
2251
8
    else {
2252
      /* we read the bytes from the callback. In case "chunked" encoding
2253
       * is forced by the application, we disregard `postsize`. This is
2254
       * a backward compatibility decision to earlier versions where
2255
       * chunking disregarded this. See issue #13229. */
2256
8
      bool chunked = FALSE;
2257
8
      char *ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding"));
2258
8
      if(ptr) {
2259
        /* Some kind of TE is requested, check if 'chunked' is chosen */
2260
0
        chunked = Curl_compareheader(ptr, STRCONST("Transfer-Encoding:"),
2261
0
                                     STRCONST("chunked"));
2262
0
      }
2263
8
      result = Curl_creader_set_fread(data, chunked ? -1 : postsize);
2264
8
    }
2265
22
    return result;
2266
2267
1.51k
  default:
2268
    /* HTTP GET/HEAD download, has no body, needs no Content-Length */
2269
1.51k
    data->state.infilesize = 0;
2270
1.51k
    return Curl_creader_set_null(data);
2271
1.94k
  }
2272
  /* not reached */
2273
1.94k
}
2274
2275
static CURLcode http_resume(struct Curl_easy *data, Curl_HttpReq httpreq)
2276
1.94k
{
2277
1.94k
  if((HTTPREQ_POST == httpreq || HTTPREQ_POST_FORM == httpreq ||
2278
1.92k
      HTTPREQ_POST_MIME == httpreq || HTTPREQ_PUT == httpreq) &&
2279
435
     data->state.resume_from) {
2280
0
    failf(data, "HTTP upload cannot be resumed");
2281
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
2282
0
  }
2283
1.94k
  return CURLE_OK;
2284
1.94k
}
2285
2286
static CURLcode http_req_set_TE(struct Curl_easy *data,
2287
                                struct dynbuf *req,
2288
                                int httpversion)
2289
1.94k
{
2290
1.94k
  CURLcode result = CURLE_OK;
2291
1.94k
  const char *ptr;
2292
2293
1.94k
  ptr = Curl_checkheaders(data, STRCONST("Transfer-Encoding"));
2294
1.94k
  if(ptr) {
2295
    /* Some kind of TE is requested, check if 'chunked' is chosen */
2296
0
    data->req.upload_chunky =
2297
0
      Curl_compareheader(ptr,
2298
0
                         STRCONST("Transfer-Encoding:"), STRCONST("chunked"));
2299
0
    if(data->req.upload_chunky && (httpversion >= 20)) {
2300
0
      infof(data, "suppressing chunked transfer encoding on connection "
2301
0
            "using HTTP version 2 or higher");
2302
0
      data->req.upload_chunky = FALSE;
2303
0
    }
2304
0
  }
2305
1.94k
  else {
2306
1.94k
    curl_off_t req_clen = Curl_creader_total_length(data);
2307
2308
1.94k
    if(req_clen < 0) {
2309
      /* indeterminate request content length */
2310
52
      if(httpversion > 10) {
2311
        /* On HTTP/1.1, enable chunked, on HTTP/2 and later we do not
2312
         * need it */
2313
52
        data->req.upload_chunky = (httpversion < 20);
2314
52
      }
2315
0
      else {
2316
0
        failf(data, "Chunky upload is not supported by HTTP 1.0");
2317
0
        return CURLE_UPLOAD_FAILED;
2318
0
      }
2319
52
    }
2320
1.89k
    else {
2321
      /* else, no chunky upload */
2322
1.89k
      data->req.upload_chunky = FALSE;
2323
1.89k
    }
2324
2325
1.94k
    if(data->req.upload_chunky)
2326
0
      result = curlx_dyn_add(req, "Transfer-Encoding: chunked\r\n");
2327
1.94k
  }
2328
1.94k
  return result;
2329
1.94k
}
2330
2331
static CURLcode addexpect(struct Curl_easy *data, struct dynbuf *r,
2332
                          int httpversion, bool *announced_exp100)
2333
435
{
2334
435
  CURLcode result;
2335
435
  char *ptr;
2336
2337
435
  *announced_exp100 = FALSE;
2338
  /* Avoid Expect: 100-continue if Upgrade: is used */
2339
435
  if(data->req.upgr101 != UPGR101_NONE)
2340
0
    return CURLE_OK;
2341
2342
  /* For really small puts we do not use Expect: headers at all, and for
2343
     the somewhat bigger ones we allow the app to disable it. Make
2344
     sure that the expect100header is always set to the preferred value
2345
     here. */
2346
435
  ptr = Curl_checkheaders(data, STRCONST("Expect"));
2347
435
  if(ptr) {
2348
0
    *announced_exp100 =
2349
0
      Curl_compareheader(ptr, STRCONST("Expect:"), STRCONST("100-continue"));
2350
0
  }
2351
435
  else if(!data->state.disableexpect && (httpversion == 11)) {
2352
    /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an
2353
       Expect: 100-continue to the headers which actually speeds up post
2354
       operations (as there is one packet coming back from the web server) */
2355
0
    curl_off_t client_len = Curl_creader_client_length(data);
2356
0
    if(client_len > EXPECT_100_THRESHOLD || client_len < 0) {
2357
0
      result = curlx_dyn_addn(r, STRCONST("Expect: 100-continue\r\n"));
2358
0
      if(result)
2359
0
        return result;
2360
0
      *announced_exp100 = TRUE;
2361
0
    }
2362
0
  }
2363
435
  return CURLE_OK;
2364
435
}
2365
2366
static CURLcode http_add_content_hds(struct Curl_easy *data,
2367
                                     struct dynbuf *r,
2368
                                     int httpversion,
2369
                                     Curl_HttpReq httpreq)
2370
1.94k
{
2371
1.94k
  CURLcode result = CURLE_OK;
2372
1.94k
  curl_off_t req_clen;
2373
1.94k
  bool announced_exp100 = FALSE;
2374
2375
1.94k
  DEBUGASSERT(data->conn);
2376
1.94k
  if(data->req.upload_chunky) {
2377
0
    result = Curl_httpchunk_add_reader(data);
2378
0
    if(result)
2379
0
      return result;
2380
0
  }
2381
2382
  /* Get the request body length that has been set up */
2383
1.94k
  req_clen = Curl_creader_total_length(data);
2384
1.94k
  switch(httpreq) {
2385
37
  case HTTPREQ_PUT:
2386
59
  case HTTPREQ_POST:
2387
59
#if !defined(CURL_DISABLE_MIME) || !defined(CURL_DISABLE_FORM_API)
2388
59
  case HTTPREQ_POST_FORM:
2389
435
  case HTTPREQ_POST_MIME:
2390
435
#endif
2391
    /* We only set Content-Length and allow a custom Content-Length if
2392
       we do not upload data chunked, as RFC2616 forbids us to set both
2393
       kinds of headers (Transfer-Encoding: chunked and Content-Length).
2394
       We do not override a custom "Content-Length" header, but during
2395
       authentication negotiation that header is suppressed.
2396
     */
2397
435
    if(req_clen >= 0 && !data->req.upload_chunky &&
2398
383
       (data->req.authneg ||
2399
383
        !Curl_checkheaders(data, STRCONST("Content-Length")))) {
2400
      /* we allow replacing this header if not during auth negotiation,
2401
         although it is not wise to actually set your own */
2402
383
      result = curlx_dyn_addf(r, "Content-Length: %" FMT_OFF_T "\r\n",
2403
383
                              req_clen);
2404
383
    }
2405
435
    if(result)
2406
0
      goto out;
2407
2408
435
#ifndef CURL_DISABLE_MIME
2409
    /* Output mime-generated headers. */
2410
435
    if(data->state.mimepost &&
2411
376
       ((httpreq == HTTPREQ_POST_FORM) || (httpreq == HTTPREQ_POST_MIME))) {
2412
376
      struct curl_slist *hdr;
2413
2414
752
      for(hdr = data->state.mimepost->curlheaders; hdr; hdr = hdr->next) {
2415
376
        result = curlx_dyn_addf(r, "%s\r\n", hdr->data);
2416
376
        if(result)
2417
0
          goto out;
2418
376
      }
2419
376
    }
2420
435
#endif
2421
435
    if(httpreq == HTTPREQ_POST &&
2422
22
       !Curl_checkheaders(data, STRCONST("Content-Type"))) {
2423
22
      result = curlx_dyn_addn(r, STRCONST("Content-Type: application/"
2424
22
                                          "x-www-form-urlencoded\r\n"));
2425
22
      if(result)
2426
0
        goto out;
2427
22
    }
2428
435
    result = addexpect(data, r, httpversion, &announced_exp100);
2429
435
    if(result)
2430
0
      goto out;
2431
435
    break;
2432
1.51k
  default:
2433
1.51k
    break;
2434
1.94k
  }
2435
2436
1.94k
  Curl_pgrsSetUploadSize(data, req_clen);
2437
1.94k
  if(announced_exp100)
2438
0
    result = http_exp100_add_reader(data);
2439
2440
1.94k
out:
2441
1.94k
  return result;
2442
1.94k
}
2443
2444
#ifndef CURL_DISABLE_COOKIES
2445
2446
static CURLcode http_cookies(struct Curl_easy *data,
2447
                             struct dynbuf *r)
2448
1.94k
{
2449
1.94k
  CURLcode result = CURLE_OK;
2450
1.94k
  const char *addcookies = NULL;
2451
1.94k
  bool linecap = FALSE;
2452
1.94k
  if(CURL_EASY_STR(data, STRING_COOKIE) &&
2453
15
     !Curl_checkheaders(data, STRCONST("Cookie")) &&
2454
15
     Curl_auth_allowed_to_host(data))
2455
15
    addcookies = CURL_EASY_STR(data, STRING_COOKIE);
2456
2457
1.94k
  if(data->cookies || addcookies) {
2458
1.94k
    struct Curl_llist list;
2459
1.94k
    int count = 0;
2460
2461
1.94k
    if(data->cookies && data->state.cookie_engine) {
2462
1.94k
      bool okay;
2463
1.94k
      const char *host = data->req.cookiehost ?
2464
1.94k
        data->req.cookiehost : data->state.origin->hostname;
2465
1.94k
      Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
2466
1.94k
      result = Curl_cookie_getlist(data, &okay, host, &list);
2467
1.94k
      if(!result && okay) {
2468
1
        struct Curl_llist_node *n;
2469
1
        size_t clen = 8; /* hold the size of the generated Cookie: header */
2470
2471
        /* loop through all cookies that matched */
2472
1
        for(n = Curl_llist_head(&list); n; n = Curl_node_next(n)) {
2473
0
          struct Cookie *co = Curl_node_elem(n);
2474
0
          if(co->value) {
2475
0
            size_t add;
2476
0
            if(!count) {
2477
0
              result = curlx_dyn_addn(r, STRCONST("Cookie: "));
2478
0
              if(result)
2479
0
                break;
2480
0
            }
2481
0
            add = strlen(co->name) + strlen(co->value) + 1;
2482
0
            if(clen + add >= MAX_COOKIE_HEADER_LEN) {
2483
0
              infof(data, "Restricted outgoing cookies due to header size, "
2484
0
                    "'%s' not sent", co->name);
2485
0
              linecap = TRUE;
2486
0
              break;
2487
0
            }
2488
0
            result = curlx_dyn_addf(r, "%s%s=%s", count ? "; " : "",
2489
0
                                    co->name, co->value);
2490
0
            if(result)
2491
0
              break;
2492
0
            clen += add + (count ? 2 : 0);
2493
0
            count++;
2494
0
          }
2495
0
        }
2496
1
        Curl_llist_destroy(&list, NULL);
2497
1
      }
2498
1.94k
      Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
2499
1.94k
    }
2500
1.94k
    if(addcookies && !result && !linecap) {
2501
15
      if(!count)
2502
15
        result = curlx_dyn_addn(r, STRCONST("Cookie: "));
2503
15
      if(!result) {
2504
15
        result = curlx_dyn_addf(r, "%s%s", count ? "; " : "", addcookies);
2505
15
        count++;
2506
15
      }
2507
15
    }
2508
1.94k
    if(count && !result)
2509
15
      result = curlx_dyn_addn(r, STRCONST("\r\n"));
2510
2511
1.94k
    if(result)
2512
0
      return result;
2513
1.94k
  }
2514
1.94k
  return result;
2515
1.94k
}
2516
#else
2517
#define http_cookies(a, b) CURLE_OK
2518
#endif
2519
2520
static CURLcode http_range(struct Curl_easy *data,
2521
                           Curl_HttpReq httpreq)
2522
1.94k
{
2523
1.94k
  if(data->state.use_range) {
2524
    /*
2525
     * A range is selected. We use different headers whether we are downloading
2526
     * or uploading and we always let customized headers override our internal
2527
     * ones if any such are specified.
2528
     */
2529
13
    if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
2530
13
       !Curl_checkheaders(data, STRCONST("Range"))) {
2531
      /* if a line like this was already allocated, free the previous one */
2532
13
      curlx_free(data->state.rangeline);
2533
13
      data->state.rangeline = curl_maprintf("Range: bytes=%s\r\n",
2534
13
                                                 data->state.range);
2535
13
      if(!data->state.rangeline)
2536
0
        return CURLE_OUT_OF_MEMORY;
2537
13
    }
2538
0
    else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) &&
2539
0
            !Curl_checkheaders(data, STRCONST("Content-Range"))) {
2540
0
      curl_off_t req_clen = Curl_creader_total_length(data);
2541
      /* if a line like this was already allocated, free the previous one */
2542
0
      curlx_free(data->state.rangeline);
2543
2544
0
      if(data->set.set_resume_from < 0) {
2545
        /* Upload resume was asked for, but we do not know the size of the
2546
           remote part so we tell the server (and act accordingly) that we
2547
           upload the whole file (again) */
2548
0
        data->state.rangeline =
2549
0
          curl_maprintf("Content-Range: bytes 0-%" FMT_OFF_T "/"
2550
0
                        "%" FMT_OFF_T "\r\n", req_clen - 1, req_clen);
2551
0
      }
2552
0
      else if(data->state.resume_from) {
2553
        /* This is because "resume" was selected */
2554
        /* Not sure if we want to send this header during authentication
2555
         * negotiation, but test1084 checks for it. In which case we have a
2556
         * "null" client reader installed that gives an unexpected length. */
2557
0
        curl_off_t total_len = data->req.authneg ?
2558
0
                               data->state.infilesize :
2559
0
                               (data->state.resume_from + req_clen);
2560
0
        data->state.rangeline =
2561
0
          curl_maprintf("Content-Range: bytes %s%" FMT_OFF_T "/"
2562
0
                        "%" FMT_OFF_T "\r\n",
2563
0
                        data->state.range, total_len - 1, total_len);
2564
0
      }
2565
0
      else {
2566
        /* Range was selected and then we pass the incoming range and append
2567
           total size */
2568
0
        data->state.rangeline =
2569
0
          curl_maprintf("Content-Range: bytes %s/%" FMT_OFF_T "\r\n",
2570
0
                        data->state.range, req_clen);
2571
0
      }
2572
0
      if(!data->state.rangeline)
2573
0
        return CURLE_OUT_OF_MEMORY;
2574
0
    }
2575
13
  }
2576
1.94k
  return CURLE_OK;
2577
1.94k
}
2578
2579
static CURLcode http_firstwrite(struct Curl_easy *data)
2580
634
{
2581
634
  struct connectdata *conn = data->conn;
2582
634
  struct SingleRequest *k = &data->req;
2583
2584
634
  if(data->req.newurl) {
2585
0
    if(conn->bits.close) {
2586
      /* Abort after the headers if "follow Location" is set
2587
         and we are set to close anyway. */
2588
0
      CURL_REQ_CLEAR_RECV(data);
2589
0
      k->done = TRUE;
2590
0
      return CURLE_OK;
2591
0
    }
2592
    /* We have a new URL to load, but since we want to be able to reuse this
2593
       connection properly, we read the full response in "ignore more" */
2594
0
    k->ignorebody = TRUE;
2595
0
    infof(data, "Ignoring the response-body");
2596
0
  }
2597
634
  if(data->state.resume_from && !k->content_range &&
2598
5
     (data->state.httpreq == HTTPREQ_GET) &&
2599
5
     !k->ignorebody) {
2600
2601
5
    if(k->size == data->state.resume_from) {
2602
      /* The resume point is at the end of file, consider this fine even if it
2603
         does not allow resume from here. */
2604
0
      infof(data, "The entire document is already downloaded");
2605
0
      streamclose(conn);
2606
      /* Abort download */
2607
0
      CURL_REQ_CLEAR_RECV(data);
2608
0
      k->done = TRUE;
2609
0
      return CURLE_OK;
2610
0
    }
2611
2612
    /* we wanted to resume a download, although the server does not seem to
2613
     * support this and we did this with a GET (if it was not a GET we did a
2614
     * POST or PUT resume) */
2615
5
    failf(data, "HTTP server does not seem to support "
2616
5
          "byte ranges. Cannot resume.");
2617
5
    return CURLE_RANGE_ERROR;
2618
5
  }
2619
2620
629
  if(data->set.timecondition && !data->state.range &&
2621
     /* A time condition has been set AND no ranges have been requested. This
2622
        seems to be what chapter 13.3.4 of RFC 2616 defines to be the correct
2623
        action for an HTTP/1.1 client */
2624
0
     !Curl_meets_timecondition(data, k->timeofdoc)) {
2625
0
    k->done = TRUE;
2626
    /* We are simulating an HTTP 304 from server so we return
2627
       what should have been returned from the server */
2628
0
    data->info.httpcode = 304;
2629
0
    infof(data, "Simulate an HTTP 304 response");
2630
    /* we abort the transfer before it is completed == we ruin the
2631
       reuse ability. Close the connection */
2632
0
    streamclose(conn);
2633
0
    return CURLE_OK;
2634
0
  } /* we have a time condition */
2635
2636
629
  return CURLE_OK;
2637
629
}
2638
2639
static CURLcode http_add_connection_hd(struct Curl_easy *data,
2640
                                       struct dynbuf *req)
2641
1.94k
{
2642
1.94k
  struct curl_slist *head;
2643
1.94k
  const char *sep = "Connection: ";
2644
1.94k
  CURLcode result = CURLE_OK;
2645
1.94k
  size_t rlen = curlx_dyn_len(req);
2646
1.94k
  bool skip;
2647
2648
  /* Add the 1st custom "Connection: " header, if there is one */
2649
2.85k
  for(head = data->set.headers; head; head = head->next) {
2650
909
    if(curl_strnequal(head->data, "Connection", 10) &&
2651
0
       Curl_headersep(head->data[10]) &&
2652
0
       !http_header_is_empty(head->data)) {
2653
0
      char *value;
2654
0
      result = copy_custom_value(head->data, &value);
2655
0
      if(result)
2656
0
        return result;
2657
0
      result = curlx_dyn_addf(req, "%s%s", sep, value);
2658
0
      sep = ", ";
2659
0
      curlx_free(value);
2660
0
      break; /* leave, having added 1st one */
2661
0
    }
2662
909
  }
2663
2664
  /* add our internal Connection: header values, if we have any */
2665
1.94k
  if(!result && data->state.http_hd_te) {
2666
4
    result = curlx_dyn_addf(req, "%s%s", sep, "TE");
2667
4
    sep = ", ";
2668
4
  }
2669
1.94k
  if(!result && data->state.http_hd_upgrade) {
2670
0
    result = curlx_dyn_addf(req, "%s%s", sep, "Upgrade");
2671
0
    sep = ", ";
2672
0
  }
2673
1.94k
  if(!result && data->state.http_hd_h2_settings) {
2674
0
    result = curlx_dyn_addf(req, "%s%s", sep, "HTTP2-Settings");
2675
0
  }
2676
1.94k
  if(!result && (rlen < curlx_dyn_len(req)))
2677
4
    result = curlx_dyn_addn(req, STRCONST("\r\n"));
2678
1.94k
  if(result)
2679
0
    return result;
2680
2681
  /* Add all user-defined Connection: headers after the first */
2682
1.94k
  skip = TRUE;
2683
2.85k
  for(head = data->set.headers; head; head = head->next) {
2684
909
    if(curl_strnequal(head->data, "Connection", 10) &&
2685
0
       Curl_headersep(head->data[10]) &&
2686
0
       !http_header_is_empty(head->data)) {
2687
0
      if(skip) {
2688
0
        skip = FALSE;
2689
0
        continue;
2690
0
      }
2691
0
      result = curlx_dyn_addf(req, "%s\r\n", head->data);
2692
0
      if(result)
2693
0
        return result;
2694
0
    }
2695
909
  }
2696
2697
1.94k
  return CURLE_OK;
2698
1.94k
}
2699
2700
/* Header identifier in order we send them by default */
2701
typedef enum {
2702
  H1_HD_REQUEST,
2703
  H1_HD_HOST,
2704
#ifndef CURL_DISABLE_PROXY
2705
  H1_HD_PROXY_AUTH,
2706
#endif
2707
  H1_HD_AUTH,
2708
  H1_HD_RANGE,
2709
  H1_HD_USER_AGENT,
2710
  H1_HD_ACCEPT,
2711
  H1_HD_TE,
2712
  H1_HD_ACCEPT_ENCODING,
2713
  H1_HD_REFERER,
2714
#ifndef CURL_DISABLE_PROXY
2715
  H1_HD_PROXY_CONNECTION,
2716
#endif
2717
  H1_HD_TRANSFER_ENCODING,
2718
#ifndef CURL_DISABLE_ALTSVC
2719
  H1_HD_ALT_USED,
2720
#endif
2721
  H1_HD_UPGRADE,
2722
  H1_HD_COOKIES,
2723
  H1_HD_CONDITIONALS,
2724
  H1_HD_CUSTOM,
2725
  H1_HD_CONTENT,
2726
  H1_HD_CONNECTION,
2727
  H1_HD_LAST  /* the last, empty header line */
2728
} http_hd_t;
2729
2730
static CURLcode http_add_hd(struct Curl_easy *data,
2731
                            struct dynbuf *req,
2732
                            http_hd_t id,
2733
                            unsigned char httpversion,
2734
                            const char *method,
2735
                            bool is_connect,
2736
                            Curl_HttpReq httpreq)
2737
38.9k
{
2738
38.9k
  struct connectdata *conn = data->conn;
2739
38.9k
  CURLcode result = CURLE_OK;
2740
2741
38.9k
  switch(id) {
2742
1.94k
  case H1_HD_REQUEST:
2743
    /* add the main request stuff */
2744
    /* GET/HEAD/POST/PUT */
2745
1.94k
    result = curlx_dyn_addf(req, "%s ", method);
2746
1.94k
    if(!result)
2747
1.94k
      result = http_target(data, req);
2748
1.94k
    if(!result)
2749
1.94k
      result = curlx_dyn_addf(req, " HTTP/%s\r\n",
2750
1.94k
                              get_http_string(httpversion));
2751
1.94k
    break;
2752
2753
1.94k
  case H1_HD_HOST:
2754
1.94k
    if(data->state.http_host) {
2755
1.94k
      result = curlx_dyn_add(req, data->state.http_host);
2756
1.94k
      if(!result)
2757
1.94k
        result = curlx_dyn_addn(req, STRCONST("\r\n"));
2758
1.94k
    }
2759
1.94k
    break;
2760
2761
0
#ifndef CURL_DISABLE_PROXY
2762
1.94k
  case H1_HD_PROXY_AUTH:
2763
1.94k
    if(data->req.hd_proxy_auth && (conn->bits.origin_is_proxy || is_connect))
2764
0
      result = curlx_dyn_add(req, data->req.hd_proxy_auth);
2765
1.94k
    break;
2766
0
#endif
2767
2768
1.94k
  case H1_HD_AUTH:
2769
1.94k
    if(data->req.hd_auth && !is_connect)
2770
11
      result = curlx_dyn_add(req, data->req.hd_auth);
2771
1.94k
    break;
2772
2773
1.94k
  case H1_HD_RANGE:
2774
1.94k
    if(data->state.use_range && data->state.rangeline)
2775
13
      result = curlx_dyn_add(req, data->state.rangeline);
2776
1.94k
    break;
2777
2778
1.94k
  case H1_HD_USER_AGENT: {
2779
1.94k
    const char *ua = CURL_EASY_STR(data, STRING_USERAGENT);
2780
1.94k
    if(ua && *ua && !Curl_checkheaders(data, STRCONST("User-Agent")))
2781
5
      result = curlx_dyn_addf(req, "User-Agent: %s\r\n", ua);
2782
1.94k
    break;
2783
0
  }
2784
2785
1.94k
  case H1_HD_ACCEPT:
2786
1.94k
    if(!Curl_checkheaders(data, STRCONST("Accept")))
2787
1.93k
      result = curlx_dyn_add(req, "Accept: */*\r\n");
2788
1.94k
    break;
2789
2790
1.94k
  case H1_HD_TE:
2791
1.94k
#ifdef HAVE_LIBZ
2792
1.94k
    if(!Curl_checkheaders(data, STRCONST("TE")) &&
2793
1.94k
       data->set.http_transfer_encoding) {
2794
4
      data->state.http_hd_te = TRUE;
2795
4
      result = curlx_dyn_add(req, "TE: gzip\r\n");
2796
4
    }
2797
1.94k
#endif
2798
1.94k
    break;
2799
2800
1.94k
  case H1_HD_ACCEPT_ENCODING: {
2801
1.94k
    const char *enc = CURL_EASY_STR(data, STRING_ENCODING);
2802
1.94k
    if(enc && !Curl_checkheaders(data, STRCONST("Accept-Encoding")))
2803
19
      result = curlx_dyn_addf(req, "Accept-Encoding: %s\r\n", enc);
2804
1.94k
    break;
2805
0
  }
2806
2807
1.94k
  case H1_HD_REFERER:
2808
1.94k
    if(Curl_bufref_ptr(&data->state.referer) &&
2809
13
       !Curl_checkheaders(data, STRCONST("Referer")))
2810
13
      result = curlx_dyn_addf(req, "Referer: %s\r\n",
2811
13
                              Curl_bufref_ptr(&data->state.referer));
2812
1.94k
    break;
2813
2814
0
#ifndef CURL_DISABLE_PROXY
2815
1.94k
  case H1_HD_PROXY_CONNECTION:
2816
1.94k
    if(conn->bits.origin_is_proxy &&
2817
0
       !Curl_checkheaders(data, STRCONST("Proxy-Connection")) &&
2818
0
       !Curl_checkProxyheaders(data, conn, STRCONST("Proxy-Connection")))
2819
0
      result = curlx_dyn_add(req, "Proxy-Connection: Keep-Alive\r\n");
2820
1.94k
    break;
2821
0
#endif
2822
2823
1.94k
  case H1_HD_TRANSFER_ENCODING:
2824
1.94k
    result = http_req_set_TE(data, req, httpversion);
2825
1.94k
    break;
2826
2827
0
#ifndef CURL_DISABLE_ALTSVC
2828
1.94k
  case H1_HD_ALT_USED:
2829
1.94k
    if(conn->bits.altused && conn->via_peer &&
2830
0
       !Curl_checkheaders(data, STRCONST("Alt-Used")))
2831
0
      result = curlx_dyn_addf(req, "Alt-Used: %s:%u\r\n",
2832
0
                              conn->via_peer->hostname, conn->via_peer->port);
2833
1.94k
    break;
2834
0
#endif
2835
2836
1.94k
  case H1_HD_UPGRADE:
2837
1.94k
    if(!Curl_conn_is_ssl(conn) && (httpversion < 20) &&
2838
0
       (data->state.http_neg.wanted & CURL_HTTP_V2x) &&
2839
0
       data->state.http_neg.h2_upgrade) {
2840
      /* append HTTP2 upgrade magic stuff to the HTTP request if it is not done
2841
         over SSL */
2842
0
      result = Curl_http2_request_upgrade(req, data);
2843
0
    }
2844
1.94k
#ifndef CURL_DISABLE_WEBSOCKETS
2845
1.94k
    if(!result && conn->scheme->protocol & (CURLPROTO_WS | CURLPROTO_WSS))
2846
0
      result = Curl_ws_request(data, req);
2847
1.94k
#endif
2848
1.94k
    break;
2849
2850
1.94k
  case H1_HD_COOKIES:
2851
1.94k
    result = http_cookies(data, req);
2852
1.94k
    break;
2853
2854
1.94k
  case H1_HD_CONDITIONALS:
2855
1.94k
    result = Curl_add_timecondition(data, req);
2856
1.94k
    break;
2857
2858
1.94k
  case H1_HD_CUSTOM:
2859
1.94k
    result = Curl_add_custom_headers(data, httpversion, req);
2860
1.94k
    break;
2861
2862
1.94k
  case H1_HD_CONTENT:
2863
1.94k
    result = http_add_content_hds(data, req, httpversion, httpreq);
2864
1.94k
    break;
2865
2866
1.94k
  case H1_HD_CONNECTION: {
2867
1.94k
    result = http_add_connection_hd(data, req);
2868
1.94k
    break;
2869
0
  }
2870
2871
1.94k
  case H1_HD_LAST:
2872
1.94k
    result = curlx_dyn_addn(req, STRCONST("\r\n"));
2873
1.94k
    break;
2874
38.9k
  }
2875
38.9k
  return result;
2876
38.9k
}
2877
2878
/*
2879
 * Curl_http() gets called from the generic multi_do() function when an HTTP
2880
 * request is to be performed. This creates and sends a properly constructed
2881
 * HTTP request.
2882
 */
2883
CURLcode Curl_http(struct Curl_easy *data, bool *done)
2884
1.95k
{
2885
1.95k
  CURLcode result = CURLE_OK;
2886
1.95k
  Curl_HttpReq httpreq;
2887
1.95k
  const char *method;
2888
1.95k
  struct dynbuf req;
2889
1.95k
  unsigned char httpversion;
2890
1.95k
  size_t hd_id;
2891
2892
  /* Always consider the DO phase done after this function call, even if there
2893
     may be parts of the request that are not yet sent, since we can deal with
2894
     the rest of the request in the PERFORM phase. */
2895
1.95k
  *done = TRUE;
2896
  /* initialize a dynamic send-buffer */
2897
1.95k
  curlx_dyn_init(&req, DYN_HTTP_REQUEST);
2898
  /* make sure the header buffer is reset - if there are leftovers from a
2899
     previous transfer */
2900
1.95k
  curlx_dyn_reset(&data->state.headerb);
2901
1.95k
  data->state.maybe_folded = FALSE;
2902
1.95k
  data->state.leading_unfold = FALSE;
2903
2904
  /* Add collecting of headers written to client. For a new connection,
2905
   * we might have done that already, but reuse
2906
   * or multiplex needs it here as well. */
2907
1.95k
  result = Curl_headers_init(data);
2908
1.95k
  if(result)
2909
0
    goto out;
2910
2911
1.95k
  data->state.http_hd_te = FALSE;
2912
1.95k
  data->state.http_hd_upgrade = FALSE;
2913
1.95k
  data->state.http_hd_h2_settings = FALSE;
2914
2915
  /* what kind of request do we need to send? */
2916
1.95k
  Curl_http_method(data, &method, &httpreq);
2917
2918
  /* select host to send */
2919
1.95k
  result = http_set_aptr_host(data);
2920
  /* setup the authentication headers, how that method and host are known */
2921
1.95k
  if(!result)
2922
1.95k
    result = Curl_http_output_auth(data, data->conn, httpreq, method,
2923
1.95k
                                   data->state.up.path,
2924
1.95k
                                   data->state.up.query, FALSE);
2925
  /* Setup input reader, resume information and ranges */
2926
1.95k
  if(!result)
2927
1.94k
    result = set_reader(data, httpreq);
2928
1.95k
  if(!result)
2929
1.94k
    result = http_resume(data, httpreq);
2930
1.95k
  if(!result)
2931
1.94k
    result = http_range(data, httpreq);
2932
1.95k
  if(result)
2933
12
    goto out;
2934
2935
1.94k
  httpversion = http_request_version(data);
2936
  /* Add request line and all headers to `req` */
2937
40.8k
  for(hd_id = 0; hd_id <= H1_HD_LAST; ++hd_id) {
2938
38.9k
    result = http_add_hd(data, &req, (http_hd_t)hd_id,
2939
38.9k
                         httpversion, method, FALSE, httpreq);
2940
38.9k
    if(result)
2941
0
      goto out;
2942
38.9k
  }
2943
2944
  /* setup variables for the upcoming transfer and send */
2945
1.94k
  Curl_xfer_setup_sendrecv(data, -1);
2946
1.94k
  result = Curl_req_send(data, &req, httpversion);
2947
2948
1.94k
  if((httpversion >= 20) && data->req.upload_chunky)
2949
    /* upload_chunky was set above to set up the request in a chunky fashion,
2950
       but is disabled here again to avoid that the chunked encoded version is
2951
       actually used when sending the request body over h2 */
2952
0
    data->req.upload_chunky = FALSE;
2953
2954
1.95k
out:
2955
1.95k
  if(result == CURLE_TOO_LARGE)
2956
0
    failf(data, "HTTP request too large");
2957
2958
1.95k
  curlx_dyn_free(&req);
2959
1.95k
  return result;
2960
1.94k
}
2961
2962
typedef enum {
2963
  STATUS_UNKNOWN, /* not enough data to tell yet */
2964
  STATUS_DONE, /* a status line was read */
2965
  STATUS_BAD /* not a status line */
2966
} statusline;
2967
2968
/* Check a string for a prefix. Check no more than 'len' bytes */
2969
static bool checkprefixmax(const char *prefix, size_t plen,
2970
                           const char *buffer, size_t blen)
2971
0
{
2972
0
  size_t ch = CURLMIN(plen, blen);
2973
0
  return curl_strnequal(prefix, buffer, ch);
2974
0
}
2975
2976
/*
2977
 * checkhttpprefix()
2978
 *
2979
 * Returns TRUE if member of the list matches prefix of string
2980
 */
2981
static statusline checkhttpprefix(struct Curl_easy *data,
2982
                                  const char *s, size_t len)
2983
0
{
2984
0
  statusline rc = STATUS_BAD;
2985
0
  statusline onmatch = len >= 5 ? STATUS_DONE : STATUS_UNKNOWN;
2986
0
  size_t i;
2987
2988
0
  for(i = 0; i < Curl_frzn_strs_count(data->set.a.http200aliases); ++i) {
2989
0
    struct Curl_str *alias = Curl_frzn_strs_get(data->set.a.http200aliases, i);
2990
0
    if(alias && checkprefixmax(alias->str, alias->len, s, len)) {
2991
0
      rc = onmatch;
2992
0
      break;
2993
0
    }
2994
0
  }
2995
2996
0
  if((rc != STATUS_DONE) && checkprefixmax(STRCONST("HTTP/"), s, len))
2997
0
    rc = onmatch;
2998
2999
0
  return rc;
3000
0
}
3001
3002
#ifndef CURL_DISABLE_RTSP
3003
static statusline checkrtspprefix(struct Curl_easy *data,
3004
                                  const char *s, size_t len)
3005
0
{
3006
0
  statusline status = STATUS_BAD;
3007
0
  statusline onmatch = len >= 5 ? STATUS_DONE : STATUS_UNKNOWN;
3008
0
  (void)data;
3009
0
  if(checkprefixmax(STRCONST("RTSP/"), s, len))
3010
0
    status = onmatch;
3011
3012
0
  return status;
3013
0
}
3014
#endif /* CURL_DISABLE_RTSP */
3015
3016
static statusline checkprotoprefix(struct Curl_easy *data,
3017
                                   struct connectdata *conn,
3018
                                   const char *s, size_t len)
3019
0
{
3020
0
#ifndef CURL_DISABLE_RTSP
3021
0
  if(conn->scheme->protocol & CURLPROTO_RTSP)
3022
0
    return checkrtspprefix(data, s, len);
3023
#else
3024
  (void)conn;
3025
#endif /* CURL_DISABLE_RTSP */
3026
3027
0
  return checkhttpprefix(data, s, len);
3028
0
}
3029
3030
/* HTTP header has field name `n` (a string constant) */
3031
#define HD_IS(hd, hdlen, n) \
3032
22
  (((hdlen) >= (sizeof(n) - 1)) && curl_strnequal(n, hd, sizeof(n) - 1))
3033
3034
#define HD_VAL(hd, hdlen, n) \
3035
99
  ((((hdlen) >= (sizeof(n) - 1)) && (hd) && \
3036
99
    curl_strnequal(n, hd, sizeof(n) - 1)) ? ((hd) + (sizeof(n) - 1)) : NULL)
3037
3038
/* HTTP header has field name `n` (a string constant) and contains `v`
3039
 * (a string constant) in its value(s) */
3040
#define HD_IS_AND_SAYS(hd, hdlen, n, v) \
3041
0
  (HD_IS(hd, hdlen, n) && \
3042
0
   ((hdlen) > ((sizeof(n) - 1) + (sizeof(v) - 1))) && \
3043
0
   Curl_compareheader(hd, STRCONST(n), STRCONST(v)))
3044
3045
/*
3046
 * http_header_a() parses a single response header starting with A.
3047
 */
3048
static CURLcode http_header_a(struct Curl_easy *data,
3049
                              const char *hd, size_t hdlen)
3050
57
{
3051
57
#ifndef CURL_DISABLE_ALTSVC
3052
57
  const char *v;
3053
57
  v = (data->asi &&
3054
57
       (Curl_xfer_is_secure(data) ||
3055
0
#ifdef DEBUGBUILD
3056
        /* allow debug builds to circumvent the HTTPS restriction */
3057
0
        getenv("CURL_ALTSVC_HTTP")
3058
#else
3059
        0
3060
#endif
3061
57
         )) ? HD_VAL(hd, hdlen, "Alt-Svc:") : NULL;
3062
57
  if(v) {
3063
    /* the ALPN of the current request */
3064
0
    struct SingleRequest *k = &data->req;
3065
0
    enum alpnid id = (k->httpversion == 30) ? ALPN_h3 :
3066
0
      (k->httpversion == 20) ? ALPN_h2 : ALPN_h1;
3067
0
    return Curl_altsvc_parse(data, data->asi, v, data->state.origin, id);
3068
0
  }
3069
#else
3070
  (void)data;
3071
  (void)hd;
3072
  (void)hdlen;
3073
#endif
3074
57
  return CURLE_OK;
3075
57
}
3076
3077
/*
3078
 * http_header_c() parses a single response header starting with C.
3079
 */
3080
static CURLcode http_header_c(struct Curl_easy *data,
3081
                              const char *hd, size_t hdlen)
3082
24
{
3083
24
  struct connectdata *conn = data->conn;
3084
24
  struct SingleRequest *k = &data->req;
3085
24
  const char *v;
3086
3087
  /* Check for Content-Length: header lines to get size. Browsers insist we
3088
     should accept multiple Content-Length headers and that a comma separated
3089
     list also is fine and then we should accept them all as long as they are
3090
     the same value. Different values trigger error.
3091
   */
3092
24
  v = (!k->http_bodyless && !data->set.ignorecl && !k->ignore_cl) ?
3093
24
    HD_VAL(hd, hdlen, "Content-Length:") : NULL;
3094
24
  if(v) {
3095
0
    do {
3096
0
      curl_off_t contentlength;
3097
0
      int offt = curlx_str_numblanks(&v, &contentlength);
3098
3099
0
      if(offt == STRE_OVERFLOW) {
3100
        /* out of range */
3101
0
        if(data->set.max_filesize) {
3102
0
          failf(data, "Maximum file size exceeded");
3103
0
          return CURLE_FILESIZE_EXCEEDED;
3104
0
        }
3105
0
        streamclose(conn);
3106
0
        infof(data, "Overflow Content-Length: value");
3107
0
        return CURLE_OK;
3108
0
      }
3109
0
      else {
3110
0
        if((offt == STRE_OK) &&
3111
0
           ((k->size == -1) || /* not set to something before */
3112
0
            (k->size == contentlength))) { /* or the same value */
3113
3114
0
          k->size = contentlength;
3115
0
          curlx_str_passblanks(&v);
3116
3117
          /* on a comma, loop and get the next instead */
3118
0
          if(!curlx_str_single(&v, ','))
3119
0
            continue;
3120
3121
0
          if(!curlx_str_newline(&v)) {
3122
0
            k->maxdownload = k->size;
3123
0
            return CURLE_OK;
3124
0
          }
3125
0
        }
3126
        /* negative, different value or rubbish - bad HTTP */
3127
0
        failf(data, "Invalid Content-Length: value");
3128
0
        return CURLE_WEIRD_SERVER_REPLY;
3129
0
      }
3130
0
    } while(1);
3131
0
  }
3132
24
  v = (!k->http_bodyless && CURL_EASY_STR(data, STRING_ENCODING)) ?
3133
24
    HD_VAL(hd, hdlen, "Content-Encoding:") : NULL;
3134
24
  if(v) {
3135
    /*
3136
     * Process Content-Encoding. Look for the values: identity, gzip, deflate,
3137
     * compress, x-gzip and x-compress. x-gzip and x-compress are the same as
3138
     * gzip and compress. (Sec 3.5 RFC 2616). zlib cannot handle compress.
3139
     * Errors are handled further down when the response body is processed
3140
     */
3141
0
    return Curl_build_unencoding_stack(data, v, FALSE);
3142
0
  }
3143
  /* check for Content-Type: header lines to get the MIME-type */
3144
24
  v = HD_VAL(hd, hdlen, "Content-Type:");
3145
24
  if(v) {
3146
18
    char *contenttype = Curl_copy_header_value(hd);
3147
18
    if(!contenttype)
3148
0
      return CURLE_OUT_OF_MEMORY;
3149
18
    if(!*contenttype)
3150
      /* ignore empty data */
3151
13
      curlx_free(contenttype);
3152
5
    else {
3153
5
      curlx_free(data->info.contenttype);
3154
5
      data->info.contenttype = contenttype;
3155
5
    }
3156
18
    return CURLE_OK;
3157
18
  }
3158
6
  if((k->httpversion < 20) &&
3159
0
     HD_IS_AND_SAYS(hd, hdlen, "Connection:", "close")) {
3160
    /*
3161
     * [RFC 2616, section 8.1.2.1]
3162
     * "Connection: close" is HTTP/1.1 language and means that
3163
     * the connection will close when this request has been
3164
     * served.
3165
     */
3166
0
    connclose(conn);
3167
0
    return CURLE_OK;
3168
0
  }
3169
6
  if((k->httpversion == 10) &&
3170
0
     HD_IS_AND_SAYS(hd, hdlen, "Connection:", "keep-alive")) {
3171
    /*
3172
     * An HTTP/1.0 reply with the 'Connection: keep-alive' line
3173
     * tells us the connection will be kept alive for our
3174
     * pleasure. Default action for 1.0 is to close.
3175
     *
3176
     * [RFC2068, section 19.7.1] */
3177
0
    connkeep(conn);
3178
0
    infof(data, "HTTP/1.0 connection set to keep alive");
3179
0
    return CURLE_OK;
3180
0
  }
3181
6
  v = !k->http_bodyless ? HD_VAL(hd, hdlen, "Content-Range:") : NULL;
3182
6
  if(v) {
3183
    /* Content-Range: bytes [num]-
3184
       Content-Range: bytes: [num]-
3185
       Content-Range: [num]-
3186
       Content-Range: [asterisk]/[total]
3187
3188
       The second format was added since Sun's webserver
3189
       JavaWebServer/1.1.1 obviously sends the header this way!
3190
       The third added since some servers use that!
3191
       The fourth means the requested range was unsatisfied.
3192
     */
3193
3194
0
    const char *ptr = v;
3195
3196
    /* Move forward until first digit or asterisk */
3197
0
    while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
3198
0
      ptr++;
3199
3200
    /* if it truly stopped on a digit */
3201
0
    if(ISDIGIT(*ptr)) {
3202
0
      if(!curlx_str_number(&ptr, &k->offset, CURL_OFF_T_MAX) &&
3203
0
         (data->state.resume_from == k->offset))
3204
        /* we asked for a resume and we got it */
3205
0
        k->content_range = TRUE;
3206
0
    }
3207
0
    else if(*ptr == '*' && ptr[1] == '/' && k->httpcode == 416 &&
3208
0
            data->state.resume_from && data->state.httpreq == HTTPREQ_GET) {
3209
0
      curl_off_t total;
3210
0
      ptr += 2;
3211
0
      if(!curlx_str_number(&ptr, &total, CURL_OFF_T_MAX)) {
3212
0
        while(ISBLANK(*ptr))
3213
0
          ptr++;
3214
0
        if((*ptr == '\r' || *ptr == '\n' || !*ptr) &&
3215
0
           total != data->state.resume_from) {
3216
0
          failf(data, "Cannot resume: remote file size differs from offset");
3217
0
          return CURLE_RANGE_ERROR;
3218
0
        }
3219
0
      }
3220
0
    }
3221
0
    else if(k->httpcode < 300)
3222
0
      data->state.resume_from = 0; /* get everything */
3223
0
  }
3224
6
  return CURLE_OK;
3225
6
}
3226
3227
/*
3228
 * http_header_l() parses a single response header starting with L.
3229
 */
3230
static CURLcode http_header_l(struct Curl_easy *data,
3231
                              const char *hd, size_t hdlen)
3232
11
{
3233
11
  struct connectdata *conn = data->conn;
3234
11
  struct SingleRequest *k = &data->req;
3235
11
  const char *v = (!k->http_bodyless &&
3236
3
                   (data->set.timecondition || data->set.get_filetime)) ?
3237
11
    HD_VAL(hd, hdlen, "Last-Modified:") : NULL;
3238
11
  if(v) {
3239
0
    if(Curl_getdate_capped(v, &k->timeofdoc))
3240
0
      k->timeofdoc = 0;
3241
0
    if(data->set.get_filetime)
3242
0
      data->info.filetime = k->timeofdoc;
3243
0
    return CURLE_OK;
3244
0
  }
3245
11
  if(HD_IS(hd, hdlen, "Location:") && (k->httpcode/100 >= 2)) {
3246
    /* this is the URL that the server advises us to use instead */
3247
0
    char *location = Curl_copy_header_value(hd);
3248
0
    if(!location)
3249
0
      return CURLE_OUT_OF_MEMORY;
3250
0
    if(!*location ||
3251
0
       (data->req.location && !strcmp(data->req.location, location))) {
3252
      /* ignore empty header, or exact repeat of a previous one */
3253
0
      curlx_free(location);
3254
0
      return CURLE_OK;
3255
0
    }
3256
0
    else {
3257
      /* has value and is not an exact repeat */
3258
0
      if(data->req.location) {
3259
0
        failf(data, "Multiple Location headers");
3260
0
        curlx_free(location);
3261
0
        return CURLE_WEIRD_SERVER_REPLY;
3262
0
      }
3263
0
      data->req.location = location;
3264
3265
0
      if(data->set.http_follow_mode && (k->httpcode/100 == 3)) {
3266
0
        CURLcode result;
3267
0
        DEBUGASSERT(!data->req.newurl);
3268
0
        data->req.newurl = curlx_strdup(data->req.location); /* clone */
3269
0
        if(!data->req.newurl)
3270
0
          return CURLE_OUT_OF_MEMORY;
3271
3272
        /* some cases of POST and PUT etc needs to rewind the data
3273
           stream at this point */
3274
0
        result = http_perhapsrewind(data, conn);
3275
0
        if(result)
3276
0
          return result;
3277
3278
        /* mark the next request as a followed location: */
3279
0
        data->state.this_is_a_follow = TRUE;
3280
0
      }
3281
0
    }
3282
0
  }
3283
11
  return CURLE_OK;
3284
11
}
3285
3286
/*
3287
 * http_header_p() parses a single response header starting with P.
3288
 */
3289
static CURLcode http_header_p(struct Curl_easy *data,
3290
                              const char *hd, size_t hdlen)
3291
0
{
3292
0
  struct SingleRequest *k = &data->req;
3293
3294
0
#ifndef CURL_DISABLE_PROXY
3295
0
  const char *v = HD_VAL(hd, hdlen, "Proxy-Connection:");
3296
0
  if(v) {
3297
0
    struct connectdata *conn = data->conn;
3298
0
    if((k->httpversion == 10) && conn->http_proxy.peer &&
3299
0
       HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "keep-alive")) {
3300
      /*
3301
       * When an HTTP/1.0 reply comes when using a proxy, the
3302
       * 'Proxy-Connection: keep-alive' line tells us the
3303
       * connection will be kept alive for our pleasure.
3304
       * Default action for 1.0 is to close.
3305
       */
3306
0
      connkeep(conn); /* do not close */
3307
0
      infof(data, "HTTP/1.0 proxy connection set to keep alive");
3308
0
    }
3309
0
    else if((k->httpversion == 11) && conn->http_proxy.peer &&
3310
0
            HD_IS_AND_SAYS(hd, hdlen, "Proxy-Connection:", "close")) {
3311
      /*
3312
       * We get an HTTP/1.1 response from a proxy and it says it will
3313
       * close down after this transfer.
3314
       */
3315
0
      connclose(conn);
3316
0
      infof(data, "HTTP/1.1 proxy connection set close");
3317
0
    }
3318
0
    return CURLE_OK;
3319
0
  }
3320
0
#endif
3321
0
  if((407 == k->httpcode) && HD_IS(hd, hdlen, "Proxy-authenticate:")) {
3322
0
    char *auth;
3323
0
    CURLcode result;
3324
0
#ifndef CURL_DISABLE_PROXY
3325
0
    if(!data->conn->bits.origin_is_proxy)
3326
      /* this response is not from a forward proxy, not for us */
3327
0
      return CURLE_OK;
3328
0
#endif
3329
0
    auth = Curl_copy_header_value(hd);
3330
0
    result = auth ? CURLE_OK : CURLE_OUT_OF_MEMORY;
3331
0
    if(!result) {
3332
0
      result = Curl_http_input_auth(data, TRUE, auth);
3333
0
      curlx_free(auth);
3334
0
    }
3335
0
    return result;
3336
0
  }
3337
#ifdef USE_SPNEGO
3338
  if(HD_IS(hd, hdlen, "Persistent-Auth:")) {
3339
    struct connectdata *conn = data->conn;
3340
    struct negotiatedata *negdata = Curl_auth_nego_get(conn, FALSE);
3341
    struct auth *authp = &data->state.authhost;
3342
    if(!negdata)
3343
      return CURLE_OUT_OF_MEMORY;
3344
    if(authp->picked == CURLAUTH_NEGOTIATE) {
3345
      char *persistentauth = Curl_copy_header_value(hd);
3346
      if(!persistentauth)
3347
        return CURLE_OUT_OF_MEMORY;
3348
      negdata->noauthpersist = !!checkprefix("false", persistentauth);
3349
      negdata->havenoauthpersist = TRUE;
3350
      infof(data, "Negotiate: noauthpersist -> %d, header part: %s",
3351
            negdata->noauthpersist, persistentauth);
3352
      curlx_free(persistentauth);
3353
    }
3354
  }
3355
#endif
3356
0
  return CURLE_OK;
3357
0
}
3358
3359
/*
3360
 * http_header_r() parses a single response header starting with R.
3361
 */
3362
static CURLcode http_header_r(struct Curl_easy *data,
3363
                              const char *hd, size_t hdlen)
3364
0
{
3365
0
  const char *v = HD_VAL(hd, hdlen, "Retry-After:");
3366
0
  if(v) {
3367
    /* Retry-After = HTTP-date / delay-seconds */
3368
0
    curl_off_t retry_after = 0; /* zero for unknown or "now" */
3369
0
    time_t date = 0;
3370
0
    curlx_str_passblanks(&v);
3371
3372
    /* try it as a date first, because a date can otherwise start with and
3373
       get treated as a number */
3374
0
    if(!Curl_getdate_capped(v, &date)) {
3375
0
      time_t current = time(NULL);
3376
0
      if(date >= current)
3377
        /* convert date to number of seconds into the future */
3378
0
        retry_after = date - current;
3379
0
    }
3380
0
    else
3381
      /* Try it as a decimal number, ignore errors */
3382
0
      (void)curlx_str_number(&v, &retry_after, CURL_OFF_T_MAX);
3383
    /* limit to 6 hours max. this is not documented so that it can be changed
3384
       in the future if necessary. */
3385
0
    if(retry_after > 21600)
3386
0
      retry_after = 21600;
3387
0
    data->info.retry_after = retry_after;
3388
0
  }
3389
0
  return CURLE_OK;
3390
0
}
3391
3392
/*
3393
 * http_header_s() parses a single response header starting with S.
3394
 */
3395
static CURLcode http_header_s(struct Curl_easy *data,
3396
                              const char *hd, size_t hdlen)
3397
0
{
3398
0
#if !defined(CURL_DISABLE_COOKIES) || !defined(CURL_DISABLE_HSTS)
3399
0
  const char *v;
3400
#else
3401
  (void)data;
3402
  (void)hd;
3403
  (void)hdlen;
3404
#endif
3405
3406
0
#ifndef CURL_DISABLE_COOKIES
3407
  /* Ignore Set-Cookie on 1xx, same as Location. A 103 can otherwise
3408
     store a cookie the final response never sent. */
3409
0
  v = (data->cookies && data->state.cookie_engine &&
3410
0
       (data->req.httpcode/100 >= 2)) ?
3411
0
    HD_VAL(hd, hdlen, "Set-Cookie:") : NULL;
3412
0
  if(v) {
3413
    /* If there is a custom-set Host: name, use it here, or else use
3414
     * real peer hostname. */
3415
0
    const char *host = data->req.cookiehost ?
3416
0
      data->req.cookiehost : data->state.origin->hostname;
3417
0
    const unsigned char secure_context =
3418
0
      Curl_secure_context(data, host, strlen(host)) ? COOKIE_SECURE : 0;
3419
0
    CURLcode result;
3420
0
    Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
3421
0
    result = Curl_cookie_add(data, data->cookies, v, host,
3422
0
                             data->state.up.path,
3423
0
                             COOKIE_HTTPHEADER | secure_context);
3424
0
    Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
3425
0
    return result;
3426
0
  }
3427
0
#endif
3428
0
#ifndef CURL_DISABLE_HSTS
3429
  /* If enabled, the header is incoming and this is over HTTPS */
3430
0
  v = (data->hsts &&
3431
0
       (Curl_xfer_is_secure(data) ||
3432
0
#ifdef DEBUGBUILD
3433
        /* allow debug builds to circumvent the HTTPS restriction */
3434
0
        getenv("CURL_HSTS_HTTP")
3435
#else
3436
        0
3437
#endif
3438
0
         )
3439
0
    ) ? HD_VAL(hd, hdlen, "Strict-Transport-Security:") : NULL;
3440
0
  if(v) {
3441
0
    CURLcode result = Curl_hsts_parse(
3442
0
      data->hsts, data->state.origin->hostname, v);
3443
0
    if(result) {
3444
0
      if(result == CURLE_OUT_OF_MEMORY)
3445
0
        return result;
3446
0
      infof(data, "Illegal STS header skipped");
3447
0
    }
3448
0
#ifdef DEBUGBUILD
3449
0
    else
3450
0
      infof(data, "Parsed STS header fine (%zu entries)",
3451
0
            Curl_llist_count(&data->hsts->list));
3452
0
#endif
3453
0
  }
3454
0
#endif
3455
3456
0
  return CURLE_OK;
3457
0
}
3458
3459
/*
3460
 * http_header_t() parses a single response header starting with T.
3461
 */
3462
static CURLcode http_header_t(struct Curl_easy *data,
3463
                              const char *hd, size_t hdlen)
3464
7
{
3465
7
  struct connectdata *conn = data->conn;
3466
7
  struct SingleRequest *k = &data->req;
3467
3468
  /* RFC 9112, ch. 6.1
3469
   * "Transfer-Encoding MAY be sent in a response to a HEAD request or
3470
   *  in a 304 (Not Modified) response (Section 15.4.5 of [HTTP]) to a
3471
   *  GET request, neither of which includes a message body, to indicate
3472
   *  that the origin server would have applied a transfer coding to the
3473
   *  message body if the request had been an unconditional GET."
3474
   *
3475
   * Read: in these cases the 'Transfer-Encoding' does not apply
3476
   * to any data following the response headers. Do not add any decoders.
3477
   */
3478
7
  const char *v = (!k->http_bodyless &&
3479
3
                   (data->state.httpreq != HTTPREQ_HEAD) &&
3480
3
                   (k->httpcode != 304)) ?
3481
7
    HD_VAL(hd, hdlen, "Transfer-Encoding:") : NULL;
3482
7
  if(v) {
3483
    /* One or more encodings. We check for chunked and/or a compression
3484
       algorithm. */
3485
0
    CURLcode result = Curl_build_unencoding_stack(data, v, TRUE);
3486
0
    if(result)
3487
0
      return result;
3488
0
    if(!k->chunk) {
3489
      /* if this is not chunked, only close can signal the end of this
3490
       * transfer as Content-Length is said not to be trusted for
3491
       * transfer-encoding! */
3492
0
      CURL_TRC_M(data, "HTTP/1.1 transfer-encoding without chunks");
3493
0
      connclose(conn);
3494
0
      k->ignore_cl = TRUE;
3495
0
    }
3496
0
    return CURLE_OK;
3497
0
  }
3498
7
  v = HD_VAL(hd, hdlen, "Trailer:");
3499
7
  if(v) {
3500
0
    data->req.resp_trailer = TRUE;
3501
0
    return CURLE_OK;
3502
0
  }
3503
7
  return CURLE_OK;
3504
7
}
3505
3506
/*
3507
 * http_header_w() parses a single response header starting with W.
3508
 */
3509
static CURLcode http_header_w(struct Curl_easy *data,
3510
                              const char *hd, size_t hdlen)
3511
1
{
3512
1
  struct SingleRequest *k = &data->req;
3513
1
  CURLcode result = CURLE_OK;
3514
3515
1
  if((401 == k->httpcode) && HD_IS(hd, hdlen, "WWW-Authenticate:")) {
3516
0
    char *auth = Curl_copy_header_value(hd);
3517
0
    if(!auth)
3518
0
      result = CURLE_OUT_OF_MEMORY;
3519
0
    else {
3520
0
      result = Curl_http_input_auth(data, FALSE, auth);
3521
0
      curlx_free(auth);
3522
0
    }
3523
0
  }
3524
1
  return result;
3525
1
}
3526
3527
/*
3528
 * http_header() parses a single response header.
3529
 */
3530
static CURLcode http_header(struct Curl_easy *data,
3531
                            const char *hd, size_t hdlen)
3532
2.14k
{
3533
2.14k
  CURLcode result = CURLE_OK;
3534
3535
2.14k
  switch(hd[0]) {
3536
57
  case 'a':
3537
57
  case 'A':
3538
57
    result = http_header_a(data, hd, hdlen);
3539
57
    break;
3540
24
  case 'c':
3541
24
  case 'C':
3542
24
    result = http_header_c(data, hd, hdlen);
3543
24
    break;
3544
11
  case 'l':
3545
11
  case 'L':
3546
11
    result = http_header_l(data, hd, hdlen);
3547
11
    break;
3548
0
  case 'p':
3549
0
  case 'P':
3550
0
    result = http_header_p(data, hd, hdlen);
3551
0
    break;
3552
0
  case 'r':
3553
0
  case 'R':
3554
0
    result = http_header_r(data, hd, hdlen);
3555
0
    break;
3556
0
  case 's':
3557
0
  case 'S':
3558
0
    result = http_header_s(data, hd, hdlen);
3559
0
    break;
3560
7
  case 't':
3561
7
  case 'T':
3562
7
    result = http_header_t(data, hd, hdlen);
3563
7
    break;
3564
1
  case 'w':
3565
1
  case 'W':
3566
1
    result = http_header_w(data, hd, hdlen);
3567
1
    break;
3568
2.14k
  }
3569
3570
2.14k
  if(!result) {
3571
2.14k
    struct connectdata *conn = data->conn;
3572
2.14k
    if(conn->scheme->protocol & CURLPROTO_RTSP)
3573
0
      result = Curl_rtsp_parseheader(data, hd);
3574
2.14k
  }
3575
2.14k
  return result;
3576
2.14k
}
3577
3578
/*
3579
 * Called after the first HTTP response line (the status line) has been
3580
 * received and parsed.
3581
 */
3582
static CURLcode http_statusline(struct Curl_easy *data,
3583
                                struct connectdata *conn)
3584
1.14k
{
3585
1.14k
  struct SingleRequest *k = &data->req;
3586
3587
1.14k
  switch(k->httpversion) {
3588
0
  case 10:
3589
0
  case 11:
3590
0
#ifdef USE_HTTP2
3591
0
  case 20:
3592
0
#endif
3593
0
#ifdef USE_HTTP3
3594
1.14k
  case 30:
3595
1.14k
#endif
3596
    /* no major version switch mid-connection */
3597
1.14k
    if(k->httpversion_sent &&
3598
1.14k
       (k->httpversion / 10 != k->httpversion_sent / 10)) {
3599
0
      failf(data, "Version mismatch (from HTTP/%d to HTTP/%d)",
3600
0
            k->httpversion_sent / 10, k->httpversion / 10);
3601
0
      return CURLE_WEIRD_SERVER_REPLY;
3602
0
    }
3603
1.14k
    break;
3604
1.14k
  default:
3605
0
    failf(data, "Unsupported HTTP version (%d.%d) in response",
3606
0
          k->httpversion / 10, k->httpversion % 10);
3607
0
    return CURLE_UNSUPPORTED_PROTOCOL;
3608
1.14k
  }
3609
3610
1.14k
  data->info.httpcode = k->httpcode;
3611
1.14k
  data->info.httpversion = k->httpversion;
3612
1.14k
  conn->httpversion_seen = k->httpversion;
3613
3614
1.14k
  if(!data->state.http_neg.rcvd_min ||
3615
266
     data->state.http_neg.rcvd_min > k->httpversion)
3616
    /* store the lowest server version we encounter */
3617
881
    data->state.http_neg.rcvd_min = k->httpversion;
3618
3619
  /*
3620
   * This code executes as part of processing the header. As a
3621
   * result, it is not totally clear how to interpret the
3622
   * response code yet as that depends on what other headers may
3623
   * be present. 401 and 407 may be errors, but may be OK
3624
   * depending on how authentication is working. Other codes
3625
   * are definitely errors, so give up here.
3626
   */
3627
1.14k
  if(data->state.resume_from && data->state.httpreq == HTTPREQ_GET &&
3628
5
     k->httpcode == 416) {
3629
    /* "Requested Range Not Satisfiable", proceed and pretend this is no
3630
       error */
3631
0
    k->ignorebody = TRUE; /* Avoid appending error msg to good data. */
3632
0
  }
3633
3634
1.14k
  if(k->httpversion == 10) {
3635
    /* Default action for HTTP/1.0 must be to close, unless
3636
       we get one of those fancy headers that tell us the
3637
       server keeps it open for us! */
3638
0
    infof(data, "HTTP 1.0, assume close after body");
3639
0
    connclose(conn);
3640
0
  }
3641
3642
1.14k
  k->http_bodyless = k->httpcode >= 100 && k->httpcode < 200;
3643
1.14k
  switch(k->httpcode) {
3644
0
  case 304:
3645
    /* (quote from RFC2616, section 10.3.5): The 304 response
3646
     * MUST NOT contain a message-body, and thus is always
3647
     * terminated by the first empty line after the header
3648
     * fields. */
3649
0
    if(data->set.timecondition)
3650
0
      data->info.timecond = TRUE;
3651
0
    FALLTHROUGH();
3652
0
  case 204:
3653
    /* (quote from RFC2616, section 10.2.5): The server has
3654
     * fulfilled the request but does not need to return an
3655
     * entity-body ... The 204 response MUST NOT include a
3656
     * message-body, and thus is always terminated by the first
3657
     * empty line after the header fields. */
3658
0
    k->size = 0;
3659
0
    k->maxdownload = 0;
3660
0
    k->http_bodyless = TRUE;
3661
0
    break;
3662
1.14k
  default:
3663
1.14k
    break;
3664
1.14k
  }
3665
1.14k
  return CURLE_OK;
3666
1.14k
}
3667
3668
/* Content-Length must be ignored if any Transfer-Encoding is present in the
3669
   response. Refer to RFC 7230 section 3.3.3 and RFC2616 section 4.4. This is
3670
   figured out here after all headers have been received but before the final
3671
   call to the user's header callback, so that a valid content length can be
3672
   retrieved by the user in the final call. */
3673
static CURLcode http_size(struct Curl_easy *data)
3674
629
{
3675
629
  struct SingleRequest *k = &data->req;
3676
629
  if(data->req.ignore_cl || k->chunk) {
3677
0
    k->size = k->maxdownload = -1;
3678
0
  }
3679
629
  else if(k->size != -1) {
3680
0
    if(data->set.max_filesize &&
3681
0
       !k->ignorebody &&
3682
0
       (k->size > data->set.max_filesize)) {
3683
0
      failf(data, "Maximum file size exceeded");
3684
0
      return CURLE_FILESIZE_EXCEEDED;
3685
0
    }
3686
0
    if(k->ignorebody)
3687
0
      infof(data, "setting size while ignoring");
3688
0
    Curl_pgrsSetDownloadSize(data, k->size);
3689
0
    k->maxdownload = k->size;
3690
0
  }
3691
629
  return CURLE_OK;
3692
629
}
3693
3694
CURLcode Curl_verify_header(struct Curl_easy *data,
3695
                            const char *hd, size_t hdlen)
3696
34.7k
{
3697
34.7k
  struct SingleRequest *k = &data->req;
3698
34.7k
  const char *nul = memchr(hd, '\0', hdlen);
3699
34.7k
  const char *cr = memchr(hd, '\r', nul ? (size_t)(nul - hd) : hdlen);
3700
  /* CR may only precede the LF, nothing else */
3701
34.7k
  if(cr && ((size_t)(cr - hd) < hdlen - 2)) {
3702
4
    failf(data, "Carriage return found in header");
3703
4
    return CURLE_WEIRD_SERVER_REPLY;
3704
4
  }
3705
34.7k
  if(nul) {
3706
    /* this is bad, bail out */
3707
18
    failf(data, "NUL byte in header");
3708
18
    return CURLE_WEIRD_SERVER_REPLY;
3709
18
  }
3710
34.7k
  if(k->headerline < 2)
3711
    /* the first "header" is the status-line and it has no colon */
3712
33.7k
    return CURLE_OK;
3713
997
  if(((hd[0] == ' ') || (hd[0] == '\t')) && k->headerline > 2)
3714
    /* line folding, cannot happen on line 2 */
3715
0
    ;
3716
997
  else if(!memchr(hd, ':', hdlen)) {
3717
    /* this is bad, bail out */
3718
0
    failf(data, "Header without colon");
3719
0
    return CURLE_WEIRD_SERVER_REPLY;
3720
0
  }
3721
997
  return CURLE_OK;
3722
997
}
3723
3724
CURLcode Curl_bump_headersize(struct Curl_easy *data,
3725
                              size_t delta,
3726
                              bool connect_only)
3727
36.0k
{
3728
36.0k
  size_t bad = 0;
3729
36.0k
  unsigned int max = MAX_HTTP_RESP_HEADER_SIZE;
3730
36.0k
  if(delta < MAX_HTTP_RESP_HEADER_SIZE) {
3731
36.0k
    data->info.header_size += (unsigned int)delta;
3732
36.0k
    data->req.allheadercount += (unsigned int)delta;
3733
36.0k
    if(!connect_only)
3734
3.43k
      data->req.headerbytecount += (unsigned int)delta;
3735
36.0k
    if(data->req.allheadercount > max)
3736
0
      bad = data->req.allheadercount;
3737
36.0k
    else if(data->info.header_size > (max * 20)) {
3738
0
      bad = data->info.header_size;
3739
0
      max *= 20;
3740
0
    }
3741
36.0k
  }
3742
0
  else
3743
0
    bad = data->req.allheadercount + delta;
3744
36.0k
  if(bad) {
3745
0
    failf(data, "Too large response headers: %zu > %u", bad, max);
3746
0
    return CURLE_RECV_ERROR;
3747
0
  }
3748
36.0k
  return CURLE_OK;
3749
36.0k
}
3750
3751
/*
3752
 * Handle a 101 Switching Protocols response. Performs the actual protocol
3753
 * upgrade to HTTP/2 or WebSocket based on what was requested.
3754
 */
3755
static CURLcode http_on_101_upgrade(struct Curl_easy *data,
3756
                                    const char *buf, size_t blen,
3757
                                    size_t *pconsumed,
3758
                                    bool *conn_changed)
3759
0
{
3760
0
  struct connectdata *conn = data->conn;
3761
0
  struct SingleRequest *k = &data->req;
3762
3763
#if !defined(USE_NGHTTP2) && defined(CURL_DISABLE_WEBSOCKETS)
3764
  (void)buf;
3765
  (void)blen;
3766
  (void)pconsumed;
3767
#else
3768
0
  CURLcode result;
3769
0
  int upgr101_requested = k->upgr101;
3770
0
#endif
3771
3772
0
  if(k->httpversion_sent != 11) {
3773
    /* invalid for other HTTP versions */
3774
0
    failf(data, "server sent 101 response while not talking HTTP/1.1");
3775
0
    return CURLE_WEIRD_SERVER_REPLY;
3776
0
  }
3777
3778
  /* Whatever the success, upgrade was selected. */
3779
0
  k->upgr101 = UPGR101_RECEIVED;
3780
0
  conn->bits.upgrade_in_progress = FALSE;
3781
0
  *conn_changed = TRUE;
3782
3783
  /* To be fully compliant, we would check the "Upgrade:" response header to
3784
   * mention the protocol we requested. */
3785
0
#ifdef USE_NGHTTP2
3786
0
  if(upgr101_requested == UPGR101_H2) {
3787
    /* Switch to HTTP/2, where we will get more responses. blen bytes in buf
3788
     * are already h2 protocol bytes */
3789
0
    infof(data, "Received 101, Switching to HTTP/2");
3790
0
    result = Curl_http2_upgrade(data, buf, blen);
3791
0
    if(!result)
3792
0
      *pconsumed += blen;
3793
0
    return result;
3794
0
  }
3795
0
#endif
3796
0
#ifndef CURL_DISABLE_WEBSOCKETS
3797
0
  if(upgr101_requested == UPGR101_WS) {
3798
    /* Switch to WebSocket, where we now stream ws frames. blen bytes in buf
3799
     * are already ws protocol bytes */
3800
0
    infof(data, "Received 101, Switching to WebSocket");
3801
0
    result = Curl_ws_accept(data, buf, blen);
3802
0
    if(!result)
3803
0
      *pconsumed += blen; /* ws accept handled the data */
3804
0
    return result;
3805
0
  }
3806
0
#endif
3807
  /* We silently accept this as the final response. What are we switching to
3808
   * if we did not ask for an Upgrade? Maybe the application provided an
3809
   * `Upgrade: xxx` header? */
3810
0
  k->header = FALSE;
3811
0
  return CURLE_OK;
3812
0
}
3813
3814
/*
3815
 * Handle 1xx intermediate HTTP responses. Sets up state for more
3816
 * headers and processes 100-continue and 101 upgrade responses.
3817
 */
3818
static CURLcode http_on_1xx_response(struct Curl_easy *data,
3819
                                     const char *buf, size_t blen,
3820
                                     size_t *pconsumed,
3821
                                     bool *conn_changed)
3822
507
{
3823
507
  struct SingleRequest *k = &data->req;
3824
3825
  /* "A user agent MAY ignore unexpected 1xx status responses."
3826
   * By default, we expect to get more responses after this one. */
3827
507
  k->header = TRUE;
3828
507
  k->headerline = 0; /* restart the header line counter */
3829
3830
507
  switch(k->httpcode) {
3831
9
  case 100:
3832
    /* We have made an HTTP PUT or POST and this is 1.1-lingo that tells us
3833
     * that the server is OK with this and ready to receive the data. */
3834
9
    http_exp100_got100(data);
3835
9
    break;
3836
0
  case 101:
3837
0
    return http_on_101_upgrade(data, buf, blen, pconsumed, conn_changed);
3838
498
  default:
3839
    /* The server may send us other 1xx responses, like informative 103. This
3840
     * has no influence on request processing and we expect to receive a
3841
     * final response eventually. */
3842
498
    break;
3843
507
  }
3844
507
  return CURLE_OK;
3845
507
}
3846
3847
#ifdef USE_SPNEGO
3848
/*
3849
 * Check if SPNEGO authentication negotiation failed due to connection closure
3850
 * (typically on HTTP/1.0 servers).
3851
 */
3852
static void http_check_auth_closure(struct Curl_easy *data,
3853
                                    struct connectdata *conn)
3854
{
3855
  /* At this point we have some idea about the fate of the connection. If we
3856
     are closing the connection it may result auth failure. */
3857
  if(conn->bits.close &&
3858
    (((data->req.httpcode == 401) &&
3859
      (conn->http_negotiate_state == CURL_NEGO_AUTH_RECV)) ||
3860
     ((data->req.httpcode == 407) &&
3861
      (conn->proxy_negotiate_state == CURL_NEGO_AUTH_RECV)))) {
3862
    infof(data, "Connection closure while negotiating auth (HTTP 1.0?)");
3863
    data->state.authproblem = TRUE;
3864
  }
3865
  if((conn->http_negotiate_state == CURL_NEGO_AUTH_DONE) &&
3866
     (data->req.httpcode != 401)) {
3867
    conn->http_negotiate_state = CURL_NEGO_AUTH_SUCC;
3868
  }
3869
  if((conn->proxy_negotiate_state == CURL_NEGO_AUTH_DONE) &&
3870
     (data->req.httpcode != 407)) {
3871
    conn->proxy_negotiate_state = CURL_NEGO_AUTH_SUCC;
3872
  }
3873
}
3874
#else
3875
#define http_check_auth_closure(x, y) /* empty */
3876
#endif
3877
3878
/*
3879
 * Handle an error response (>= 300) received while still sending the
3880
 * request body. Deals with 417 Expectation Failed retries, keep-sending
3881
 * on error, and aborting the send.
3882
 */
3883
static CURLcode http_handle_send_error(struct Curl_easy *data)
3884
38
{
3885
38
  struct connectdata *conn = data->conn;
3886
38
  struct SingleRequest *k = &data->req;
3887
38
  CURLcode result = CURLE_OK;
3888
3889
38
  if(!data->req.authneg && !conn->bits.close &&
3890
38
     !Curl_creader_will_rewind(data)) {
3891
    /*
3892
     * General treatment of errors when about to send data.
3893
     * Including: "417 Expectation Failed", while waiting for
3894
     * 100-continue.
3895
     *
3896
     * The check for close above is done because if something
3897
     * else has already deemed the connection to get closed then
3898
     * something else should have considered the big picture and
3899
     * we avoid this check.
3900
     */
3901
3902
38
    switch(data->state.httpreq) {
3903
0
    case HTTPREQ_PUT:
3904
0
    case HTTPREQ_POST:
3905
0
    case HTTPREQ_POST_FORM:
3906
1
    case HTTPREQ_POST_MIME:
3907
      /* We got an error response. If this happened before the
3908
       * whole request body has been sent we stop sending and
3909
       * mark the connection for closure after we have read the
3910
       * entire response. */
3911
1
      if(!Curl_req_done_sending(data)) {
3912
0
        if((k->httpcode == 417) && http_exp100_is_selected(data)) {
3913
          /* 417 Expectation Failed - try again without the
3914
             Expect header */
3915
0
          if(!k->writebytecount && http_exp100_is_waiting(data)) {
3916
0
            infof(data, "Got HTTP failure 417 while waiting for a 100");
3917
0
          }
3918
0
          else {
3919
0
            infof(data, "Got HTTP failure 417 while sending data");
3920
0
            streamclose(conn);
3921
0
            result = http_perhapsrewind(data, conn);
3922
0
            if(result)
3923
0
              return result;
3924
0
          }
3925
0
          data->state.disableexpect = TRUE;
3926
0
          Curl_req_abort_sending(data);
3927
0
          DEBUGASSERT(!data->req.newurl);
3928
0
          data->req.newurl = Curl_bufref_dup(&data->state.url);
3929
0
          if(!data->req.newurl)
3930
0
            return CURLE_OUT_OF_MEMORY;
3931
0
        }
3932
0
        else if(data->set.http_keep_sending_on_error) {
3933
0
          infof(data, "HTTP error before end of send, keep sending");
3934
0
          http_exp100_send_anyway(data);
3935
0
        }
3936
0
        else {
3937
0
          infof(data, "HTTP error before end of send, stop sending");
3938
0
          streamclose(conn);
3939
0
          result = Curl_req_abort_sending(data);
3940
0
          if(result)
3941
0
            return result;
3942
0
        }
3943
0
      }
3944
1
      break;
3945
3946
37
    default: /* default label present to avoid compiler warnings */
3947
37
      break;
3948
38
    }
3949
38
  }
3950
3951
38
  if(Curl_creader_will_rewind(data) && !Curl_req_done_sending(data)) {
3952
    /* We rewind before next send, continue sending now */
3953
0
    infof(data, "Keep sending data to get tossed away");
3954
0
    CURL_REQ_SET_SEND(data);
3955
0
  }
3956
38
  return result;
3957
38
}
3958
3959
static CURLcode http_on_response(struct Curl_easy *data,
3960
                                 const char *last_hd, size_t last_hd_len,
3961
                                 const char *buf, size_t blen,
3962
                                 size_t *pconsumed)
3963
1.14k
{
3964
1.14k
  struct connectdata *conn = data->conn;
3965
1.14k
  CURLcode result = CURLE_OK;
3966
1.14k
  struct SingleRequest *k = &data->req;
3967
1.14k
  bool conn_changed = FALSE;
3968
3969
1.14k
  (void)buf; /* not used without HTTP2 enabled */
3970
1.14k
  *pconsumed = 0;
3971
3972
1.14k
  if(k->upgr101 == UPGR101_RECEIVED) {
3973
    /* supposedly upgraded to http2 now */
3974
0
    if(data->req.httpversion != 20)
3975
0
      infof(data, "Lying server, not serving HTTP/2");
3976
0
  }
3977
3978
1.14k
  if(k->httpcode < 200 && last_hd) {
3979
    /* Intermediate responses might trigger processing of more responses,
3980
     * write the last header to the client before proceeding. */
3981
507
    result = http_write_header(data, last_hd, last_hd_len);
3982
507
    last_hd = NULL; /* handled it */
3983
507
    if(result)
3984
0
      goto out;
3985
507
  }
3986
3987
1.14k
  if(k->httpcode < 100) {
3988
0
    failf(data, "Unsupported response code in HTTP response");
3989
0
    result = CURLE_UNSUPPORTED_PROTOCOL;
3990
0
    goto out;
3991
0
  }
3992
1.14k
  else if(k->httpcode < 200) {
3993
507
    result = http_on_1xx_response(data, buf, blen, pconsumed, &conn_changed);
3994
507
    goto out;
3995
507
  }
3996
3997
  /* k->httpcode >= 200, final response */
3998
634
  k->header = FALSE;
3999
634
  if(conn->bits.upgrade_in_progress) {
4000
    /* Asked for protocol upgrade, but it was not selected */
4001
0
    conn->bits.upgrade_in_progress = FALSE;
4002
0
    conn_changed = TRUE;
4003
0
  }
4004
4005
634
  if((k->size == -1) && !k->chunk && !conn->bits.close &&
4006
634
     (k->httpversion == 11) &&
4007
0
     !(conn->scheme->protocol & CURLPROTO_RTSP) &&
4008
0
     data->state.httpreq != HTTPREQ_HEAD) {
4009
    /* On HTTP 1.1, when connection is not to get closed, but no
4010
       Content-Length nor Transfer-Encoding chunked have been received,
4011
       according to RFC2616 section 4.4 point 5, we assume that the server
4012
       will close the connection to signal the end of the document. */
4013
0
    infof(data, "no chunk, no close, no size. Assume close to signal end");
4014
0
    streamclose(conn);
4015
0
  }
4016
4017
634
  http_check_auth_closure(data, conn);
4018
4019
634
#ifndef CURL_DISABLE_WEBSOCKETS
4020
  /* All >=200 HTTP status codes are errors when wanting ws */
4021
634
  if(data->req.upgr101 == UPGR101_WS) {
4022
0
    failf(data, "Refused WebSocket upgrade: %d", k->httpcode);
4023
0
    result = CURLE_HTTP_RETURNED_ERROR;
4024
0
    goto out;
4025
0
  }
4026
634
#endif
4027
4028
  /* Check if this response means the transfer errored. */
4029
634
  if(http_should_fail(data, data->req.httpcode)) {
4030
0
    failf(data, "The requested URL returned error: %d",
4031
0
          k->httpcode);
4032
0
    result = CURLE_HTTP_RETURNED_ERROR;
4033
0
    goto out;
4034
0
  }
4035
4036
  /* Curl_http_auth_act() checks what authentication methods that are
4037
   * available and decides which one (if any) to use. It will set 'newurl' if
4038
   * an auth method was picked. */
4039
634
  result = Curl_http_auth_act(data);
4040
634
  if(result)
4041
0
    goto out;
4042
4043
634
  if(k->httpcode >= 300) {
4044
38
    result = http_handle_send_error(data);
4045
38
    if(result)
4046
0
      goto out;
4047
38
  }
4048
4049
  /* final response without error, prepare to receive the body */
4050
634
  result = http_firstwrite(data);
4051
634
  if(result)
4052
5
    goto out;
4053
4054
  /* This is the last response that we get for the current request. Check on
4055
   * the body size and determine if the response is complete. */
4056
629
  result = http_size(data);
4057
629
  if(result)
4058
0
    goto out;
4059
4060
629
#ifndef CURL_DISABLE_RTSP
4061
  /* An RTSP response to any method may carry a body, which is announced
4062
     with Content-Length (RFC 2326 section 12.14). Read it instead of
4063
     treating it as excess data, unless the application asked for no body
4064
     with CURLOPT_NOBODY. */
4065
629
  if((conn->scheme->protocol & CURLPROTO_RTSP) && data->req.no_body &&
4066
0
     !data->set.opt_no_body && (k->size > 0))
4067
0
    data->req.no_body = FALSE;
4068
629
#endif
4069
4070
  /* If we requested a "no body", this is a good time to get
4071
   * out and return home.
4072
   */
4073
629
  if(data->req.no_body)
4074
7
    k->download_done = TRUE;
4075
4076
  /* If max download size is *zero* (nothing) we already have nothing and can
4077
     safely return ok now! For HTTP/2, we would like to call
4078
     http2_handle_stream_close to properly close a stream. In order to do
4079
     this, we keep reading until we close the stream. */
4080
629
  if((k->maxdownload == 0) && (k->httpversion_sent < 20))
4081
0
    k->download_done = TRUE;
4082
4083
1.14k
out:
4084
1.14k
  if(last_hd)
4085
    /* if not written yet, write it now */
4086
634
    result = Curl_1st_fatal(result,
4087
634
                            http_write_header(data, last_hd, last_hd_len));
4088
1.14k
  if(conn_changed)
4089
    /* poke the multi handle to allow pending pipewait to retry */
4090
0
    Curl_multi_connchanged(data->multi);
4091
1.14k
  return result;
4092
629
}
4093
4094
static CURLcode http_rw_hd(struct Curl_easy *data,
4095
                           const char *hd, size_t hdlen,
4096
                           const char *buf_remain, size_t blen,
4097
                           size_t *pconsumed)
4098
3.28k
{
4099
3.28k
  CURLcode result = CURLE_OK;
4100
3.28k
  struct SingleRequest *k = &data->req;
4101
3.28k
  int writetype;
4102
3.28k
  DEBUGASSERT(!hd[hdlen]); /* null-terminated */
4103
4104
3.28k
  *pconsumed = 0;
4105
3.28k
  if((0x0a == *hd) || (0x0d == *hd)) {
4106
    /* Empty header line means end of headers! */
4107
1.14k
    struct dynbuf last_header;
4108
1.14k
    size_t consumed;
4109
4110
1.14k
    if((hdlen != 1 || hd[0] != '\n') &&
4111
1.14k
       (hdlen != 2 || hd[0] != '\r' || hd[1] != '\n')) {
4112
0
      failf(data, "Invalid header termination");
4113
0
      return CURLE_WEIRD_SERVER_REPLY;
4114
0
    }
4115
4116
1.14k
    curlx_dyn_init(&last_header, hdlen + 1);
4117
1.14k
    result = curlx_dyn_addn(&last_header, hd, hdlen);
4118
1.14k
    if(result)
4119
0
      return result;
4120
4121
    /* analyze the response to find out what to do. */
4122
    /* Caveat: we clear anything in the header brigade, because a
4123
     * response might switch HTTP version which may call use recursively.
4124
     * Not nice, but that is currently the way of things. */
4125
1.14k
    curlx_dyn_reset(&data->state.headerb);
4126
1.14k
    result = http_on_response(data, curlx_dyn_ptr(&last_header),
4127
1.14k
                              curlx_dyn_len(&last_header),
4128
1.14k
                              buf_remain, blen, &consumed);
4129
1.14k
    *pconsumed += consumed;
4130
1.14k
    curlx_dyn_free(&last_header);
4131
1.14k
    return result;
4132
1.14k
  }
4133
4134
  /*
4135
   * Checks for special headers coming up.
4136
   */
4137
4138
2.14k
  writetype = CLIENTWRITE_HEADER;
4139
2.14k
  if(!k->headerline++) {
4140
    /* This is the first header, it MUST be the error code line
4141
       or else we consider this to be the body right away! */
4142
1.14k
    bool fine_statusline = FALSE;
4143
4144
1.14k
    k->httpversion = 0; /* Do not know yet */
4145
1.14k
    if(data->conn->scheme->protocol & PROTO_FAMILY_HTTP) {
4146
      /*
4147
       * https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2
4148
       *
4149
       * The response code is always a three-digit number in HTTP as the spec
4150
       * says. We allow any three-digit number here, but we cannot make
4151
       * guarantees on future behaviors since it is not within the protocol.
4152
       */
4153
1.14k
      const char *p = hd;
4154
4155
1.14k
      curlx_str_passblanks(&p);
4156
1.14k
      if(!strncmp(p, "HTTP/", 5)) {
4157
1.14k
        p += 5;
4158
1.14k
        switch(*p) {
4159
0
        case '1':
4160
0
          p++;
4161
0
          if((p[0] == '.') && (p[1] == '0' || p[1] == '1')) {
4162
0
            if(ISBLANK(p[2])) {
4163
0
              k->httpversion = (unsigned char)(10 + (p[1] - '0'));
4164
0
              p += 3;
4165
0
              if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) {
4166
0
                k->httpcode = ((p[0] - '0') * 100) + ((p[1] - '0') * 10) +
4167
0
                  (p[2] - '0');
4168
                /* RFC 9112 requires a single space following the status code,
4169
                   but the browsers do not so let's not insist */
4170
0
                fine_statusline = TRUE;
4171
0
              }
4172
0
            }
4173
0
          }
4174
0
          if(!fine_statusline) {
4175
0
            failf(data, "Unsupported HTTP/1 subversion in response");
4176
0
            return CURLE_UNSUPPORTED_PROTOCOL;
4177
0
          }
4178
0
          break;
4179
0
        case '2':
4180
1.14k
        case '3':
4181
1.14k
          if(!ISBLANK(p[1]))
4182
0
            break;
4183
1.14k
          k->httpversion = (unsigned char)((*p - '0') * 10);
4184
1.14k
          p += 2;
4185
1.14k
          if(ISDIGIT(p[0]) && ISDIGIT(p[1]) && ISDIGIT(p[2])) {
4186
1.14k
            k->httpcode = ((p[0] - '0') * 100) + ((p[1] - '0') * 10) +
4187
1.14k
              (p[2] - '0');
4188
1.14k
            p += 3;
4189
1.14k
            if(!ISBLANK(*p))
4190
0
              break;
4191
1.14k
            fine_statusline = TRUE;
4192
1.14k
          }
4193
1.14k
          break;
4194
1.14k
        default: /* unsupported */
4195
0
          failf(data, "Unsupported HTTP version in response");
4196
0
          return CURLE_UNSUPPORTED_PROTOCOL;
4197
1.14k
        }
4198
1.14k
      }
4199
4200
1.14k
      if(!fine_statusline) {
4201
        /* If user has set option HTTP200ALIASES,
4202
           compare header line against list of aliases */
4203
0
        statusline check = checkhttpprefix(data, hd, hdlen);
4204
0
        if(check == STATUS_DONE) {
4205
0
          fine_statusline = TRUE;
4206
0
          k->httpcode = 200;
4207
0
          k->httpversion = 10;
4208
0
        }
4209
0
      }
4210
1.14k
    }
4211
0
    else if(data->conn->scheme->protocol & CURLPROTO_RTSP) {
4212
0
      const char *p = hd;
4213
0
      struct Curl_str ver;
4214
0
      curl_off_t status;
4215
      /* we set the max string a little excessive to forgive some leading
4216
         spaces */
4217
0
      if(!curlx_str_until(&p, &ver, 32, ' ') &&
4218
0
         !curlx_str_single(&p, ' ') &&
4219
0
         !curlx_str_number(&p, &status, 999)) {
4220
0
        curlx_str_trimblanks(&ver);
4221
0
        if(curlx_str_cmp(&ver, "RTSP/1.0")) {
4222
0
          k->httpcode = (int)status;
4223
0
          fine_statusline = TRUE;
4224
0
          k->httpversion = 11; /* RTSP acts like HTTP 1.1 */
4225
0
        }
4226
0
      }
4227
0
      if(!fine_statusline)
4228
0
        return CURLE_WEIRD_SERVER_REPLY;
4229
0
    }
4230
4231
1.14k
    if(fine_statusline) {
4232
1.14k
      result = http_statusline(data, data->conn);
4233
1.14k
      if(result)
4234
0
        return result;
4235
1.14k
      writetype |= CLIENTWRITE_STATUS;
4236
1.14k
    }
4237
0
    else {
4238
0
      k->header = FALSE;   /* this is not a header line */
4239
0
      return CURLE_WEIRD_SERVER_REPLY;
4240
0
    }
4241
1.14k
  }
4242
4243
2.14k
  result = Curl_verify_header(data, hd, hdlen);
4244
2.14k
  if(result)
4245
0
    return result;
4246
4247
2.14k
  result = http_header(data, hd, hdlen);
4248
2.14k
  if(result)
4249
0
    return result;
4250
4251
  /*
4252
   * Taken in one (more) header. Write it to the client.
4253
   */
4254
2.14k
  Curl_debug(data, CURLINFO_HEADER_IN, hd, hdlen);
4255
4256
2.14k
  if(k->httpcode / 100 == 1)
4257
1.40k
    writetype |= CLIENTWRITE_1XX;
4258
2.14k
  result = Curl_client_write(data, writetype, hd, hdlen);
4259
2.14k
  if(result)
4260
0
    return result;
4261
4262
2.14k
  result = Curl_bump_headersize(data, hdlen, FALSE);
4263
2.14k
  if(result)
4264
0
    return result;
4265
4266
2.14k
  return CURLE_OK;
4267
2.14k
}
4268
4269
/* remove trailing CRLF then all trailing whitespace */
4270
void Curl_http_to_fold(struct dynbuf *bf)
4271
1.50k
{
4272
1.50k
  size_t len = curlx_dyn_len(bf);
4273
1.50k
  const char *hd = curlx_dyn_ptr(bf);
4274
1.50k
  if(len && (hd[len - 1] == '\n'))
4275
1.50k
    len--;
4276
1.50k
  if(len && (hd[len - 1] == '\r'))
4277
273
    len--;
4278
2.96k
  while(len && ISBLANK(hd[len - 1])) /* strip off trailing whitespace */
4279
1.46k
    len--;
4280
1.50k
  curlx_dyn_setlen(bf, len);
4281
1.50k
}
4282
4283
static void unfold_header(struct Curl_easy *data)
4284
0
{
4285
0
  Curl_http_to_fold(&data->state.headerb);
4286
0
  data->state.leading_unfold = TRUE;
4287
0
}
4288
4289
/*
4290
 * Read any HTTP header lines from the server and pass them to the client app.
4291
 */
4292
static CURLcode http_parse_headers(struct Curl_easy *data,
4293
                                   const char *buf, size_t blen,
4294
                                   size_t *pconsumed)
4295
0
{
4296
0
  struct connectdata *conn = data->conn;
4297
0
  CURLcode result = CURLE_OK;
4298
0
  struct SingleRequest *k = &data->req;
4299
0
  const char *end_ptr;
4300
0
  bool leftover_body = FALSE;
4301
4302
  /* we have bytes for the next header, make sure it is not a folded header
4303
     before passing it on */
4304
0
  if(data->state.maybe_folded && blen) {
4305
0
    if(ISBLANK(buf[0])) {
4306
      /* folded, remove the trailing newlines and append the next header */
4307
0
      unfold_header(data);
4308
0
    }
4309
0
    else {
4310
      /* the header data we hold is a complete header, pass it on */
4311
0
      size_t ignore_this;
4312
0
      result = http_rw_hd(data, curlx_dyn_ptr(&data->state.headerb),
4313
0
                          curlx_dyn_len(&data->state.headerb),
4314
0
                          NULL, 0, &ignore_this);
4315
0
      curlx_dyn_reset(&data->state.headerb);
4316
0
      if(result)
4317
0
        return result;
4318
0
    }
4319
0
    data->state.maybe_folded = FALSE;
4320
0
  }
4321
4322
  /* header line within buffer loop */
4323
0
  *pconsumed = 0;
4324
0
  while(blen && k->header) {
4325
0
    size_t consumed;
4326
0
    size_t hlen;
4327
0
    const char *hd;
4328
0
    size_t unfold_len = 0;
4329
4330
0
    if(data->state.leading_unfold) {
4331
      /* immediately after an unfold, keep only a single whitespace */
4332
0
      while(blen && ISBLANK(buf[0])) {
4333
0
        buf++;
4334
0
        blen--;
4335
0
        unfold_len++;
4336
0
      }
4337
0
      if(blen) {
4338
        /* insert a single space */
4339
0
        result = curlx_dyn_addn(&data->state.headerb, " ", 1);
4340
0
        if(result)
4341
0
          return result;
4342
0
        data->state.leading_unfold = FALSE; /* done now */
4343
0
      }
4344
0
    }
4345
4346
0
    end_ptr = memchr(buf, '\n', blen);
4347
0
    if(!end_ptr) {
4348
      /* Not a complete header line within buffer, append the data to
4349
         the end of the headerbuff. */
4350
0
      result = curlx_dyn_addn(&data->state.headerb, buf, blen);
4351
0
      if(result)
4352
0
        return result;
4353
0
      *pconsumed += blen + unfold_len;
4354
4355
0
      if(!k->headerline) {
4356
        /* check if this looks like a protocol header */
4357
0
        statusline st =
4358
0
          checkprotoprefix(data, conn,
4359
0
                           curlx_dyn_ptr(&data->state.headerb),
4360
0
                           curlx_dyn_len(&data->state.headerb));
4361
4362
0
        if(st == STATUS_BAD) {
4363
          /* this is not the beginning of a protocol first header line.
4364
           * Cannot be 0.9 if version was detected or connection was reused. */
4365
0
          k->header = FALSE;
4366
0
          streamclose(conn);
4367
0
          if((k->httpversion >= 10) || conn->bits.reuse) {
4368
0
            failf(data, "Invalid status line");
4369
0
            return CURLE_WEIRD_SERVER_REPLY;
4370
0
          }
4371
0
          if(!data->state.http_neg.accept_09) {
4372
0
            failf(data, "Received HTTP/0.9 when not allowed");
4373
0
            return CURLE_UNSUPPORTED_PROTOCOL;
4374
0
          }
4375
0
          leftover_body = TRUE;
4376
0
          goto out;
4377
0
        }
4378
0
      }
4379
0
      goto out; /* read more and try again */
4380
0
    }
4381
4382
    /* the size of the remaining header line */
4383
0
    consumed = (end_ptr - buf) + 1;
4384
4385
0
    result = curlx_dyn_addn(&data->state.headerb, buf, consumed);
4386
0
    if(result)
4387
0
      return result;
4388
0
    blen -= consumed;
4389
0
    buf += consumed;
4390
0
    *pconsumed += consumed + unfold_len;
4391
4392
    /****
4393
     * We now have a FULL header line in 'headerb'.
4394
     *****/
4395
4396
0
    hlen = curlx_dyn_len(&data->state.headerb);
4397
0
    hd = curlx_dyn_ptr(&data->state.headerb);
4398
4399
0
    if(!k->headerline) {
4400
      /* the first read "header", the status line */
4401
0
      statusline st = checkprotoprefix(data, conn, hd, hlen);
4402
0
      if(st == STATUS_BAD) {
4403
0
        streamclose(conn);
4404
        /* this is not the beginning of a protocol first header line.
4405
         * Cannot be 0.9 if version was detected or connection was reused. */
4406
0
        if((k->httpversion >= 10) || conn->bits.reuse) {
4407
0
          failf(data, "Invalid status line");
4408
0
          return CURLE_WEIRD_SERVER_REPLY;
4409
0
        }
4410
0
        if(!data->state.http_neg.accept_09) {
4411
0
          failf(data, "Received HTTP/0.9 when not allowed");
4412
0
          return CURLE_UNSUPPORTED_PROTOCOL;
4413
0
        }
4414
0
        k->header = FALSE;
4415
0
        leftover_body = TRUE;
4416
0
        goto out;
4417
0
      }
4418
0
    }
4419
0
    else {
4420
0
      if(hlen && !ISNEWLINE(hd[0])) {
4421
        /* this is NOT the header separator */
4422
4423
        /* if we have bytes for the next header, check for folding */
4424
0
        if(blen && ISBLANK(buf[0])) {
4425
          /* remove the trailing CRLF and append the next header */
4426
0
          unfold_header(data);
4427
0
          continue;
4428
0
        }
4429
0
        else if(!blen) {
4430
          /* this might be a folded header so deal with it in next invoke */
4431
0
          data->state.maybe_folded = TRUE;
4432
0
          break;
4433
0
        }
4434
0
      }
4435
0
    }
4436
4437
0
    result = http_rw_hd(data, hd, hlen, buf, blen, &consumed);
4438
    /* We are done with this line. We reset because response
4439
     * processing might switch to HTTP/2 and that might call us
4440
     * directly again. */
4441
0
    curlx_dyn_reset(&data->state.headerb);
4442
0
    if(consumed) {
4443
0
      blen -= consumed;
4444
0
      buf += consumed;
4445
0
      *pconsumed += consumed;
4446
0
    }
4447
0
    if(result)
4448
0
      return result;
4449
0
  }
4450
4451
  /* We might have reached the end of the header part here, but
4452
     there might be a non-header part left in the end of the read
4453
     buffer. */
4454
0
out:
4455
0
  if(!k->header && !leftover_body) {
4456
0
    curlx_dyn_free(&data->state.headerb);
4457
0
  }
4458
0
  return CURLE_OK;
4459
0
}
4460
4461
CURLcode Curl_http_write_resp_hd(struct Curl_easy *data,
4462
                                 const char *hd, size_t hdlen,
4463
                                 bool is_eos)
4464
3.28k
{
4465
3.28k
  CURLcode result;
4466
3.28k
  size_t consumed;
4467
3.28k
  char tmp = 0;
4468
3.28k
  DEBUGASSERT(!hd[hdlen]); /* null-terminated */
4469
4470
3.28k
  result = http_rw_hd(data, hd, hdlen, &tmp, 0, &consumed);
4471
3.28k
  if(!result && is_eos) {
4472
0
    result = Curl_client_write(data, (CLIENTWRITE_BODY | CLIENTWRITE_EOS),
4473
0
                               &tmp, 0);
4474
0
  }
4475
3.28k
  return result;
4476
3.28k
}
4477
4478
/*
4479
 * HTTP protocol `write_resp` implementation. Parse headers
4480
 * when not done yet and otherwise return without consuming data.
4481
 */
4482
CURLcode Curl_http_write_resp_hds(struct Curl_easy *data,
4483
                                  const char *buf, size_t blen,
4484
                                  size_t *pconsumed)
4485
650
{
4486
650
  if(!data->req.header) {
4487
650
    *pconsumed = 0;
4488
650
    return CURLE_OK;
4489
650
  }
4490
0
  else {
4491
0
    CURLcode result;
4492
4493
0
    result = http_parse_headers(data, buf, blen, pconsumed);
4494
0
    if(!result && !data->req.header) {
4495
0
      if(!data->req.no_body && curlx_dyn_len(&data->state.headerb)) {
4496
        /* leftover from parsing something that turned out not
4497
         * to be a header, only happens if we allow for
4498
         * HTTP/0.9 like responses */
4499
0
        result = Curl_client_write(data, CLIENTWRITE_BODY,
4500
0
                                   curlx_dyn_ptr(&data->state.headerb),
4501
0
                                   curlx_dyn_len(&data->state.headerb));
4502
0
      }
4503
0
      curlx_dyn_free(&data->state.headerb);
4504
0
    }
4505
0
    return result;
4506
0
  }
4507
650
}
4508
4509
CURLcode Curl_http_write_resp(struct Curl_easy *data,
4510
                              const char *buf, size_t blen,
4511
                              bool is_eos)
4512
650
{
4513
650
  CURLcode result;
4514
650
  size_t consumed;
4515
650
  int flags;
4516
4517
650
  result = Curl_http_write_resp_hds(data, buf, blen, &consumed);
4518
650
  if(result || data->req.done)
4519
0
    goto out;
4520
4521
650
  DEBUGASSERT(consumed <= blen);
4522
650
  blen -= consumed;
4523
650
  buf += consumed;
4524
  /* either all was consumed in header parsing, or we have data left
4525
   * and are done with headers, e.g. it is BODY data */
4526
650
  DEBUGASSERT(!blen || !data->req.header);
4527
650
  if(!data->req.header && (blen || is_eos)) {
4528
    /* BODY data after header been parsed, write and consume */
4529
650
    flags = CLIENTWRITE_BODY;
4530
650
    if(is_eos)
4531
533
      flags |= CLIENTWRITE_EOS;
4532
650
    result = Curl_client_write(data, flags, buf, blen);
4533
650
  }
4534
650
out:
4535
650
  return result;
4536
650
}
4537
4538
/* Decode HTTP status code string. */
4539
CURLcode Curl_http_decode_status(int32_t *pstatus, const char *s, size_t len)
4540
1.14k
{
4541
1.14k
  CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
4542
1.14k
  int32_t status = 0;
4543
1.14k
  int i;
4544
4545
1.14k
  if(len != 3)
4546
0
    goto out;
4547
4548
4.58k
  for(i = 0; i < 3; ++i) {
4549
3.44k
    char c = s[i];
4550
4551
3.44k
    if(c < '0' || c > '9')
4552
0
      goto out;
4553
4554
3.44k
    status *= 10;
4555
3.44k
    status += c - '0';
4556
3.44k
  }
4557
1.14k
  result = CURLE_OK;
4558
1.14k
out:
4559
1.14k
  *pstatus = result ? -1 : status;
4560
1.14k
  return result;
4561
1.14k
}
4562
4563
CURLcode Curl_http_req_make(struct httpreq **preq,
4564
                            const char *method, size_t m_len,
4565
                            const char *scheme, size_t s_len,
4566
                            const char *authority, size_t a_len,
4567
                            const char *path, size_t p_len)
4568
9.14k
{
4569
9.14k
  struct httpreq *req;
4570
9.14k
  CURLcode result = CURLE_OUT_OF_MEMORY;
4571
4572
9.14k
  DEBUGASSERT(method && m_len);
4573
4574
9.14k
  req = curlx_calloc(1, sizeof(*req) + m_len);
4575
9.14k
  if(!req)
4576
1
    goto out;
4577
#if defined(__GNUC__) && __GNUC__ >= 13
4578
#pragma GCC diagnostic push
4579
/* error: 'memcpy' offset [137, 142] from the object at 'req' is out of
4580
   the bounds of referenced subobject 'method' with type 'char[1]' at
4581
   offset 136 */
4582
#pragma GCC diagnostic ignored "-Warray-bounds"
4583
#endif
4584
9.14k
  memcpy(req->method, method, m_len);
4585
#if defined(__GNUC__) && __GNUC__ >= 13
4586
#pragma GCC diagnostic pop
4587
#endif
4588
9.14k
  if(scheme) {
4589
7.21k
    req->scheme = curlx_memdup0(scheme, s_len);
4590
7.21k
    if(!req->scheme)
4591
1
      goto out;
4592
7.21k
  }
4593
9.14k
  if(authority) {
4594
7.21k
    req->authority = curlx_memdup0(authority, a_len);
4595
7.21k
    if(!req->authority)
4596
1
      goto out;
4597
7.21k
  }
4598
9.14k
  if(path) {
4599
9.14k
    req->path = curlx_memdup0(path, p_len);
4600
9.14k
    if(!req->path)
4601
1
      goto out;
4602
9.14k
  }
4603
9.14k
  Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST);
4604
9.14k
  Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST);
4605
9.14k
  result = CURLE_OK;
4606
4607
9.14k
out:
4608
9.14k
  if(result && req)
4609
3
    Curl_http_req_free(req);
4610
9.14k
  *preq = result ? NULL : req;
4611
9.14k
  return result;
4612
9.14k
}
4613
4614
static CURLcode req_assign_url_authority(struct httpreq *req, CURLU *url)
4615
0
{
4616
0
  char *host, *port;
4617
0
  struct dynbuf buf;
4618
0
  CURLUcode uc;
4619
0
  CURLcode result = CURLE_URL_MALFORMAT;
4620
4621
0
  host = port = NULL;
4622
0
  curlx_dyn_init(&buf, DYN_HTTP_REQUEST);
4623
4624
0
  uc = curl_url_get(url, CURLUPART_HOST, &host, 0);
4625
0
  if(uc && uc != CURLUE_NO_HOST)
4626
0
    goto out;
4627
0
  if(!host) {
4628
0
    req->authority = NULL;
4629
0
    result = CURLE_OK;
4630
0
    goto out;
4631
0
  }
4632
4633
0
  uc = curl_url_get(url, CURLUPART_PORT, &port, CURLU_NO_DEFAULT_PORT);
4634
0
  if(uc && uc != CURLUE_NO_PORT)
4635
0
    goto out;
4636
4637
0
  result = curlx_dyn_add(&buf, host);
4638
0
  if(result)
4639
0
    goto out;
4640
0
  if(port) {
4641
0
    result = curlx_dyn_addf(&buf, ":%s", port);
4642
0
    if(result)
4643
0
      goto out;
4644
0
  }
4645
0
  req->authority = curlx_dyn_ptr(&buf);
4646
0
out:
4647
0
  curlx_free(host);
4648
0
  curlx_free(port);
4649
0
  if(result)
4650
0
    curlx_dyn_free(&buf);
4651
0
  return result;
4652
0
}
4653
4654
static CURLcode req_assign_url_path(struct httpreq *req, CURLU *url)
4655
0
{
4656
0
  char *path, *query;
4657
0
  struct dynbuf buf;
4658
0
  CURLUcode uc;
4659
0
  CURLcode result = CURLE_URL_MALFORMAT;
4660
4661
0
  path = query = NULL;
4662
0
  curlx_dyn_init(&buf, DYN_HTTP_REQUEST);
4663
4664
0
  uc = curl_url_get(url, CURLUPART_PATH, &path, 0);
4665
0
  if(uc)
4666
0
    goto out;
4667
0
  uc = curl_url_get(url, CURLUPART_QUERY, &query, 0);
4668
0
  if(uc && uc != CURLUE_NO_QUERY)
4669
0
    goto out;
4670
4671
0
  if(!query) {
4672
0
    req->path = path;
4673
0
    path = NULL;
4674
0
  }
4675
0
  else {
4676
0
    result = curlx_dyn_add(&buf, path);
4677
0
    if(!result)
4678
0
      result = curlx_dyn_addf(&buf, "?%s", query);
4679
0
    if(result)
4680
0
      goto out;
4681
0
    req->path = curlx_dyn_ptr(&buf);
4682
0
  }
4683
0
  result = CURLE_OK;
4684
4685
0
out:
4686
0
  curlx_free(path);
4687
0
  curlx_free(query);
4688
0
  if(result)
4689
0
    curlx_dyn_free(&buf);
4690
0
  return result;
4691
0
}
4692
4693
CURLcode Curl_http_req_make2(struct httpreq **preq,
4694
                             const char *method, size_t m_len,
4695
                             CURLU *url, const char *scheme_default)
4696
0
{
4697
0
  struct httpreq *req;
4698
0
  CURLcode result = CURLE_OUT_OF_MEMORY;
4699
0
  CURLUcode uc;
4700
4701
0
  DEBUGASSERT(method && m_len);
4702
4703
0
  req = curlx_calloc(1, sizeof(*req) + m_len);
4704
0
  if(!req)
4705
0
    goto out;
4706
0
  memcpy(req->method, method, m_len);
4707
4708
0
  uc = curl_url_get(url, CURLUPART_SCHEME, &req->scheme, 0);
4709
0
  if(uc && uc != CURLUE_NO_SCHEME)
4710
0
    goto out;
4711
0
  if(!req->scheme && scheme_default) {
4712
0
    req->scheme = curlx_strdup(scheme_default);
4713
0
    if(!req->scheme)
4714
0
      goto out;
4715
0
  }
4716
4717
0
  result = req_assign_url_authority(req, url);
4718
0
  if(result)
4719
0
    goto out;
4720
0
  result = req_assign_url_path(req, url);
4721
0
  if(result)
4722
0
    goto out;
4723
4724
0
  Curl_dynhds_init(&req->headers, 0, DYN_HTTP_REQUEST);
4725
0
  Curl_dynhds_init(&req->trailers, 0, DYN_HTTP_REQUEST);
4726
0
  result = CURLE_OK;
4727
4728
0
out:
4729
0
  if(result && req)
4730
0
    Curl_http_req_free(req);
4731
0
  *preq = result ? NULL : req;
4732
0
  return result;
4733
0
}
4734
4735
void Curl_http_req_free(struct httpreq *req)
4736
11.0k
{
4737
11.0k
  if(req) {
4738
9.14k
    curlx_free(req->scheme);
4739
9.14k
    curlx_free(req->authority);
4740
9.14k
    curlx_free(req->path);
4741
9.14k
    Curl_dynhds_cleanup(&req->headers);
4742
9.14k
    Curl_dynhds_cleanup(&req->trailers);
4743
9.14k
    curlx_free(req);
4744
9.14k
  }
4745
11.0k
}
4746
4747
struct name_const {
4748
  const char *name;
4749
  size_t namelen;
4750
};
4751
4752
static const struct name_const H2_NON_FIELD[] = {
4753
  { STRCONST("Host") },
4754
  { STRCONST("Upgrade") },
4755
  { STRCONST("Connection") },
4756
  { STRCONST("Keep-Alive") },
4757
  { STRCONST("Proxy-Connection") },
4758
  { STRCONST("Transfer-Encoding") },
4759
};
4760
4761
static bool h2_permissible_field(struct dynhds_entry *e)
4762
4.75k
{
4763
4.75k
  size_t i;
4764
21.6k
  for(i = 0; i < CURL_ARRAYSIZE(H2_NON_FIELD); ++i) {
4765
18.8k
    if(e->namelen == H2_NON_FIELD[i].namelen &&
4766
1.95k
       curl_strnequal(H2_NON_FIELD[i].name, e->name, e->namelen))
4767
1.93k
      return FALSE;
4768
18.8k
  }
4769
2.81k
  return TRUE;
4770
4.75k
}
4771
4772
static bool http_TE_has_token(const char *fvalue, const char *token)
4773
4
{
4774
8
  while(*fvalue) {
4775
4
    struct Curl_str name;
4776
4777
    /* skip to first token */
4778
4
    while(ISBLANK(*fvalue) || *fvalue == ',')
4779
0
      fvalue++;
4780
4
    if(curlx_str_cspn(&fvalue, &name, " \t\r;,"))
4781
0
      return FALSE;
4782
4
    if(curlx_str_casecompare(&name, token))
4783
0
      return TRUE;
4784
4785
    /* skip any remainder after token, e.g. parameters with quoted strings */
4786
4
    while(*fvalue && *fvalue != ',') {
4787
0
      if(*fvalue == '"') {
4788
0
        struct Curl_str qw;
4789
        /* if we do not cleanly find a quoted word here, the header value
4790
         * does not follow HTTP syntax and we reject */
4791
0
        if(curlx_str_quotedword(&fvalue, &qw, CURL_MAX_HTTP_HEADER))
4792
0
          return FALSE;
4793
0
      }
4794
0
      else
4795
0
        fvalue++;
4796
0
    }
4797
4
  }
4798
4
  return FALSE;
4799
4
}
4800
4801
CURLcode Curl_http_req_to_h2(struct dynhds *h2_headers,
4802
                             struct httpreq *req, struct Curl_easy *data)
4803
1.92k
{
4804
1.92k
  const char *scheme = NULL, *authority = NULL;
4805
1.92k
  struct dynhds_entry *e;
4806
1.92k
  uint32_t i, nheaders;
4807
1.92k
  CURLcode result;
4808
4809
1.92k
  DEBUGASSERT(req);
4810
1.92k
  DEBUGASSERT(h2_headers);
4811
4812
1.92k
  if(req->scheme) {
4813
0
    scheme = req->scheme;
4814
0
  }
4815
1.92k
  else if(strcmp("CONNECT", req->method)) {
4816
1.92k
    scheme = Curl_checkheaders(data, STRCONST(HTTP_PSEUDO_SCHEME));
4817
1.92k
    if(scheme) {
4818
0
      scheme += sizeof(HTTP_PSEUDO_SCHEME);
4819
0
      curlx_str_passblanks(&scheme);
4820
0
      infof(data, "set pseudo header %s to %s", HTTP_PSEUDO_SCHEME, scheme);
4821
0
    }
4822
1.92k
    else {
4823
1.92k
      scheme = data->state.origin->scheme->name;
4824
1.92k
    }
4825
1.92k
  }
4826
4827
1.92k
  if(req->authority) {
4828
0
    authority = req->authority;
4829
0
  }
4830
1.92k
  else {
4831
1.92k
    e = Curl_dynhds_get(&req->headers, STRCONST("Host"));
4832
1.92k
    if(e)
4833
1.92k
      authority = e->value;
4834
1.92k
  }
4835
4836
1.92k
  Curl_dynhds_reset(h2_headers);
4837
1.92k
  Curl_dynhds_set_opts(h2_headers, DYNHDS_OPT_LOWERCASE);
4838
1.92k
  result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_METHOD),
4839
1.92k
                           req->method, strlen(req->method));
4840
1.92k
  if(!result && scheme) {
4841
1.92k
    result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_SCHEME),
4842
1.92k
                             scheme, strlen(scheme));
4843
1.92k
  }
4844
1.92k
  if(!result && authority) {
4845
1.92k
    result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_AUTHORITY),
4846
1.92k
                             authority, strlen(authority));
4847
1.92k
  }
4848
1.92k
  if(!result && req->path) {
4849
1.92k
    result = Curl_dynhds_add(h2_headers, STRCONST(HTTP_PSEUDO_PATH),
4850
1.92k
                             req->path, strlen(req->path));
4851
1.92k
  }
4852
4853
1.92k
  nheaders = Curl_dynhds_count(&req->headers);
4854
6.68k
  for(i = 0; !result && (i < nheaders); ++i) {
4855
4.75k
    e = Curl_dynhds_getn(&req->headers, i);
4856
4.75k
    if(!e)
4857
0
      break;
4858
    /* "TE" is special in that it is only permissible when it
4859
     * has only value "trailers". RFC 9113 ch. 8.2.2 */
4860
4.75k
    if(e->namelen == 2 && curl_strequal("TE", e->name)) {
4861
4
      if(http_TE_has_token(e->value, "trailers"))
4862
0
        result = Curl_dynhds_add(h2_headers, e->name, e->namelen,
4863
0
                                 "trailers", CURL_CSTRLEN("trailers"));
4864
4
    }
4865
4.75k
    else if(h2_permissible_field(e)) {
4866
2.81k
      result = Curl_dynhds_add(h2_headers, e->name, e->namelen,
4867
2.81k
                               e->value, e->valuelen);
4868
2.81k
    }
4869
4.75k
  }
4870
4871
1.92k
  return result;
4872
1.92k
}
4873
4874
CURLcode Curl_http_resp_make(struct http_resp **presp,
4875
                             int status,
4876
                             const char *description)
4877
0
{
4878
0
  struct http_resp *resp;
4879
0
  CURLcode result = CURLE_OUT_OF_MEMORY;
4880
4881
0
  resp = curlx_calloc(1, sizeof(*resp));
4882
0
  if(!resp)
4883
0
    goto out;
4884
4885
0
  resp->status = status;
4886
0
  if(description) {
4887
0
    resp->description = curlx_strdup(description);
4888
0
    if(!resp->description)
4889
0
      goto out;
4890
0
  }
4891
0
  Curl_dynhds_init(&resp->headers, 0, DYN_HTTP_REQUEST);
4892
0
  Curl_dynhds_init(&resp->trailers, 0, DYN_HTTP_REQUEST);
4893
0
  result = CURLE_OK;
4894
4895
0
out:
4896
0
  if(result && resp)
4897
0
    Curl_http_resp_free(resp);
4898
0
  *presp = result ? NULL : resp;
4899
0
  return result;
4900
0
}
4901
4902
void Curl_http_resp_free(struct http_resp *resp)
4903
0
{
4904
0
  if(resp) {
4905
0
    curlx_free(resp->description);
4906
0
    Curl_dynhds_cleanup(&resp->headers);
4907
0
    Curl_dynhds_cleanup(&resp->trailers);
4908
0
    if(resp->prev)
4909
0
      Curl_http_resp_free(resp->prev);
4910
0
    curlx_free(resp);
4911
0
  }
4912
0
}
4913
4914
CURLcode Curl_http_setup_conn(struct Curl_easy *data,
4915
                              struct connectdata *conn)
4916
9.41k
{
4917
  /* allocate the HTTP-specific struct for the Curl_easy, only to survive
4918
     during this request */
4919
9.41k
  if(data->state.http_neg.wanted == CURL_HTTP_V3x) {
4920
    /* only HTTP/3, needs to work */
4921
9.41k
    CURLcode result = Curl_conn_may_http3(data, conn);
4922
9.41k
    if(result)
4923
0
      return result;
4924
9.41k
  }
4925
9.41k
  return CURLE_OK;
4926
9.41k
}
4927
4928
CURLcode Curl_http_setup_filters(struct Curl_easy *data,
4929
                                 struct Curl_cfilter *cf)
4930
1.95k
{
4931
1.95k
  const char *alpn = Curl_conn_cf_get_alpn_negotiated(cf, data);
4932
1.95k
  CURLcode result;
4933
4934
1.95k
  if(alpn && !strcmp("h3", alpn)) {
4935
1.95k
    CURL_TRC_CF(data, cf, "using HTTP/3 (via ALPN)");
4936
1.95k
  }
4937
0
  else if(alpn && !strcmp("h2", alpn)) {
4938
0
    if(Curl_conn_cf_http_version(data, cf) != 20) {
4939
0
      CURL_TRC_CF(data, cf, "adding HTTP/2 filter");
4940
0
      result = Curl_http2_switch_at(data, cf);
4941
0
      if(result)
4942
0
        return result;
4943
0
    }
4944
0
    CURL_TRC_CF(data, cf, "using HTTP/2 (via ALPN)");
4945
0
  }
4946
0
  else {
4947
    /* Check if user wants to use HTTP/2 with clear TCP */
4948
0
    if(Curl_http2_may_switch_at(data, cf)) {
4949
0
      CURL_TRC_CF(data, cf, "adding HTTP/2 filter");
4950
0
      result = Curl_http2_switch_at(data, cf);
4951
0
      if(result)
4952
0
        return result;
4953
0
      CURL_TRC_CF(data, cf, "using HTTP/2 (over clean TCP)");
4954
0
    }
4955
0
    else
4956
0
      CURL_TRC_CF(data, cf, "using HTTP/1.x");
4957
0
  }
4958
1.95k
  return CURLE_OK;
4959
1.95k
}
4960
4961
/*
4962
 * HTTP handler interface.
4963
 */
4964
const struct Curl_protocol Curl_protocol_http = {
4965
  Curl_http_setup_conn,                 /* setup_connection */
4966
  Curl_http_setup_filters,              /* setup_filters */
4967
  Curl_http,                            /* do_it */
4968
  Curl_http_done,                       /* done */
4969
  ZERO_NULL,                            /* do_more */
4970
  ZERO_NULL,                            /* connect_it */
4971
  ZERO_NULL,                            /* connecting */
4972
  ZERO_NULL,                            /* doing */
4973
  ZERO_NULL,                            /* proto_pollset */
4974
  Curl_http_doing_pollset,              /* doing_pollset */
4975
  ZERO_NULL,                            /* domore_pollset */
4976
  Curl_http_perform_pollset,            /* perform_pollset */
4977
  ZERO_NULL,                            /* disconnect */
4978
  Curl_http_write_resp,                 /* write_resp */
4979
  Curl_http_write_resp_hd,              /* write_resp_hd */
4980
  ZERO_NULL,                            /* connection_is_dead */
4981
  ZERO_NULL,                            /* attach connection */
4982
  Curl_http_follow,                     /* follow */
4983
};
4984
4985
#endif /* CURL_DISABLE_HTTP */