1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2019 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 * SPDX-License-Identifier: curl
23 ***************************************************************************/
25 * The Alt-Svc: header is defined in RFC 7838:
26 * https://datatracker.ietf.org/doc/html/rfc7838
28 #include "curl_setup.h"
30 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
31 #include <curl/curl.h>
34 #include "curl_get_line.h"
36 #include "parsedate.h"
42 /* The last 3 #include files should be in this order */
43 #include "curl_printf.h"
44 #include "curl_memory.h"
47 #define MAX_ALTSVC_LINE 4095
48 #define MAX_ALTSVC_DATELENSTR "64"
49 #define MAX_ALTSVC_DATELEN 64
50 #define MAX_ALTSVC_HOSTLENSTR "512"
51 #define MAX_ALTSVC_HOSTLEN 512
52 #define MAX_ALTSVC_ALPNLENSTR "10"
53 #define MAX_ALTSVC_ALPNLEN 10
55 #define H3VERSION "h3"
57 static enum alpnid alpn2alpnid(char *name)
59 if(strcasecompare(name, "h1"))
61 if(strcasecompare(name, "h2"))
63 if(strcasecompare(name, H3VERSION))
65 return ALPN_none; /* unknown, probably rubbish input */
68 /* Given the ALPN ID, return the name */
69 const char *Curl_alpnid2str(enum alpnid id)
84 static void altsvc_free(struct altsvc *as)
91 static struct altsvc *altsvc_createid(const char *srchost,
93 enum alpnid srcalpnid,
94 enum alpnid dstalpnid,
98 struct altsvc *as = calloc(sizeof(struct altsvc), 1);
102 hlen = strlen(srchost);
104 as->src.host = strdup(srchost);
107 if(hlen && (srchost[hlen - 1] == '.'))
108 /* strip off trailing any dot */
109 as->src.host[--hlen] = 0;
110 as->dst.host = strdup(dsthost);
114 as->src.alpnid = srcalpnid;
115 as->dst.alpnid = dstalpnid;
116 as->src.port = curlx_ultous(srcport);
117 as->dst.port = curlx_ultous(dstport);
125 static struct altsvc *altsvc_create(char *srchost,
129 unsigned int srcport,
130 unsigned int dstport)
132 enum alpnid dstalpnid = alpn2alpnid(dstalpn);
133 enum alpnid srcalpnid = alpn2alpnid(srcalpn);
134 if(!srcalpnid || !dstalpnid)
136 return altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid,
140 /* only returns SERIOUS errors */
141 static CURLcode altsvc_add(struct altsvcinfo *asi, char *line)
144 h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
146 char srchost[MAX_ALTSVC_HOSTLEN + 1];
147 char dsthost[MAX_ALTSVC_HOSTLEN + 1];
148 char srcalpn[MAX_ALTSVC_ALPNLEN + 1];
149 char dstalpn[MAX_ALTSVC_ALPNLEN + 1];
150 char date[MAX_ALTSVC_DATELEN + 1];
151 unsigned int srcport;
152 unsigned int dstport;
154 unsigned int persist;
158 "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
159 "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
160 "\"%" MAX_ALTSVC_DATELENSTR "[^\"]\" %u %u",
161 srcalpn, srchost, &srcport,
162 dstalpn, dsthost, &dstport,
163 date, &persist, &prio);
166 time_t expires = Curl_getdate_capped(date);
167 as = altsvc_create(srchost, dsthost, srcalpn, dstalpn, srcport, dstport);
169 as->expires = expires;
171 as->persist = persist ? 1 : 0;
172 Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
180 * Load alt-svc entries from the given file. The text based line-oriented file
181 * format is documented here: https://curl.se/docs/alt-svc.html
183 * This function only returns error on major problems that prevent alt-svc
184 * handling to work completely. It will ignore individual syntactical errors
187 static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
189 CURLcode result = CURLE_OK;
193 /* we need a private copy of the file name so that the altsvc cache file
194 name survives an easy handle reset */
196 asi->filename = strdup(file);
198 return CURLE_OUT_OF_MEMORY;
200 fp = fopen(file, FOPEN_READTEXT);
202 line = malloc(MAX_ALTSVC_LINE);
205 while(Curl_get_line(line, MAX_ALTSVC_LINE, fp)) {
206 char *lineptr = line;
207 while(*lineptr && ISBLANK(*lineptr))
210 /* skip commented lines */
213 altsvc_add(asi, lineptr);
215 free(line); /* free the line buffer */
221 Curl_safefree(asi->filename);
224 return CURLE_OUT_OF_MEMORY;
228 * Write this single altsvc entry to a single output line
231 static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
234 CURLcode result = Curl_gmtime(as->expires, &stamp);
244 Curl_alpnid2str(as->src.alpnid), as->src.host, as->src.port,
245 Curl_alpnid2str(as->dst.alpnid), as->dst.host, as->dst.port,
246 stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
247 stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
248 as->persist, as->prio);
252 /* ---- library-wide functions below ---- */
255 * Curl_altsvc_init() creates a new altsvc cache.
256 * It returns the new instance or NULL if something goes wrong.
258 struct altsvcinfo *Curl_altsvc_init(void)
260 struct altsvcinfo *asi = calloc(sizeof(struct altsvcinfo), 1);
263 Curl_llist_init(&asi->list, NULL);
265 /* set default behavior */
266 asi->flags = CURLALTSVC_H1
278 * Curl_altsvc_load() loads alt-svc from file.
280 CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
284 result = altsvc_load(asi, file);
289 * Curl_altsvc_ctrl() passes on the external bitmask.
291 CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl)
296 return CURLE_BAD_FUNCTION_ARGUMENT;
302 * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
305 void Curl_altsvc_cleanup(struct altsvcinfo **altsvcp)
307 struct Curl_llist_element *e;
308 struct Curl_llist_element *n;
310 struct altsvcinfo *altsvc = *altsvcp;
311 for(e = altsvc->list.head; e; e = n) {
312 struct altsvc *as = e->ptr;
316 free(altsvc->filename);
318 *altsvcp = NULL; /* clear the pointer */
323 * Curl_altsvc_save() writes the altsvc cache to a file.
325 CURLcode Curl_altsvc_save(struct Curl_easy *data,
326 struct altsvcinfo *altsvc, const char *file)
328 struct Curl_llist_element *e;
329 struct Curl_llist_element *n;
330 CURLcode result = CURLE_OK;
332 char *tempstore = NULL;
335 /* no cache activated */
338 /* if not new name is given, use the one we stored from the load */
339 if(!file && altsvc->filename)
340 file = altsvc->filename;
342 if((altsvc->flags & CURLALTSVC_READONLYFILE) || !file || !file[0])
343 /* marked as read-only, no file or zero length file name */
346 result = Curl_fopen(data, file, &out, &tempstore);
348 fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n"
349 "# This file was generated by libcurl! Edit at your own risk.\n",
351 for(e = altsvc->list.head; e; e = n) {
352 struct altsvc *as = e->ptr;
354 result = altsvc_out(as, out);
359 if(!result && tempstore && Curl_rename(tempstore, file))
360 result = CURLE_WRITE_ERROR;
362 if(result && tempstore)
369 static CURLcode getalnum(const char **ptr, char *alpnbuf, size_t buflen)
373 const char *p = *ptr;
374 while(*p && ISBLANK(*p))
377 while(*p && !ISBLANK(*p) && (*p != ';') && (*p != '='))
382 if(!len || (len >= buflen))
383 return CURLE_BAD_FUNCTION_ARGUMENT;
384 memcpy(alpnbuf, protop, len);
389 /* hostcompare() returns true if 'host' matches 'check'. The first host
390 * argument may have a trailing dot present that will be ignored.
392 static bool hostcompare(const char *host, const char *check)
394 size_t hlen = strlen(host);
395 size_t clen = strlen(check);
397 if(hlen && (host[hlen - 1] == '.'))
400 /* they can't match if they have different lengths */
402 return strncasecompare(host, check, hlen);
405 /* altsvc_flush() removes all alternatives for this source origin from the
407 static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid,
408 const char *srchost, unsigned short srcport)
410 struct Curl_llist_element *e;
411 struct Curl_llist_element *n;
412 for(e = asi->list.head; e; e = n) {
413 struct altsvc *as = e->ptr;
415 if((srcalpnid == as->src.alpnid) &&
416 (srcport == as->src.port) &&
417 hostcompare(srchost, as->src.host)) {
418 Curl_llist_remove(&asi->list, e, NULL);
425 /* to play well with debug builds, we can *set* a fixed time this will
427 static time_t debugtime(void *unused)
429 char *timestr = getenv("CURL_TIME");
432 unsigned long val = strtol(timestr, NULL, 10);
437 #define time(x) debugtime(x)
440 #define ISNEWLINE(x) (((x) == '\n') || (x) == '\r')
443 * Curl_altsvc_parse() takes an incoming alt-svc response header and stores
444 * the data correctly in the cache.
446 * 'value' points to the header *value*. That's contents to the right of the
449 * Currently this function rejects invalid data without returning an error.
450 * Invalid host name, port number will result in the specific alternative
451 * being rejected. Unknown protocols are skipped.
453 CURLcode Curl_altsvc_parse(struct Curl_easy *data,
454 struct altsvcinfo *asi, const char *value,
455 enum alpnid srcalpnid, const char *srchost,
456 unsigned short srcport)
458 const char *p = value;
460 char namebuf[MAX_ALTSVC_HOSTLEN] = "";
461 char alpnbuf[MAX_ALTSVC_ALPNLEN] = "";
463 unsigned short dstport = srcport; /* the same by default */
464 CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
466 #ifdef CURL_DISABLE_VERBOSE_STRINGS
470 infof(data, "Excessive alt-svc header, ignoring.");
476 /* "clear" is a magic keyword */
477 if(strcasecompare(alpnbuf, "clear")) {
478 /* Flush cached alternatives for this source origin */
479 altsvc_flush(asi, srcalpnid, srchost, srcport);
485 /* [protocol]="[host][:port]" */
486 enum alpnid dstalpnid = alpn2alpnid(alpnbuf); /* the same by default */
489 const char *dsthost = "";
490 const char *value_ptr;
495 time_t maxage = 24 * 3600; /* default is 24 hours */
496 bool persist = FALSE;
500 /* host name starts here */
501 const char *hostp = p;
502 while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-')))
505 if(!len || (len >= MAX_ALTSVC_HOSTLEN)) {
506 infof(data, "Excessive alt-svc host name, ignoring.");
510 memcpy(namebuf, hostp, len);
516 /* no destination name, use source host */
521 unsigned long port = strtoul(++p, &end_ptr, 10);
522 if(port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') {
523 infof(data, "Unknown alt-svc port number, ignoring.");
527 dstport = curlx_ultous(port);
532 /* Handle the optional 'ma' and 'persist' flags. Unknown flags
539 p++; /* pass the semicolon */
540 if(!*p || ISNEWLINE(*p))
542 result = getalnum(&p, option, sizeof(option));
544 /* skip option if name is too long */
547 while(*p && ISBLANK(*p))
552 while(*p && ISBLANK(*p))
563 while(*p && *p != '\"')
569 while(*p && !ISBLANK(*p) && *p!= ';' && *p != ',')
572 num = strtoul(value_ptr, &end_ptr, 10);
573 if((end_ptr != value_ptr) && (num < ULONG_MAX)) {
574 if(strcasecompare("ma", option))
576 else if(strcasecompare("persist", option) && (num == 1))
580 if(dstalpnid && valid) {
582 /* Flush cached alternatives for this source origin, if any - when
583 this is the first entry of the line. */
584 altsvc_flush(asi, srcalpnid, srchost, srcport);
586 as = altsvc_createid(srchost, dsthost,
587 srcalpnid, dstalpnid,
590 /* The expires time also needs to take the Age: value (if any) into
591 account. [See RFC 7838 section 3.1] */
592 as->expires = maxage + time(NULL);
593 as->persist = persist;
594 Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
595 infof(data, "Added alt-svc: %s:%d over %s", dsthost, dstport,
596 Curl_alpnid2str(dstalpnid));
602 /* after the double quote there can be a comma if there's another
603 string or a semicolon if no more */
605 /* comma means another alternative is presented */
607 result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
614 } while(*p && (*p != ';') && (*p != '\n') && (*p != '\r'));
620 * Return TRUE on a match
622 bool Curl_altsvc_lookup(struct altsvcinfo *asi,
623 enum alpnid srcalpnid, const char *srchost,
625 struct altsvc **dstentry,
626 const int versions) /* one or more bits */
628 struct Curl_llist_element *e;
629 struct Curl_llist_element *n;
630 time_t now = time(NULL);
632 DEBUGASSERT(srchost);
633 DEBUGASSERT(dstentry);
635 for(e = asi->list.head; e; e = n) {
636 struct altsvc *as = e->ptr;
638 if(as->expires < now) {
639 /* an expired entry, remove */
640 Curl_llist_remove(&asi->list, e, NULL);
644 if((as->src.alpnid == srcalpnid) &&
645 hostcompare(srchost, as->src.host) &&
646 (as->src.port == srcport) &&
647 (versions & as->dst.alpnid)) {
656 #endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */