Coverage Report

Created: 2026-12-01 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/altsvc.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
/*
25
 * The Alt-Svc: header is defined in RFC 7838:
26
 * https://datatracker.ietf.org/doc/html/rfc7838
27
 */
28
#include "curl_setup.h"
29
30
#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
31
#include "urldata.h"
32
#include "altsvc.h"
33
#include "curl_fopen.h"
34
#include "curl_get_line.h"
35
#include "parsedate.h"
36
#include "curl_trc.h"
37
#include "curl_addrinfo.h"
38
#include "curlx/inet_pton.h"
39
#include "curlx/strparse.h"
40
#include "connect.h"
41
#include "escape.h"
42
#include "urlapi-int.h"
43
44
13.1k
#define MAX_ALTSVC_LINE    4095
45
0
#define MAX_ALTSVC_DATELEN 17
46
0
#define MAX_ALTSVC_HOSTLEN 2048
47
13.1k
#define MAX_ALTSVC_ALPNLEN 10
48
49
0
#define H3VERSION "h3"
50
51
/*
52
 * If USE_IPV6 is disabled, we still want to parse IPv6 addresses, so make
53
 * sure we have _some_ value for AF_INET6 without polluting our fake value
54
 * everywhere.
55
 */
56
#if !defined(USE_IPV6) && !defined(AF_INET6)
57
#define AF_INET6 (AF_INET + 1)
58
#endif
59
60
#if defined(DEBUGBUILD) || defined(UNITTESTS)
61
/* to play well with debug builds, we can *set* a fixed time this will
62
   return */
63
static time_t altsvc_debugtime(void *unused)
64
0
{
65
0
  const char *timestr = getenv("CURL_TIME");
66
0
  (void)unused;
67
0
  if(timestr) {
68
0
    curl_off_t val;
69
0
    curlx_str_number(&timestr, &val, TIME_T_MAX);
70
0
    return (time_t)val;
71
0
  }
72
0
  return time(NULL);
73
0
}
74
#undef time
75
0
#define time(x) altsvc_debugtime(x)
76
#endif
77
78
/* Given the ALPN ID, return the name */
79
const char *Curl_alpnid2str(enum alpnid id)
80
0
{
81
0
  switch(id) {
82
0
  case ALPN_h1:
83
0
    return "h1";
84
0
  case ALPN_h2:
85
0
    return "h2";
86
0
  case ALPN_h3:
87
0
    return H3VERSION;
88
0
  default:
89
0
    return ""; /* bad */
90
0
  }
91
0
}
92
93
static enum alpnid Curl_str2alpnid(const struct Curl_str *cstr)
94
0
{
95
0
  return Curl_alpn2alpnid((const unsigned char *)curlx_str(cstr),
96
0
                          curlx_strlen(cstr));
97
0
}
98
99
0
#define altsvc_free(x) curlx_free(x)
100
101
static struct altsvc *altsvc_createid(const char *srchost,
102
                                      size_t hlen,
103
                                      const char *dsthost,
104
                                      size_t dlen, /* dsthost length */
105
                                      enum alpnid srcalpnid,
106
                                      enum alpnid dstalpnid,
107
                                      size_t srcport,
108
                                      size_t dstport)
109
0
{
110
0
  struct altsvc *as;
111
0
  if((hlen > 2) && srchost[0] == '[') {
112
    /* IPv6 address, strip off brackets */
113
0
    srchost++;
114
0
    hlen -= 2;
115
0
  }
116
0
  else if(hlen && (srchost[hlen - 1] == '.')) {
117
    /* strip off trailing dot */
118
0
    hlen--;
119
0
  }
120
0
  if((dlen > 2) && dsthost[0] == '[') {
121
    /* IPv6 address, strip off brackets */
122
0
    dsthost++;
123
0
    dlen -= 2;
124
0
  }
125
0
  if(!hlen || !dlen)
126
    /* bad input */
127
0
    return NULL;
128
  /* struct size plus both strings */
129
0
  as = curlx_calloc(1, sizeof(struct altsvc) + (hlen + 1) + (dlen + 1));
130
0
  if(!as)
131
0
    return NULL;
132
0
  as->src.host = (char *)as + sizeof(struct altsvc);
133
0
  memcpy(as->src.host, srchost, hlen);
134
  /* the null-terminator is already there */
135
136
0
  as->dst.host = (char *)as + sizeof(struct altsvc) + hlen + 1;
137
0
  memcpy(as->dst.host, dsthost, dlen);
138
  /* the null-terminator is already there */
139
140
0
  as->src.alpnid = srcalpnid;
141
0
  as->dst.alpnid = dstalpnid;
142
0
  as->src.port = (unsigned short)srcport;
143
0
  as->dst.port = (unsigned short)dstport;
144
145
0
  return as;
146
0
}
147
148
static struct altsvc *altsvc_create(struct Curl_str *srchost,
149
                                    struct Curl_str *dsthost,
150
                                    struct Curl_str *srcalpn,
151
                                    struct Curl_str *dstalpn,
152
                                    size_t srcport,
153
                                    size_t dstport)
154
0
{
155
0
  enum alpnid dstalpnid = Curl_str2alpnid(dstalpn);
156
0
  enum alpnid srcalpnid = Curl_str2alpnid(srcalpn);
157
0
  if(!srcalpnid || !dstalpnid)
158
0
    return NULL;
159
0
  return altsvc_createid(curlx_str(srchost), curlx_strlen(srchost),
160
0
                         curlx_str(dsthost), curlx_strlen(dsthost),
161
0
                         srcalpnid, dstalpnid,
162
0
                         srcport, dstport);
163
0
}
164
165
/* append the new entry to the list after possibly removing an old entry
166
   first */
167
static void altsvc_append(struct altsvcinfo *asi, struct altsvc *as)
168
0
{
169
0
  while(Curl_llist_count(&asi->list) >= MAX_ALTSVC_ENTRIES) {
170
    /* It is full. Remove the first entry in the list */
171
0
    struct Curl_llist_node *e = Curl_llist_head(&asi->list);
172
0
    struct altsvc *oldas = Curl_node_elem(e);
173
0
    Curl_node_remove(e);
174
0
    altsvc_free(oldas);
175
0
  }
176
0
  Curl_llist_append(&asi->list, as, &as->node);
177
0
}
178
179
/* return TRUE if the destination host is a valid hostname or IPv6 address */
180
static bool altsvc_valid_host(const char *host, size_t len)
181
0
{
182
0
  struct Curl_str ip6;
183
0
  char buf[MAX_IPADR_LEN];
184
0
  unsigned char addr[16];
185
186
0
  if((len > 2) && (host[0] == '[') && (host[len - 1] == ']')) {
187
0
    host++;
188
0
    len -= 2;
189
0
  }
190
0
  if(!Curl_hostname_check(host, len))
191
0
    return TRUE;
192
0
  if(Curl_looks_like_ipv6(host, len, FALSE, &ip6, NULL) &&
193
0
     curlx_strlen(&ip6) && (curlx_strlen(&ip6) < sizeof(buf))) {
194
0
    memcpy(buf, curlx_str(&ip6), curlx_strlen(&ip6));
195
0
    buf[curlx_strlen(&ip6)] = 0;
196
0
    return curlx_inet_pton(AF_INET6, buf, addr) == 1;
197
0
  }
198
0
  return FALSE;
199
0
}
200
201
/* only returns SERIOUS errors */
202
static CURLcode altsvc_add(struct altsvcinfo *asi, const char *line)
203
13.1k
{
204
  /* Example line:
205
     h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
206
   */
207
13.1k
  struct Curl_str srchost;
208
13.1k
  struct Curl_str dsthost;
209
13.1k
  struct Curl_str srcalpn;
210
13.1k
  struct Curl_str dstalpn;
211
13.1k
  struct Curl_str date;
212
13.1k
  curl_off_t srcport;
213
13.1k
  curl_off_t dstport;
214
13.1k
  curl_off_t persist;
215
13.1k
  curl_off_t prio;
216
217
13.1k
  if(curlx_str_word(&line, &srcalpn, MAX_ALTSVC_ALPNLEN) ||
218
13.1k
     curlx_str_singlespace(&line) ||
219
0
     curlx_str_word(&line, &srchost, MAX_ALTSVC_HOSTLEN) ||
220
0
     curlx_str_singlespace(&line) ||
221
0
     curlx_str_number(&line, &srcport, 65535) ||
222
0
     curlx_str_singlespace(&line) ||
223
0
     curlx_str_word(&line, &dstalpn, MAX_ALTSVC_ALPNLEN) ||
224
0
     curlx_str_singlespace(&line) ||
225
0
     curlx_str_word(&line, &dsthost, MAX_ALTSVC_HOSTLEN) ||
226
0
     curlx_str_singlespace(&line) ||
227
0
     curlx_str_number(&line, &dstport, 65535) ||
228
0
     curlx_str_singlespace(&line) ||
229
0
     curlx_str_quotedword(&line, &date, MAX_ALTSVC_DATELEN) ||
230
0
     curlx_str_singlespace(&line) ||
231
0
     curlx_str_number(&line, &persist, 1) ||
232
0
     curlx_str_singlespace(&line) ||
233
0
     curlx_str_number(&line, &prio, 0) ||
234
0
     curlx_str_newline(&line) ||
235
0
     !altsvc_valid_host(curlx_str(&dsthost), curlx_strlen(&dsthost)))
236
13.1k
    ;
237
0
  else {
238
0
    char dbuf[MAX_ALTSVC_DATELEN + 1];
239
0
    time_t expires = 0;
240
0
    time_t now = time(NULL);
241
242
    /* The date parser works on a null-terminated string. The maximum length
243
       is upheld by curlx_str_quotedword(). */
244
0
    memcpy(dbuf, curlx_str(&date), curlx_strlen(&date));
245
0
    dbuf[curlx_strlen(&date)] = 0;
246
0
    Curl_getdate_capped(dbuf, &expires);
247
248
0
    if(now < expires) {
249
0
      struct altsvc *as = altsvc_create(&srchost, &dsthost, &srcalpn, &dstalpn,
250
0
                                        (size_t)srcport, (size_t)dstport);
251
0
      if(as) {
252
0
        as->expires = expires;
253
0
        as->persist = persist ? 1 : 0;
254
0
        altsvc_append(asi, as);
255
0
      }
256
0
      else
257
0
        return CURLE_OUT_OF_MEMORY;
258
0
    }
259
0
  }
260
261
13.1k
  return CURLE_OK;
262
13.1k
}
263
264
/*
265
 * Load alt-svc entries from the given file. The text based line-oriented file
266
 * format is documented here: https://curl.se/docs/alt-svc.html
267
 *
268
 * This function only returns error on major problems that prevent alt-svc
269
 * handling to work completely. It will ignore individual syntactical errors
270
 * etc.
271
 */
272
static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
273
13.1k
{
274
13.1k
  CURLcode result = CURLE_OK;
275
13.1k
  FILE *fp;
276
277
  /* we need a private copy of the filename so that the altsvc cache file
278
     name survives an easy handle reset */
279
13.1k
  curlx_free(asi->filename);
280
13.1k
  asi->filename = curlx_strdup(file);
281
13.1k
  if(!asi->filename)
282
3
    return CURLE_OUT_OF_MEMORY;
283
284
13.1k
  fp = curlx_fopen(file, FOPEN_READTEXT);
285
13.1k
  if(fp) {
286
13.1k
    curlx_struct_stat stat;
287
13.1k
    if((curlx_fstat(fileno(fp), &stat) == -1) || !S_ISDIR(stat.st_mode)) {
288
13.1k
      bool eof = FALSE;
289
13.1k
      struct dynbuf buf;
290
13.1k
      curlx_dyn_init(&buf, MAX_ALTSVC_LINE);
291
13.1k
      do {
292
13.1k
        result = Curl_get_line(&buf, fp, &eof);
293
13.1k
        if(!result) {
294
13.1k
          const char *lineptr = curlx_dyn_ptr(&buf);
295
13.1k
          curlx_str_passblanks(&lineptr);
296
13.1k
          if(curlx_str_single(&lineptr, '#'))
297
13.1k
            altsvc_add(asi, lineptr);
298
13.1k
        }
299
13.1k
      } while(!result && !eof);
300
13.1k
      curlx_dyn_free(&buf); /* free the line buffer */
301
13.1k
    }
302
13.1k
    curlx_fclose(fp);
303
13.1k
  }
304
13.1k
  return result;
305
13.1k
}
306
307
/*
308
 * Write this single altsvc entry to a single output line
309
 */
310
static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
311
0
{
312
0
  struct tm stamp;
313
0
  const char *dst6_pre = "";
314
0
  const char *dst6_post = "";
315
0
  const char *src6_pre = "";
316
0
  const char *src6_post = "";
317
0
  CURLcode result = curlx_gmtime(as->expires, &stamp);
318
0
  if(result)
319
    /* fail silently for date errors so that only this entry gets
320
       skipped */
321
0
    return CURLE_OK;
322
0
#ifdef USE_IPV6
323
0
  else {
324
0
    char ipv6_unused[16];
325
0
    if(curlx_inet_pton(AF_INET6, as->dst.host, ipv6_unused) == 1) {
326
0
      dst6_pre = "[";
327
0
      dst6_post = "]";
328
0
    }
329
0
    if(curlx_inet_pton(AF_INET6, as->src.host, ipv6_unused) == 1) {
330
0
      src6_pre = "[";
331
0
      src6_post = "]";
332
0
    }
333
0
  }
334
0
#endif
335
0
  curl_mfprintf(fp,
336
0
                "%s %s%s%s %u "
337
0
                "%s %s%s%s %u "
338
0
                "\"%d%02d%02d "
339
0
                "%02d:%02d:%02d\" "
340
0
                "%d 0\n", /* prio still always zero */
341
0
                Curl_alpnid2str(as->src.alpnid),
342
0
                src6_pre, as->src.host, src6_post,
343
0
                as->src.port,
344
345
0
                Curl_alpnid2str(as->dst.alpnid),
346
0
                dst6_pre, as->dst.host, dst6_post,
347
0
                as->dst.port,
348
349
0
                stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
350
0
                stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
351
0
                as->persist);
352
0
  return CURLE_OK;
353
0
}
354
355
/* ---- library-wide functions below ---- */
356
357
/*
358
 * Curl_altsvc_init() creates a new altsvc cache.
359
 * It returns the new instance or NULL if something goes wrong.
360
 */
361
struct altsvcinfo *Curl_altsvc_init(void)
362
13.1k
{
363
13.1k
  struct altsvcinfo *asi = curlx_calloc(1, sizeof(struct altsvcinfo));
364
13.1k
  if(!asi)
365
26
    return NULL;
366
13.1k
  Curl_llist_init(&asi->list, NULL);
367
368
  /* set default behavior */
369
13.1k
  asi->flags = CURLALTSVC_H1
370
13.1k
#ifdef USE_HTTP2
371
13.1k
    | CURLALTSVC_H2
372
13.1k
#endif
373
#ifdef USE_HTTP3
374
    | CURLALTSVC_H3
375
#endif
376
13.1k
    ;
377
13.1k
  return asi;
378
13.1k
}
379
380
/*
381
 * Curl_altsvc_load() loads alt-svc from file.
382
 */
383
CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
384
13.1k
{
385
13.1k
  DEBUGASSERT(asi);
386
13.1k
  return altsvc_load(asi, file);
387
13.1k
}
388
389
/*
390
 * Curl_altsvc_ctrl() passes on the external bitmask.
391
 */
392
CURLcode Curl_altsvc_ctrl(struct Curl_easy *data, const long ctrl)
393
655
{
394
655
  DEBUGASSERT(data);
395
655
  if(!ctrl)
396
117
    return CURLE_BAD_FUNCTION_ARGUMENT;
397
398
538
  if(!data->asi) {
399
4
    data->asi = Curl_altsvc_init();
400
4
    if(!data->asi)
401
0
      return CURLE_OUT_OF_MEMORY;
402
4
  }
403
538
  data->asi->flags = ctrl;
404
538
  return CURLE_OK;
405
538
}
406
407
/*
408
 * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
409
 * resources.
410
 */
411
void Curl_altsvc_cleanup(struct altsvcinfo **asi)
412
26.3k
{
413
26.3k
  if(*asi) {
414
13.1k
    struct Curl_llist_node *e;
415
13.1k
    struct Curl_llist_node *n;
416
13.1k
    struct altsvcinfo *altsvc = *asi;
417
13.1k
    for(e = Curl_llist_head(&altsvc->list); e; e = n) {
418
0
      struct altsvc *as = Curl_node_elem(e);
419
0
      n = Curl_node_next(e);
420
0
      altsvc_free(as);
421
0
    }
422
13.1k
    curlx_free(altsvc->filename);
423
13.1k
    curlx_free(altsvc);
424
13.1k
    *asi = NULL; /* clear the pointer */
425
13.1k
  }
426
26.3k
}
427
428
/*
429
 * Curl_altsvc_save() writes the altsvc cache to a file.
430
 */
431
CURLcode Curl_altsvc_save(struct Curl_easy *data,
432
                          struct altsvcinfo *asi, const char *file)
433
26.3k
{
434
26.3k
  CURLcode result = CURLE_OK;
435
26.3k
  FILE *out;
436
26.3k
  char *tempstore = NULL;
437
438
26.3k
  if(!asi)
439
    /* no cache activated */
440
13.1k
    return CURLE_OK;
441
442
  /* if not new name is given, use the one we stored from the load */
443
13.1k
  if(!file && asi->filename)
444
0
    file = asi->filename;
445
446
13.1k
  if((asi->flags & CURLALTSVC_READONLYFILE) || !file || !file[0])
447
    /* marked as read-only, no file or zero length filename */
448
75
    return CURLE_OK;
449
450
13.0k
  result = Curl_fopen(data, file, &out, &tempstore);
451
13.0k
  if(!result) {
452
13.0k
    struct Curl_llist_node *e;
453
13.0k
    struct Curl_llist_node *n;
454
13.0k
    fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n"
455
13.0k
          "# This file was generated by libcurl! Edit at your own risk.\n",
456
13.0k
          out);
457
13.0k
    for(e = Curl_llist_head(&asi->list); e; e = n) {
458
0
      struct altsvc *as = Curl_node_elem(e);
459
0
      n = Curl_node_next(e);
460
0
      result = altsvc_out(as, out);
461
0
      if(result)
462
0
        break;
463
0
    }
464
13.0k
    if(fflush(out) || ferror(out))
465
0
      result = CURLE_WRITE_ERROR;
466
13.0k
    if(curlx_fclose(out))
467
0
      result = CURLE_WRITE_ERROR;
468
13.0k
    if(!result && tempstore && curlx_rename(tempstore, file))
469
0
      result = CURLE_WRITE_ERROR;
470
471
13.0k
    if(result && tempstore)
472
0
      unlink(tempstore);
473
13.0k
  }
474
13.0k
  curlx_free(tempstore);
475
13.0k
  return result;
476
13.1k
}
477
478
/* hostcompare() returns true if 'host' matches 'check'. The first host
479
 * argument may have a trailing dot present that will be ignored.
480
 */
481
static bool hostcompare(const char *host, const char *check)
482
0
{
483
0
  size_t hlen = strlen(host);
484
0
  size_t clen = strlen(check);
485
486
0
  if(hlen && (host[hlen - 1] == '.'))
487
0
    hlen--;
488
0
  if(hlen != clen)
489
    /* they cannot match if they have different lengths */
490
0
    return FALSE;
491
0
  return curl_strnequal(host, check, hlen);
492
0
}
493
494
/* Remove all cached alternatives for this origin, regardless of ALPN. */
495
static void altsvc_flush(struct altsvcinfo *asi,
496
                         struct Curl_peer *origin)
497
0
{
498
0
  struct Curl_llist_node *e;
499
0
  struct Curl_llist_node *n;
500
0
  for(e = Curl_llist_head(&asi->list); e; e = n) {
501
0
    struct altsvc *as = Curl_node_elem(e);
502
0
    n = Curl_node_next(e);
503
0
    if((origin->port == as->src.port) &&
504
0
       hostcompare(origin->hostname, as->src.host)) {
505
0
      Curl_node_remove(e);
506
0
      altsvc_free(as);
507
0
    }
508
0
  }
509
0
}
510
511
0
#define CAP_ALTSVC_MAX_AGE (2*365*24*3600) /* two years cap */
512
513
0
#define ALTSVC_MA      1
514
0
#define ALTSVC_PERSIST 2
515
static void altsvc_parse_params(const char **pp,
516
                                time_t *pmaxage,
517
                                bool *ppersist)
518
0
{
519
0
  curlx_str_passblanks(pp);
520
0
  if(curlx_str_single(pp, ';'))
521
0
    return;
522
523
0
  for(;;) {
524
0
    struct Curl_str name;
525
0
    struct Curl_str val;
526
0
    curl_off_t num;
527
0
    int keyword = 0;
528
529
    /* allow some extra whitespaces around name and value */
530
0
    if(curlx_str_until(pp, &name, MAX_ALTSVC_LINE, '=') ||
531
0
       curlx_str_single(pp, '='))
532
0
      break;  /* skip further parameter parsing */
533
534
0
    curlx_str_trimblanks(&name);
535
0
    curlx_str_passblanks(pp);
536
0
    if(**pp == '\"') {
537
0
      if(curlx_str_quotedword(pp, &val, MAX_ALTSVC_LINE))
538
0
        break;
539
0
    }
540
0
    else {
541
0
      if(curlx_str_cspn(pp, &val, ",;\r\n"))
542
0
        break;
543
0
    }
544
0
    curlx_str_trimblanks(&val);
545
546
0
    if(curlx_str_casecompare2(&name, STRCONST("ma")))
547
0
      keyword = ALTSVC_MA;
548
0
    else if(curlx_str_casecompare2(&name, STRCONST("persist")))
549
0
      keyword = ALTSVC_PERSIST;
550
551
0
    if(keyword) {
552
0
      const char *vp = curlx_str(&val);
553
0
      const char *vend = vp + curlx_strlen(&val);
554
0
      if(curlx_str_number(&vp, &num, CURL_OFF_T_MAX))
555
0
        break; /* not a number, skip further parameter parsing */
556
0
      if(vp != vend)
557
0
        break; /* not entirely a number, skip further parameter parsing */
558
0
      if(keyword == ALTSVC_MA) {
559
0
        if(num > CAP_ALTSVC_MAX_AGE)
560
0
          num = CAP_ALTSVC_MAX_AGE;
561
0
        *pmaxage = (time_t)num;
562
0
      }
563
0
      else if(num == 1)
564
0
        *ppersist = TRUE;
565
0
    }
566
567
0
    curlx_str_passblanks(pp);
568
0
    if(curlx_str_single(pp, ';'))
569
0
      break; /* no further parameters */
570
0
  }
571
0
}
572
573
static bool altsvc_parse_dest(const char **pp,
574
                              struct Curl_easy *data,
575
                              struct Curl_peer *origin,
576
                              struct Curl_str *dsthost,
577
                              uint16_t *pdstport)
578
0
{
579
0
  curl_off_t port = 0;
580
581
0
  if(curlx_str_single(pp, '\"'))
582
0
    return FALSE;
583
584
  /* quoted string, with hostname or just :port ? */
585
0
  if(curlx_str_single(pp, ':')) { /* is hostname:port ? */
586
0
    if(curlx_str_single(pp, '[')) { /* DNS hostname/IPv4 */
587
0
      if(curlx_str_until(pp, dsthost, MAX_ALTSVC_HOSTLEN, ':')) {
588
0
        infof(data, "Bad alt-svc hostname, ignoring.");
589
0
        return FALSE;
590
0
      }
591
0
    }
592
0
    else { /* IPv6 hostname */
593
0
      if(curlx_str_until(pp, dsthost, MAX_IPADR_LEN, ']') ||
594
0
         curlx_str_single(pp, ']')) {
595
0
        infof(data, "Bad alt-svc IPv6 hostname, ignoring.");
596
0
        return FALSE;
597
0
      }
598
0
    }
599
0
    if(curlx_str_single(pp, ':'))
600
0
      return FALSE; /* not followed by ':' */
601
0
    if(!altsvc_valid_host(curlx_str(dsthost), curlx_strlen(dsthost))) {
602
0
      infof(data, "Bad alt-svc hostname, ignoring.");
603
0
      return FALSE;
604
0
    }
605
0
  }
606
0
  else  /* is only :port, hostname is effectively origin */
607
0
    curlx_str_assign(dsthost, origin->hostname,
608
0
                     strlen(origin->hostname));
609
610
0
  if(curlx_str_number(pp, &port, 0xffff)) {
611
0
    infof(data, "Unknown alt-svc port number, ignoring.");
612
0
    return FALSE;
613
0
  }
614
615
0
  *pdstport = (uint16_t)port;
616
0
  if(curlx_str_single(pp, '\"'))
617
0
    return FALSE; /* quoted string not ending here as expected */
618
0
  return TRUE;
619
0
}
620
621
/*
622
 * Curl_altsvc_parse() takes an incoming alt-svc response header and stores
623
 * the data correctly in the cache.
624
 *
625
 * 'value' points to the header *value*. That is contents to the right of the
626
 * header name.
627
 *
628
 * Currently this function rejects invalid data without returning an error.
629
 * Invalid hostname, port number will result in the specific alternative
630
 * being rejected. Unknown protocols are skipped.
631
 */
632
CURLcode Curl_altsvc_parse(struct Curl_easy *data,
633
                           struct altsvcinfo *asi, const char *value,
634
                           struct Curl_peer *origin,
635
                           enum alpnid origin_alpnid)
636
0
{
637
0
  struct altsvc *as;
638
0
  size_t entries = 0;
639
0
  struct Curl_str alpn;
640
0
  const char *p;
641
642
0
  DEBUGASSERT(asi);
643
0
  DEBUGASSERT(origin);
644
  /* RFC 7838, The "Alt-Svc" header field value is basically
645
   * Alt-Svc: (clear|alpn="(host)?:port"\s*(;\s*parameter=value)*)
646
   * This can be repeated, comma-separated.
647
   *
648
   * We parse "best effort", ignoring values we do not recognize.
649
   */
650
651
  /* Try to catch a standalone "clear" */
652
0
  p = value;
653
0
  if(!curlx_str_cspn(&p, &alpn, ";\n\r")) {
654
0
    curlx_str_trimblanks(&alpn);
655
    /* "clear" is a magic keyword */
656
0
    if(curlx_str_casecompare2(&alpn, STRCONST("clear"))) {
657
      /* Flush cached alternatives for this source origin */
658
0
      altsvc_flush(asi, origin);
659
0
      return CURLE_OK;
660
0
    }
661
0
  }
662
663
  /* Not a standalone "clear", parse from start for alpn entries */
664
0
  for(p = value; *p;) {
665
0
    time_t maxage = 24 * 3600; /* default is 24 hours */
666
0
    bool persist = FALSE;
667
0
    enum alpnid dstalpnid;
668
0
    struct Curl_str dsthost;
669
0
    uint16_t dstport;
670
671
0
    if(curlx_str_until(&p, &alpn, MAX_ALTSVC_LINE, '='))
672
0
      break; /* not another entry, leave */
673
0
    curlx_str_trimblanks(&alpn);
674
0
    if(memchr(curlx_str(&alpn), '%', curlx_strlen(&alpn))) {
675
0
      char *decoded;
676
0
      size_t dlen;
677
      /* RFC 7838 section 3: protocol-id is a percent-encoded ALPN name. */
678
0
      CURLcode result = Curl_urldecode(curlx_str(&alpn), curlx_strlen(&alpn),
679
0
                                       &decoded, &dlen, REJECT_CTRL);
680
0
      if(result == CURLE_URL_MALFORMAT)
681
0
        dstalpnid = ALPN_none;
682
0
      else if(result)
683
0
        return result;
684
0
      else {
685
0
        dstalpnid = Curl_alpn2alpnid((const unsigned char *)decoded, dlen);
686
0
        curlx_free(decoded);
687
0
      }
688
0
    }
689
0
    else
690
0
      dstalpnid = Curl_str2alpnid(&alpn);
691
692
0
    if(curlx_str_single(&p, '='))
693
0
      break;
694
695
    /* Parse altsvc hostname:port */
696
0
    if(!altsvc_parse_dest(&p, data, origin, &dsthost, &dstport))
697
0
      break;
698
699
    /* Parse optional parameters */
700
0
    altsvc_parse_params(&p, &maxage, &persist);
701
702
0
    if(dstalpnid) { /* this is a known ALPN id, e.g. not ALPN_none */
703
0
      if(!entries++)
704
        /* Flush cached alternatives for this source origin, if any - when
705
           this is the first entry of the line. */
706
0
        altsvc_flush(asi, origin);
707
708
0
      as = altsvc_createid(origin->hostname, strlen(origin->hostname),
709
0
                           curlx_str(&dsthost),
710
0
                           curlx_strlen(&dsthost),
711
0
                           origin_alpnid, dstalpnid,
712
0
                           origin->port, dstport);
713
0
      if(as) {
714
0
        time_t secs = time(NULL);
715
        /* The expires time also needs to take the Age: value (if any)
716
           into account. [See RFC 7838 section 3.1] */
717
0
        if(maxage > (TIME_T_MAX - secs))
718
0
          as->expires = TIME_T_MAX;
719
0
        else
720
0
          as->expires = maxage + secs;
721
0
        as->persist = persist;
722
0
        altsvc_append(asi, as);
723
0
        infof(data, "Added alt-svc: %.*s:%u over %s",
724
0
              (int)curlx_strlen(&dsthost), curlx_str(&dsthost),
725
0
              dstport, Curl_alpnid2str(dstalpnid));
726
0
      }
727
0
      else
728
0
        return CURLE_OUT_OF_MEMORY;
729
0
    }
730
731
    /* When this is followed by a comma, we expect another entry */
732
0
    if(curlx_str_single(&p, ','))
733
0
      break;
734
0
  }
735
736
0
  return CURLE_OK;
737
0
}
738
739
/*
740
 * Return TRUE on a match
741
 */
742
bool Curl_altsvc_lookup(struct altsvcinfo *asi,
743
                        struct Curl_peer *origin,
744
                        enum alpnid origin_alpnid,
745
                        struct altsvc **dstentry,
746
                        const int versions, /* one or more bits */
747
                        bool *psame_destination)
748
635
{
749
635
  DEBUGASSERT(asi);
750
635
  DEBUGASSERT(origin);
751
635
  DEBUGASSERT(dstentry);
752
635
  *psame_destination = FALSE;
753
754
635
  if(Curl_llist_count(&asi->list)) {
755
0
    struct Curl_llist_node *e;
756
0
    struct Curl_llist_node *n;
757
0
    time_t now = time(NULL);
758
759
0
    for(e = Curl_llist_head(&asi->list); e; e = n) {
760
0
      struct altsvc *as = Curl_node_elem(e);
761
0
      n = Curl_node_next(e);
762
0
      if(as->expires < now) {
763
        /* an expired entry, remove */
764
0
        Curl_node_remove(e);
765
0
        altsvc_free(as);
766
0
        continue;
767
0
      }
768
0
      if((origin_alpnid == as->src.alpnid) &&
769
0
         (versions & (int)as->dst.alpnid) &&
770
0
         (origin->port == as->src.port) &&
771
0
         hostcompare(origin->hostname, as->src.host)) {
772
        /* match */
773
0
        *dstentry = as;
774
        /* alt-svc on the same host+port or another one? */
775
0
        *psame_destination = (origin->port == as->dst.port) &&
776
0
                             hostcompare(origin->hostname, as->dst.host);
777
0
        return TRUE;
778
0
      }
779
0
    }
780
0
  }
781
635
  return FALSE;
782
635
}
783
784
#if defined(DEBUGBUILD) || defined(UNITTESTS)
785
#undef time
786
#endif
787
788
#endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */