altsvc.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2019 - 2022, 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. ***************************************************************************/
  22. /*
  23. * The Alt-Svc: header is defined in RFC 7838:
  24. * https://datatracker.ietf.org/doc/html/rfc7838
  25. */
  26. #include "curl_setup.h"
  27. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_ALTSVC)
  28. #include <curl/curl.h>
  29. #include "urldata.h"
  30. #include "altsvc.h"
  31. #include "curl_get_line.h"
  32. #include "strcase.h"
  33. #include "parsedate.h"
  34. #include "sendf.h"
  35. #include "warnless.h"
  36. #include "rand.h"
  37. #include "rename.h"
  38. /* The last 3 #include files should be in this order */
  39. #include "curl_printf.h"
  40. #include "curl_memory.h"
  41. #include "memdebug.h"
  42. #define MAX_ALTSVC_LINE 4095
  43. #define MAX_ALTSVC_DATELENSTR "64"
  44. #define MAX_ALTSVC_DATELEN 64
  45. #define MAX_ALTSVC_HOSTLENSTR "512"
  46. #define MAX_ALTSVC_HOSTLEN 512
  47. #define MAX_ALTSVC_ALPNLENSTR "10"
  48. #define MAX_ALTSVC_ALPNLEN 10
  49. #if defined(USE_QUICHE) && !defined(UNITTESTS)
  50. #define H3VERSION "h3-29"
  51. #elif defined(USE_NGTCP2) && !defined(UNITTESTS)
  52. #define H3VERSION "h3-29"
  53. #elif defined(USE_MSH3) && !defined(UNITTESTS)
  54. #define H3VERSION "h3-29"
  55. #else
  56. #define H3VERSION "h3"
  57. #endif
  58. static enum alpnid alpn2alpnid(char *name)
  59. {
  60. if(strcasecompare(name, "h1"))
  61. return ALPN_h1;
  62. if(strcasecompare(name, "h2"))
  63. return ALPN_h2;
  64. if(strcasecompare(name, H3VERSION))
  65. return ALPN_h3;
  66. return ALPN_none; /* unknown, probably rubbish input */
  67. }
  68. /* Given the ALPN ID, return the name */
  69. const char *Curl_alpnid2str(enum alpnid id)
  70. {
  71. switch(id) {
  72. case ALPN_h1:
  73. return "h1";
  74. case ALPN_h2:
  75. return "h2";
  76. case ALPN_h3:
  77. return H3VERSION;
  78. default:
  79. return ""; /* bad */
  80. }
  81. }
  82. static void altsvc_free(struct altsvc *as)
  83. {
  84. free(as->src.host);
  85. free(as->dst.host);
  86. free(as);
  87. }
  88. static struct altsvc *altsvc_createid(const char *srchost,
  89. const char *dsthost,
  90. enum alpnid srcalpnid,
  91. enum alpnid dstalpnid,
  92. unsigned int srcport,
  93. unsigned int dstport)
  94. {
  95. struct altsvc *as = calloc(sizeof(struct altsvc), 1);
  96. if(!as)
  97. return NULL;
  98. as->src.host = strdup(srchost);
  99. if(!as->src.host)
  100. goto error;
  101. as->dst.host = strdup(dsthost);
  102. if(!as->dst.host)
  103. goto error;
  104. as->src.alpnid = srcalpnid;
  105. as->dst.alpnid = dstalpnid;
  106. as->src.port = curlx_ultous(srcport);
  107. as->dst.port = curlx_ultous(dstport);
  108. return as;
  109. error:
  110. altsvc_free(as);
  111. return NULL;
  112. }
  113. static struct altsvc *altsvc_create(char *srchost,
  114. char *dsthost,
  115. char *srcalpn,
  116. char *dstalpn,
  117. unsigned int srcport,
  118. unsigned int dstport)
  119. {
  120. enum alpnid dstalpnid = alpn2alpnid(dstalpn);
  121. enum alpnid srcalpnid = alpn2alpnid(srcalpn);
  122. if(!srcalpnid || !dstalpnid)
  123. return NULL;
  124. return altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid,
  125. srcport, dstport);
  126. }
  127. /* only returns SERIOUS errors */
  128. static CURLcode altsvc_add(struct altsvcinfo *asi, char *line)
  129. {
  130. /* Example line:
  131. h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
  132. */
  133. char srchost[MAX_ALTSVC_HOSTLEN + 1];
  134. char dsthost[MAX_ALTSVC_HOSTLEN + 1];
  135. char srcalpn[MAX_ALTSVC_ALPNLEN + 1];
  136. char dstalpn[MAX_ALTSVC_ALPNLEN + 1];
  137. char date[MAX_ALTSVC_DATELEN + 1];
  138. unsigned int srcport;
  139. unsigned int dstport;
  140. unsigned int prio;
  141. unsigned int persist;
  142. int rc;
  143. rc = sscanf(line,
  144. "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
  145. "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
  146. "\"%" MAX_ALTSVC_DATELENSTR "[^\"]\" %u %u",
  147. srcalpn, srchost, &srcport,
  148. dstalpn, dsthost, &dstport,
  149. date, &persist, &prio);
  150. if(9 == rc) {
  151. struct altsvc *as;
  152. time_t expires = Curl_getdate_capped(date);
  153. as = altsvc_create(srchost, dsthost, srcalpn, dstalpn, srcport, dstport);
  154. if(as) {
  155. as->expires = expires;
  156. as->prio = prio;
  157. as->persist = persist ? 1 : 0;
  158. Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
  159. }
  160. }
  161. return CURLE_OK;
  162. }
  163. /*
  164. * Load alt-svc entries from the given file. The text based line-oriented file
  165. * format is documented here:
  166. * https://github.com/curl/curl/wiki/QUIC-implementation
  167. *
  168. * This function only returns error on major problems that prevents alt-svc
  169. * handling to work completely. It will ignore individual syntactical errors
  170. * etc.
  171. */
  172. static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
  173. {
  174. CURLcode result = CURLE_OK;
  175. char *line = NULL;
  176. FILE *fp;
  177. /* we need a private copy of the file name so that the altsvc cache file
  178. name survives an easy handle reset */
  179. free(asi->filename);
  180. asi->filename = strdup(file);
  181. if(!asi->filename)
  182. return CURLE_OUT_OF_MEMORY;
  183. fp = fopen(file, FOPEN_READTEXT);
  184. if(fp) {
  185. line = malloc(MAX_ALTSVC_LINE);
  186. if(!line)
  187. goto fail;
  188. while(Curl_get_line(line, MAX_ALTSVC_LINE, fp)) {
  189. char *lineptr = line;
  190. while(*lineptr && ISBLANK(*lineptr))
  191. lineptr++;
  192. if(*lineptr == '#')
  193. /* skip commented lines */
  194. continue;
  195. altsvc_add(asi, lineptr);
  196. }
  197. free(line); /* free the line buffer */
  198. fclose(fp);
  199. }
  200. return result;
  201. fail:
  202. Curl_safefree(asi->filename);
  203. free(line);
  204. fclose(fp);
  205. return CURLE_OUT_OF_MEMORY;
  206. }
  207. /*
  208. * Write this single altsvc entry to a single output line
  209. */
  210. static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
  211. {
  212. struct tm stamp;
  213. CURLcode result = Curl_gmtime(as->expires, &stamp);
  214. if(result)
  215. return result;
  216. fprintf(fp,
  217. "%s %s %u "
  218. "%s %s %u "
  219. "\"%d%02d%02d "
  220. "%02d:%02d:%02d\" "
  221. "%u %d\n",
  222. Curl_alpnid2str(as->src.alpnid), as->src.host, as->src.port,
  223. Curl_alpnid2str(as->dst.alpnid), as->dst.host, as->dst.port,
  224. stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
  225. stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
  226. as->persist, as->prio);
  227. return CURLE_OK;
  228. }
  229. /* ---- library-wide functions below ---- */
  230. /*
  231. * Curl_altsvc_init() creates a new altsvc cache.
  232. * It returns the new instance or NULL if something goes wrong.
  233. */
  234. struct altsvcinfo *Curl_altsvc_init(void)
  235. {
  236. struct altsvcinfo *asi = calloc(sizeof(struct altsvcinfo), 1);
  237. if(!asi)
  238. return NULL;
  239. Curl_llist_init(&asi->list, NULL);
  240. /* set default behavior */
  241. asi->flags = CURLALTSVC_H1
  242. #ifdef USE_HTTP2
  243. | CURLALTSVC_H2
  244. #endif
  245. #ifdef ENABLE_QUIC
  246. | CURLALTSVC_H3
  247. #endif
  248. ;
  249. return asi;
  250. }
  251. /*
  252. * Curl_altsvc_load() loads alt-svc from file.
  253. */
  254. CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
  255. {
  256. CURLcode result;
  257. DEBUGASSERT(asi);
  258. result = altsvc_load(asi, file);
  259. return result;
  260. }
  261. /*
  262. * Curl_altsvc_ctrl() passes on the external bitmask.
  263. */
  264. CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl)
  265. {
  266. DEBUGASSERT(asi);
  267. if(!ctrl)
  268. /* unexpected */
  269. return CURLE_BAD_FUNCTION_ARGUMENT;
  270. asi->flags = ctrl;
  271. return CURLE_OK;
  272. }
  273. /*
  274. * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
  275. * resources.
  276. */
  277. void Curl_altsvc_cleanup(struct altsvcinfo **altsvcp)
  278. {
  279. struct Curl_llist_element *e;
  280. struct Curl_llist_element *n;
  281. if(*altsvcp) {
  282. struct altsvcinfo *altsvc = *altsvcp;
  283. for(e = altsvc->list.head; e; e = n) {
  284. struct altsvc *as = e->ptr;
  285. n = e->next;
  286. altsvc_free(as);
  287. }
  288. free(altsvc->filename);
  289. free(altsvc);
  290. *altsvcp = NULL; /* clear the pointer */
  291. }
  292. }
  293. /*
  294. * Curl_altsvc_save() writes the altsvc cache to a file.
  295. */
  296. CURLcode Curl_altsvc_save(struct Curl_easy *data,
  297. struct altsvcinfo *altsvc, const char *file)
  298. {
  299. struct Curl_llist_element *e;
  300. struct Curl_llist_element *n;
  301. CURLcode result = CURLE_OK;
  302. FILE *out;
  303. char *tempstore;
  304. unsigned char randsuffix[9];
  305. if(!altsvc)
  306. /* no cache activated */
  307. return CURLE_OK;
  308. /* if not new name is given, use the one we stored from the load */
  309. if(!file && altsvc->filename)
  310. file = altsvc->filename;
  311. if((altsvc->flags & CURLALTSVC_READONLYFILE) || !file || !file[0])
  312. /* marked as read-only, no file or zero length file name */
  313. return CURLE_OK;
  314. if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix)))
  315. return CURLE_FAILED_INIT;
  316. tempstore = aprintf("%s.%s.tmp", file, randsuffix);
  317. if(!tempstore)
  318. return CURLE_OUT_OF_MEMORY;
  319. out = fopen(tempstore, FOPEN_WRITETEXT);
  320. if(!out)
  321. result = CURLE_WRITE_ERROR;
  322. else {
  323. fputs("# Your alt-svc cache. https://curl.se/docs/alt-svc.html\n"
  324. "# This file was generated by libcurl! Edit at your own risk.\n",
  325. out);
  326. for(e = altsvc->list.head; e; e = n) {
  327. struct altsvc *as = e->ptr;
  328. n = e->next;
  329. result = altsvc_out(as, out);
  330. if(result)
  331. break;
  332. }
  333. fclose(out);
  334. if(!result && Curl_rename(tempstore, file))
  335. result = CURLE_WRITE_ERROR;
  336. if(result)
  337. unlink(tempstore);
  338. }
  339. free(tempstore);
  340. return result;
  341. }
  342. static CURLcode getalnum(const char **ptr, char *alpnbuf, size_t buflen)
  343. {
  344. size_t len;
  345. const char *protop;
  346. const char *p = *ptr;
  347. while(*p && ISBLANK(*p))
  348. p++;
  349. protop = p;
  350. while(*p && !ISBLANK(*p) && (*p != ';') && (*p != '='))
  351. p++;
  352. len = p - protop;
  353. *ptr = p;
  354. if(!len || (len >= buflen))
  355. return CURLE_BAD_FUNCTION_ARGUMENT;
  356. memcpy(alpnbuf, protop, len);
  357. alpnbuf[len] = 0;
  358. return CURLE_OK;
  359. }
  360. /* altsvc_flush() removes all alternatives for this source origin from the
  361. list */
  362. static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid,
  363. const char *srchost, unsigned short srcport)
  364. {
  365. struct Curl_llist_element *e;
  366. struct Curl_llist_element *n;
  367. for(e = asi->list.head; e; e = n) {
  368. struct altsvc *as = e->ptr;
  369. n = e->next;
  370. if((srcalpnid == as->src.alpnid) &&
  371. (srcport == as->src.port) &&
  372. strcasecompare(srchost, as->src.host)) {
  373. Curl_llist_remove(&asi->list, e, NULL);
  374. altsvc_free(as);
  375. }
  376. }
  377. }
  378. #ifdef DEBUGBUILD
  379. /* to play well with debug builds, we can *set* a fixed time this will
  380. return */
  381. static time_t debugtime(void *unused)
  382. {
  383. char *timestr = getenv("CURL_TIME");
  384. (void)unused;
  385. if(timestr) {
  386. unsigned long val = strtol(timestr, NULL, 10);
  387. return (time_t)val;
  388. }
  389. return time(NULL);
  390. }
  391. #define time(x) debugtime(x)
  392. #endif
  393. #define ISNEWLINE(x) (((x) == '\n') || (x) == '\r')
  394. /*
  395. * Curl_altsvc_parse() takes an incoming alt-svc response header and stores
  396. * the data correctly in the cache.
  397. *
  398. * 'value' points to the header *value*. That's contents to the right of the
  399. * header name.
  400. *
  401. * Currently this function rejects invalid data without returning an error.
  402. * Invalid host name, port number will result in the specific alternative
  403. * being rejected. Unknown protocols are skipped.
  404. */
  405. CURLcode Curl_altsvc_parse(struct Curl_easy *data,
  406. struct altsvcinfo *asi, const char *value,
  407. enum alpnid srcalpnid, const char *srchost,
  408. unsigned short srcport)
  409. {
  410. const char *p = value;
  411. size_t len;
  412. char namebuf[MAX_ALTSVC_HOSTLEN] = "";
  413. char alpnbuf[MAX_ALTSVC_ALPNLEN] = "";
  414. struct altsvc *as;
  415. unsigned short dstport = srcport; /* the same by default */
  416. CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
  417. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  418. (void)data;
  419. #endif
  420. if(result) {
  421. infof(data, "Excessive alt-svc header, ignoring.");
  422. return CURLE_OK;
  423. }
  424. DEBUGASSERT(asi);
  425. /* Flush all cached alternatives for this source origin, if any */
  426. altsvc_flush(asi, srcalpnid, srchost, srcport);
  427. /* "clear" is a magic keyword */
  428. if(strcasecompare(alpnbuf, "clear")) {
  429. return CURLE_OK;
  430. }
  431. do {
  432. if(*p == '=') {
  433. /* [protocol]="[host][:port]" */
  434. enum alpnid dstalpnid = alpn2alpnid(alpnbuf); /* the same by default */
  435. p++;
  436. if(*p == '\"') {
  437. const char *dsthost = "";
  438. const char *value_ptr;
  439. char option[32];
  440. unsigned long num;
  441. char *end_ptr;
  442. bool quoted = FALSE;
  443. time_t maxage = 24 * 3600; /* default is 24 hours */
  444. bool persist = FALSE;
  445. p++;
  446. if(*p != ':') {
  447. /* host name starts here */
  448. const char *hostp = p;
  449. while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-')))
  450. p++;
  451. len = p - hostp;
  452. if(!len || (len >= MAX_ALTSVC_HOSTLEN)) {
  453. infof(data, "Excessive alt-svc host name, ignoring.");
  454. dstalpnid = ALPN_none;
  455. }
  456. else {
  457. memcpy(namebuf, hostp, len);
  458. namebuf[len] = 0;
  459. dsthost = namebuf;
  460. }
  461. }
  462. else {
  463. /* no destination name, use source host */
  464. dsthost = srchost;
  465. }
  466. if(*p == ':') {
  467. /* a port number */
  468. unsigned long port = strtoul(++p, &end_ptr, 10);
  469. if(port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') {
  470. infof(data, "Unknown alt-svc port number, ignoring.");
  471. dstalpnid = ALPN_none;
  472. }
  473. p = end_ptr;
  474. dstport = curlx_ultous(port);
  475. }
  476. if(*p++ != '\"')
  477. break;
  478. /* Handle the optional 'ma' and 'persist' flags. Unknown flags
  479. are skipped. */
  480. for(;;) {
  481. while(ISBLANK(*p))
  482. p++;
  483. if(*p != ';')
  484. break;
  485. p++; /* pass the semicolon */
  486. if(!*p || ISNEWLINE(*p))
  487. break;
  488. result = getalnum(&p, option, sizeof(option));
  489. if(result) {
  490. /* skip option if name is too long */
  491. option[0] = '\0';
  492. }
  493. while(*p && ISBLANK(*p))
  494. p++;
  495. if(*p != '=')
  496. return CURLE_OK;
  497. p++;
  498. while(*p && ISBLANK(*p))
  499. p++;
  500. if(!*p)
  501. return CURLE_OK;
  502. if(*p == '\"') {
  503. /* quoted value */
  504. p++;
  505. quoted = TRUE;
  506. }
  507. value_ptr = p;
  508. if(quoted) {
  509. while(*p && *p != '\"')
  510. p++;
  511. if(!*p++)
  512. return CURLE_OK;
  513. }
  514. else {
  515. while(*p && !ISBLANK(*p) && *p!= ';' && *p != ',')
  516. p++;
  517. }
  518. num = strtoul(value_ptr, &end_ptr, 10);
  519. if((end_ptr != value_ptr) && (num < ULONG_MAX)) {
  520. if(strcasecompare("ma", option))
  521. maxage = num;
  522. else if(strcasecompare("persist", option) && (num == 1))
  523. persist = TRUE;
  524. }
  525. }
  526. if(dstalpnid) {
  527. as = altsvc_createid(srchost, dsthost,
  528. srcalpnid, dstalpnid,
  529. srcport, dstport);
  530. if(as) {
  531. /* The expires time also needs to take the Age: value (if any) into
  532. account. [See RFC 7838 section 3.1] */
  533. as->expires = maxage + time(NULL);
  534. as->persist = persist;
  535. Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
  536. infof(data, "Added alt-svc: %s:%d over %s", dsthost, dstport,
  537. Curl_alpnid2str(dstalpnid));
  538. }
  539. }
  540. else {
  541. infof(data, "Unknown alt-svc protocol \"%s\", skipping.",
  542. alpnbuf);
  543. }
  544. }
  545. else
  546. break;
  547. /* after the double quote there can be a comma if there's another
  548. string or a semicolon if no more */
  549. if(*p == ',') {
  550. /* comma means another alternative is presented */
  551. p++;
  552. result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
  553. if(result)
  554. break;
  555. }
  556. }
  557. else
  558. break;
  559. } while(*p && (*p != ';') && (*p != '\n') && (*p != '\r'));
  560. return CURLE_OK;
  561. }
  562. /*
  563. * Return TRUE on a match
  564. */
  565. bool Curl_altsvc_lookup(struct altsvcinfo *asi,
  566. enum alpnid srcalpnid, const char *srchost,
  567. int srcport,
  568. struct altsvc **dstentry,
  569. const int versions) /* one or more bits */
  570. {
  571. struct Curl_llist_element *e;
  572. struct Curl_llist_element *n;
  573. time_t now = time(NULL);
  574. DEBUGASSERT(asi);
  575. DEBUGASSERT(srchost);
  576. DEBUGASSERT(dstentry);
  577. for(e = asi->list.head; e; e = n) {
  578. struct altsvc *as = e->ptr;
  579. n = e->next;
  580. if(as->expires < now) {
  581. /* an expired entry, remove */
  582. Curl_llist_remove(&asi->list, e, NULL);
  583. altsvc_free(as);
  584. continue;
  585. }
  586. if((as->src.alpnid == srcalpnid) &&
  587. strcasecompare(as->src.host, srchost) &&
  588. (as->src.port == srcport) &&
  589. (versions & as->dst.alpnid)) {
  590. /* match */
  591. *dstentry = as;
  592. return TRUE;
  593. }
  594. }
  595. return FALSE;
  596. }
  597. #endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_ALTSVC */