2
0

doh.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  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. #ifndef CURL_DISABLE_DOH
  26. #include "urldata.h"
  27. #include "curl_addrinfo.h"
  28. #include "doh.h"
  29. #include "sendf.h"
  30. #include "multiif.h"
  31. #include "url.h"
  32. #include "share.h"
  33. #include "curl_base64.h"
  34. #include "connect.h"
  35. #include "strdup.h"
  36. #include "dynbuf.h"
  37. /* The last 3 #include files should be in this order */
  38. #include "curl_printf.h"
  39. #include "curl_memory.h"
  40. #include "memdebug.h"
  41. #include "escape.h"
  42. #define DNS_CLASS_IN 0x01
  43. /* doh_print_buf truncates if the hex string will be more than this */
  44. #define LOCAL_PB_HEXMAX 400
  45. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  46. static const char * const errors[]={
  47. "",
  48. "Bad label",
  49. "Out of range",
  50. "Label loop",
  51. "Too small",
  52. "Out of memory",
  53. "RDATA length",
  54. "Malformat",
  55. "Bad RCODE",
  56. "Unexpected TYPE",
  57. "Unexpected CLASS",
  58. "No content",
  59. "Bad ID",
  60. "Name too long"
  61. };
  62. static const char *doh_strerror(DOHcode code)
  63. {
  64. if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG))
  65. return errors[code];
  66. return "bad error code";
  67. }
  68. struct curl_trc_feat Curl_doh_trc = {
  69. "DoH",
  70. CURL_LOG_LVL_NONE,
  71. };
  72. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  73. /* @unittest 1655
  74. */
  75. UNITTEST DOHcode doh_req_encode(const char *host,
  76. DNStype dnstype,
  77. unsigned char *dnsp, /* buffer */
  78. size_t len, /* buffer size */
  79. size_t *olen) /* output length */
  80. {
  81. const size_t hostlen = strlen(host);
  82. unsigned char *orig = dnsp;
  83. const char *hostp = host;
  84. /* The expected output length is 16 bytes more than the length of
  85. * the QNAME-encoding of the hostname.
  86. *
  87. * A valid DNS name may not contain a zero-length label, except at
  88. * the end. For this reason, a name beginning with a dot, or
  89. * containing a sequence of two or more consecutive dots, is invalid
  90. * and cannot be encoded as a QNAME.
  91. *
  92. * If the hostname ends with a trailing dot, the corresponding
  93. * QNAME-encoding is one byte longer than the hostname. If (as is
  94. * also valid) the hostname is shortened by the omission of the
  95. * trailing dot, then its QNAME-encoding will be two bytes longer
  96. * than the hostname.
  97. *
  98. * Each [ label, dot ] pair is encoded as [ length, label ],
  99. * preserving overall length. A final [ label ] without a dot is
  100. * also encoded as [ length, label ], increasing overall length
  101. * by one. The encoding is completed by appending a zero byte,
  102. * representing the zero-length root label, again increasing
  103. * the overall length by one.
  104. */
  105. size_t expected_len;
  106. DEBUGASSERT(hostlen);
  107. expected_len = 12 + 1 + hostlen + 4;
  108. if(host[hostlen-1]!='.')
  109. expected_len++;
  110. if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
  111. return DOH_DNS_NAME_TOO_LONG;
  112. if(len < expected_len)
  113. return DOH_TOO_SMALL_BUFFER;
  114. *dnsp++ = 0; /* 16 bit id */
  115. *dnsp++ = 0;
  116. *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
  117. *dnsp++ = '\0'; /* |RA| Z | RCODE | */
  118. *dnsp++ = '\0';
  119. *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
  120. *dnsp++ = '\0';
  121. *dnsp++ = '\0'; /* ANCOUNT */
  122. *dnsp++ = '\0';
  123. *dnsp++ = '\0'; /* NSCOUNT */
  124. *dnsp++ = '\0';
  125. *dnsp++ = '\0'; /* ARCOUNT */
  126. /* encode each label and store it in the QNAME */
  127. while(*hostp) {
  128. size_t labellen;
  129. char *dot = strchr(hostp, '.');
  130. if(dot)
  131. labellen = dot - hostp;
  132. else
  133. labellen = strlen(hostp);
  134. if((labellen > 63) || (!labellen)) {
  135. /* label is too long or too short, error out */
  136. *olen = 0;
  137. return DOH_DNS_BAD_LABEL;
  138. }
  139. /* label is non-empty, process it */
  140. *dnsp++ = (unsigned char)labellen;
  141. memcpy(dnsp, hostp, labellen);
  142. dnsp += labellen;
  143. hostp += labellen;
  144. /* advance past dot, but only if there is one */
  145. if(dot)
  146. hostp++;
  147. } /* next label */
  148. *dnsp++ = 0; /* append zero-length label for root */
  149. /* There are assigned TYPE codes beyond 255: use range [1..65535] */
  150. *dnsp++ = (unsigned char)(255 & (dnstype >> 8)); /* upper 8 bit TYPE */
  151. *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
  152. *dnsp++ = '\0'; /* upper 8 bit CLASS */
  153. *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
  154. *olen = dnsp - orig;
  155. /* verify that our estimation of length is valid, since
  156. * this has led to buffer overflows in this function */
  157. DEBUGASSERT(*olen == expected_len);
  158. return DOH_OK;
  159. }
  160. static size_t
  161. doh_write_cb(char *contents, size_t size, size_t nmemb, void *userp)
  162. {
  163. size_t realsize = size * nmemb;
  164. struct dynbuf *mem = (struct dynbuf *)userp;
  165. if(Curl_dyn_addn(mem, contents, realsize))
  166. return 0;
  167. return realsize;
  168. }
  169. #if defined(USE_HTTPSRR) && defined(DEBUGBUILD)
  170. static void doh_print_buf(struct Curl_easy *data,
  171. const char *prefix,
  172. unsigned char *buf, size_t len)
  173. {
  174. unsigned char hexstr[LOCAL_PB_HEXMAX];
  175. size_t hlen = LOCAL_PB_HEXMAX;
  176. bool truncated = FALSE;
  177. if(len > (LOCAL_PB_HEXMAX / 2))
  178. truncated = TRUE;
  179. Curl_hexencode(buf, len, hexstr, hlen);
  180. if(!truncated)
  181. infof(data, "%s: len=%d, val=%s", prefix, (int)len, hexstr);
  182. else
  183. infof(data, "%s: len=%d (truncated)val=%s", prefix, (int)len, hexstr);
  184. return;
  185. }
  186. #endif
  187. /* called from multi.c when this DoH transfer is complete */
  188. static int doh_done(struct Curl_easy *doh, CURLcode result)
  189. {
  190. struct Curl_easy *data; /* the transfer that asked for the DoH probe */
  191. data = Curl_multi_get_handle(doh->multi, doh->set.dohfor_mid);
  192. if(!data) {
  193. DEBUGF(infof(doh, "doh_done: xfer for mid=%" FMT_OFF_T
  194. " not found", doh->set.dohfor_mid));
  195. DEBUGASSERT(0);
  196. }
  197. else {
  198. struct doh_probes *dohp = data->req.doh;
  199. /* one of the DoH request done for the 'data' transfer is now complete! */
  200. dohp->pending--;
  201. infof(doh, "a DoH request is completed, %u to go", dohp->pending);
  202. if(result)
  203. infof(doh, "DoH request %s", curl_easy_strerror(result));
  204. if(!dohp->pending) {
  205. /* DoH completed, run the transfer picking up the results */
  206. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  207. }
  208. }
  209. return 0;
  210. }
  211. #define ERROR_CHECK_SETOPT(x,y) \
  212. do { \
  213. result = curl_easy_setopt((CURL *)doh, x, y); \
  214. if(result && \
  215. result != CURLE_NOT_BUILT_IN && \
  216. result != CURLE_UNKNOWN_OPTION) \
  217. goto error; \
  218. } while(0)
  219. static CURLcode doh_run_probe(struct Curl_easy *data,
  220. struct doh_probe *p, DNStype dnstype,
  221. const char *host,
  222. const char *url, CURLM *multi,
  223. struct curl_slist *headers)
  224. {
  225. struct Curl_easy *doh = NULL;
  226. CURLcode result = CURLE_OK;
  227. timediff_t timeout_ms;
  228. DOHcode d = doh_req_encode(host, dnstype, p->req_body, sizeof(p->req_body),
  229. &p->req_body_len);
  230. if(d) {
  231. failf(data, "Failed to encode DoH packet [%d]", d);
  232. return CURLE_OUT_OF_MEMORY;
  233. }
  234. p->dnstype = dnstype;
  235. Curl_dyn_init(&p->resp_body, DYN_DOH_RESPONSE);
  236. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  237. if(timeout_ms <= 0) {
  238. result = CURLE_OPERATION_TIMEDOUT;
  239. goto error;
  240. }
  241. /* Curl_open() is the internal version of curl_easy_init() */
  242. result = Curl_open(&doh);
  243. if(result)
  244. goto error;
  245. /* pass in the struct pointer via a local variable to please coverity and
  246. the gcc typecheck helpers */
  247. doh->state.internal = TRUE;
  248. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  249. doh->state.feat = &Curl_doh_trc;
  250. #endif
  251. ERROR_CHECK_SETOPT(CURLOPT_URL, url);
  252. ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https");
  253. ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
  254. ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, &p->resp_body);
  255. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->req_body);
  256. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->req_body_len);
  257. ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
  258. #ifdef USE_HTTP2
  259. ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
  260. ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L);
  261. #endif
  262. #ifndef DEBUGBUILD
  263. /* enforce HTTPS if not debug */
  264. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
  265. #else
  266. /* in debug mode, also allow http */
  267. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
  268. #endif
  269. ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
  270. ERROR_CHECK_SETOPT(CURLOPT_SHARE, (CURLSH *)data->share);
  271. if(data->set.err && data->set.err != stderr)
  272. ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err);
  273. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc))
  274. ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
  275. if(data->set.no_signal)
  276. ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
  277. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST,
  278. data->set.doh_verifyhost ? 2L : 0L);
  279. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER,
  280. data->set.doh_verifypeer ? 1L : 0L);
  281. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS,
  282. data->set.doh_verifystatus ? 1L : 0L);
  283. /* Inherit *some* SSL options from the user's transfer. This is a
  284. best-guess as to which options are needed for compatibility. #3661
  285. Note DoH does not inherit the user's proxy server so proxy SSL settings
  286. have no effect and are not inherited. If that changes then two new
  287. options should be added to check doh proxy insecure separately,
  288. CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER.
  289. */
  290. if(data->set.ssl.falsestart)
  291. ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
  292. if(data->set.str[STRING_SSL_CAFILE]) {
  293. ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
  294. data->set.str[STRING_SSL_CAFILE]);
  295. }
  296. if(data->set.blobs[BLOB_CAINFO]) {
  297. ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB,
  298. data->set.blobs[BLOB_CAINFO]);
  299. }
  300. if(data->set.str[STRING_SSL_CAPATH]) {
  301. ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
  302. data->set.str[STRING_SSL_CAPATH]);
  303. }
  304. if(data->set.str[STRING_SSL_CRLFILE]) {
  305. ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
  306. data->set.str[STRING_SSL_CRLFILE]);
  307. }
  308. if(data->set.ssl.certinfo)
  309. ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
  310. if(data->set.ssl.fsslctx)
  311. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
  312. if(data->set.ssl.fsslctxp)
  313. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
  314. if(data->set.fdebug)
  315. ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug);
  316. if(data->set.debugdata)
  317. ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata);
  318. if(data->set.str[STRING_SSL_EC_CURVES]) {
  319. ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
  320. data->set.str[STRING_SSL_EC_CURVES]);
  321. }
  322. {
  323. long mask =
  324. (data->set.ssl.enable_beast ?
  325. CURLSSLOPT_ALLOW_BEAST : 0) |
  326. (data->set.ssl.no_revoke ?
  327. CURLSSLOPT_NO_REVOKE : 0) |
  328. (data->set.ssl.no_partialchain ?
  329. CURLSSLOPT_NO_PARTIALCHAIN : 0) |
  330. (data->set.ssl.revoke_best_effort ?
  331. CURLSSLOPT_REVOKE_BEST_EFFORT : 0) |
  332. (data->set.ssl.native_ca_store ?
  333. CURLSSLOPT_NATIVE_CA : 0) |
  334. (data->set.ssl.auto_client_cert ?
  335. CURLSSLOPT_AUTO_CLIENT_CERT : 0);
  336. (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, mask);
  337. }
  338. doh->set.fmultidone = doh_done;
  339. doh->set.dohfor_mid = data->mid; /* for which transfer this is done */
  340. /* DoH handles must not inherit private_data. The handles may be passed to
  341. the user via callbacks and the user will be able to identify them as
  342. internal handles because private data is not set. The user can then set
  343. private_data via CURLOPT_PRIVATE if they so choose. */
  344. DEBUGASSERT(!doh->set.private_data);
  345. if(curl_multi_add_handle(multi, doh))
  346. goto error;
  347. p->easy_mid = doh->mid;
  348. return CURLE_OK;
  349. error:
  350. Curl_close(&doh);
  351. p->easy_mid = -1;
  352. return result;
  353. }
  354. /*
  355. * Curl_doh() resolves a name using DoH. It resolves a name and returns a
  356. * 'Curl_addrinfo *' with the address information.
  357. */
  358. struct Curl_addrinfo *Curl_doh(struct Curl_easy *data,
  359. const char *hostname,
  360. int port,
  361. int *waitp)
  362. {
  363. CURLcode result = CURLE_OK;
  364. struct doh_probes *dohp;
  365. struct connectdata *conn = data->conn;
  366. size_t i;
  367. #ifdef USE_HTTPSRR
  368. /* for now, this is only used when ECH is enabled */
  369. # ifdef USE_ECH
  370. char *qname = NULL;
  371. # endif
  372. #endif
  373. *waitp = FALSE;
  374. (void)hostname;
  375. (void)port;
  376. DEBUGASSERT(!data->req.doh);
  377. DEBUGASSERT(conn);
  378. /* start clean, consider allocating this struct on demand */
  379. dohp = data->req.doh = calloc(1, sizeof(struct doh_probes));
  380. if(!dohp)
  381. return NULL;
  382. for(i = 0; i < DOH_SLOT_COUNT; ++i) {
  383. dohp->probe[i].easy_mid = -1;
  384. }
  385. conn->bits.doh = TRUE;
  386. dohp->host = hostname;
  387. dohp->port = port;
  388. dohp->req_hds =
  389. curl_slist_append(NULL,
  390. "Content-Type: application/dns-message");
  391. if(!dohp->req_hds)
  392. goto error;
  393. /* create IPv4 DoH request */
  394. result = doh_run_probe(data, &dohp->probe[DOH_SLOT_IPV4],
  395. DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
  396. data->multi, dohp->req_hds);
  397. if(result)
  398. goto error;
  399. dohp->pending++;
  400. #ifdef USE_IPV6
  401. if((conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) {
  402. /* create IPv6 DoH request */
  403. result = doh_run_probe(data, &dohp->probe[DOH_SLOT_IPV6],
  404. DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
  405. data->multi, dohp->req_hds);
  406. if(result)
  407. goto error;
  408. dohp->pending++;
  409. }
  410. #endif
  411. #ifdef USE_HTTPSRR
  412. /*
  413. * TODO: Figure out the conditions under which we want to make
  414. * a request for an HTTPS RR when we are not doing ECH. For now,
  415. * making this request breaks a bunch of DoH tests, e.g. test2100,
  416. * where the additional request does not match the pre-cooked data
  417. * files, so there is a bit of work attached to making the request
  418. * in a non-ECH use-case. For the present, we will only make the
  419. * request when ECH is enabled in the build and is being used for
  420. * the curl operation.
  421. */
  422. # ifdef USE_ECH
  423. if(data->set.tls_ech & CURLECH_ENABLE
  424. || data->set.tls_ech & CURLECH_HARD) {
  425. if(port == 443)
  426. qname = strdup(hostname);
  427. else
  428. qname = aprintf("_%d._https.%s", port, hostname);
  429. if(!qname)
  430. goto error;
  431. result = doh_run_probe(data, &dohp->probe[DOH_SLOT_HTTPS_RR],
  432. DNS_TYPE_HTTPS, qname, data->set.str[STRING_DOH],
  433. data->multi, dohp->req_hds);
  434. Curl_safefree(qname);
  435. if(result)
  436. goto error;
  437. dohp->pending++;
  438. }
  439. # endif
  440. #endif
  441. *waitp = TRUE; /* this never returns synchronously */
  442. return NULL;
  443. error:
  444. Curl_doh_cleanup(data);
  445. return NULL;
  446. }
  447. static DOHcode doh_skipqname(const unsigned char *doh, size_t dohlen,
  448. unsigned int *indexp)
  449. {
  450. unsigned char length;
  451. do {
  452. if(dohlen < (*indexp + 1))
  453. return DOH_DNS_OUT_OF_RANGE;
  454. length = doh[*indexp];
  455. if((length & 0xc0) == 0xc0) {
  456. /* name pointer, advance over it and be done */
  457. if(dohlen < (*indexp + 2))
  458. return DOH_DNS_OUT_OF_RANGE;
  459. *indexp += 2;
  460. break;
  461. }
  462. if(length & 0xc0)
  463. return DOH_DNS_BAD_LABEL;
  464. if(dohlen < (*indexp + 1 + length))
  465. return DOH_DNS_OUT_OF_RANGE;
  466. *indexp += (unsigned int)(1 + length);
  467. } while(length);
  468. return DOH_OK;
  469. }
  470. static unsigned short doh_get16bit(const unsigned char *doh,
  471. unsigned int index)
  472. {
  473. return (unsigned short)((doh[index] << 8) | doh[index + 1]);
  474. }
  475. static unsigned int doh_get32bit(const unsigned char *doh, unsigned int index)
  476. {
  477. /* make clang and gcc optimize this to bswap by incrementing
  478. the pointer first. */
  479. doh += index;
  480. /* avoid undefined behavior by casting to unsigned before shifting
  481. 24 bits, possibly into the sign bit. codegen is same, but
  482. ub sanitizer will not be upset */
  483. return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) |
  484. ((unsigned)doh[2] << 8) | doh[3];
  485. }
  486. static void doh_store_a(const unsigned char *doh, int index,
  487. struct dohentry *d)
  488. {
  489. /* silently ignore addresses over the limit */
  490. if(d->numaddr < DOH_MAX_ADDR) {
  491. struct dohaddr *a = &d->addr[d->numaddr];
  492. a->type = DNS_TYPE_A;
  493. memcpy(&a->ip.v4, &doh[index], 4);
  494. d->numaddr++;
  495. }
  496. }
  497. static void doh_store_aaaa(const unsigned char *doh, int index,
  498. struct dohentry *d)
  499. {
  500. /* silently ignore addresses over the limit */
  501. if(d->numaddr < DOH_MAX_ADDR) {
  502. struct dohaddr *a = &d->addr[d->numaddr];
  503. a->type = DNS_TYPE_AAAA;
  504. memcpy(&a->ip.v6, &doh[index], 16);
  505. d->numaddr++;
  506. }
  507. }
  508. #ifdef USE_HTTPSRR
  509. static DOHcode doh_store_https(const unsigned char *doh, int index,
  510. struct dohentry *d, uint16_t len)
  511. {
  512. /* silently ignore RRs over the limit */
  513. if(d->numhttps_rrs < DOH_MAX_HTTPS) {
  514. struct dohhttps_rr *h = &d->https_rrs[d->numhttps_rrs];
  515. h->val = Curl_memdup(&doh[index], len);
  516. if(!h->val)
  517. return DOH_OUT_OF_MEM;
  518. h->len = len;
  519. d->numhttps_rrs++;
  520. }
  521. return DOH_OK;
  522. }
  523. #endif
  524. static DOHcode doh_store_cname(const unsigned char *doh, size_t dohlen,
  525. unsigned int index, struct dohentry *d)
  526. {
  527. struct dynbuf *c;
  528. unsigned int loop = 128; /* a valid DNS name can never loop this much */
  529. unsigned char length;
  530. if(d->numcname == DOH_MAX_CNAME)
  531. return DOH_OK; /* skip! */
  532. c = &d->cname[d->numcname++];
  533. do {
  534. if(index >= dohlen)
  535. return DOH_DNS_OUT_OF_RANGE;
  536. length = doh[index];
  537. if((length & 0xc0) == 0xc0) {
  538. int newpos;
  539. /* name pointer, get the new offset (14 bits) */
  540. if((index + 1) >= dohlen)
  541. return DOH_DNS_OUT_OF_RANGE;
  542. /* move to the new index */
  543. newpos = (length & 0x3f) << 8 | doh[index + 1];
  544. index = (unsigned int)newpos;
  545. continue;
  546. }
  547. else if(length & 0xc0)
  548. return DOH_DNS_BAD_LABEL; /* bad input */
  549. else
  550. index++;
  551. if(length) {
  552. if(Curl_dyn_len(c)) {
  553. if(Curl_dyn_addn(c, STRCONST(".")))
  554. return DOH_OUT_OF_MEM;
  555. }
  556. if((index + length) > dohlen)
  557. return DOH_DNS_BAD_LABEL;
  558. if(Curl_dyn_addn(c, &doh[index], length))
  559. return DOH_OUT_OF_MEM;
  560. index += length;
  561. }
  562. } while(length && --loop);
  563. if(!loop)
  564. return DOH_DNS_LABEL_LOOP;
  565. return DOH_OK;
  566. }
  567. static DOHcode doh_rdata(const unsigned char *doh,
  568. size_t dohlen,
  569. unsigned short rdlength,
  570. unsigned short type,
  571. int index,
  572. struct dohentry *d)
  573. {
  574. /* RDATA
  575. - A (TYPE 1): 4 bytes
  576. - AAAA (TYPE 28): 16 bytes
  577. - NS (TYPE 2): N bytes
  578. - HTTPS (TYPE 65): N bytes */
  579. DOHcode rc;
  580. switch(type) {
  581. case DNS_TYPE_A:
  582. if(rdlength != 4)
  583. return DOH_DNS_RDATA_LEN;
  584. doh_store_a(doh, index, d);
  585. break;
  586. case DNS_TYPE_AAAA:
  587. if(rdlength != 16)
  588. return DOH_DNS_RDATA_LEN;
  589. doh_store_aaaa(doh, index, d);
  590. break;
  591. #ifdef USE_HTTPSRR
  592. case DNS_TYPE_HTTPS:
  593. rc = doh_store_https(doh, index, d, rdlength);
  594. if(rc)
  595. return rc;
  596. break;
  597. #endif
  598. case DNS_TYPE_CNAME:
  599. rc = doh_store_cname(doh, dohlen, (unsigned int)index, d);
  600. if(rc)
  601. return rc;
  602. break;
  603. case DNS_TYPE_DNAME:
  604. /* explicit for clarity; just skip; rely on synthesized CNAME */
  605. break;
  606. default:
  607. /* unsupported type, just skip it */
  608. break;
  609. }
  610. return DOH_OK;
  611. }
  612. UNITTEST void de_init(struct dohentry *de)
  613. {
  614. int i;
  615. memset(de, 0, sizeof(*de));
  616. de->ttl = INT_MAX;
  617. for(i = 0; i < DOH_MAX_CNAME; i++)
  618. Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
  619. }
  620. UNITTEST DOHcode doh_resp_decode(const unsigned char *doh,
  621. size_t dohlen,
  622. DNStype dnstype,
  623. struct dohentry *d)
  624. {
  625. unsigned char rcode;
  626. unsigned short qdcount;
  627. unsigned short ancount;
  628. unsigned short type = 0;
  629. unsigned short rdlength;
  630. unsigned short nscount;
  631. unsigned short arcount;
  632. unsigned int index = 12;
  633. DOHcode rc;
  634. if(dohlen < 12)
  635. return DOH_TOO_SMALL_BUFFER; /* too small */
  636. if(!doh || doh[0] || doh[1])
  637. return DOH_DNS_BAD_ID; /* bad ID */
  638. rcode = doh[3] & 0x0f;
  639. if(rcode)
  640. return DOH_DNS_BAD_RCODE; /* bad rcode */
  641. qdcount = doh_get16bit(doh, 4);
  642. while(qdcount) {
  643. rc = doh_skipqname(doh, dohlen, &index);
  644. if(rc)
  645. return rc; /* bad qname */
  646. if(dohlen < (index + 4))
  647. return DOH_DNS_OUT_OF_RANGE;
  648. index += 4; /* skip question's type and class */
  649. qdcount--;
  650. }
  651. ancount = doh_get16bit(doh, 6);
  652. while(ancount) {
  653. unsigned short class;
  654. unsigned int ttl;
  655. rc = doh_skipqname(doh, dohlen, &index);
  656. if(rc)
  657. return rc; /* bad qname */
  658. if(dohlen < (index + 2))
  659. return DOH_DNS_OUT_OF_RANGE;
  660. type = doh_get16bit(doh, index);
  661. if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
  662. && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
  663. && (type != dnstype))
  664. /* Not the same type as was asked for nor CNAME nor DNAME */
  665. return DOH_DNS_UNEXPECTED_TYPE;
  666. index += 2;
  667. if(dohlen < (index + 2))
  668. return DOH_DNS_OUT_OF_RANGE;
  669. class = doh_get16bit(doh, index);
  670. if(DNS_CLASS_IN != class)
  671. return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
  672. index += 2;
  673. if(dohlen < (index + 4))
  674. return DOH_DNS_OUT_OF_RANGE;
  675. ttl = doh_get32bit(doh, index);
  676. if(ttl < d->ttl)
  677. d->ttl = ttl;
  678. index += 4;
  679. if(dohlen < (index + 2))
  680. return DOH_DNS_OUT_OF_RANGE;
  681. rdlength = doh_get16bit(doh, index);
  682. index += 2;
  683. if(dohlen < (index + rdlength))
  684. return DOH_DNS_OUT_OF_RANGE;
  685. rc = doh_rdata(doh, dohlen, rdlength, type, (int)index, d);
  686. if(rc)
  687. return rc; /* bad doh_rdata */
  688. index += rdlength;
  689. ancount--;
  690. }
  691. nscount = doh_get16bit(doh, 8);
  692. while(nscount) {
  693. rc = doh_skipqname(doh, dohlen, &index);
  694. if(rc)
  695. return rc; /* bad qname */
  696. if(dohlen < (index + 8))
  697. return DOH_DNS_OUT_OF_RANGE;
  698. index += 2 + 2 + 4; /* type, class and ttl */
  699. if(dohlen < (index + 2))
  700. return DOH_DNS_OUT_OF_RANGE;
  701. rdlength = doh_get16bit(doh, index);
  702. index += 2;
  703. if(dohlen < (index + rdlength))
  704. return DOH_DNS_OUT_OF_RANGE;
  705. index += rdlength;
  706. nscount--;
  707. }
  708. arcount = doh_get16bit(doh, 10);
  709. while(arcount) {
  710. rc = doh_skipqname(doh, dohlen, &index);
  711. if(rc)
  712. return rc; /* bad qname */
  713. if(dohlen < (index + 8))
  714. return DOH_DNS_OUT_OF_RANGE;
  715. index += 2 + 2 + 4; /* type, class and ttl */
  716. if(dohlen < (index + 2))
  717. return DOH_DNS_OUT_OF_RANGE;
  718. rdlength = doh_get16bit(doh, index);
  719. index += 2;
  720. if(dohlen < (index + rdlength))
  721. return DOH_DNS_OUT_OF_RANGE;
  722. index += rdlength;
  723. arcount--;
  724. }
  725. if(index != dohlen)
  726. return DOH_DNS_MALFORMAT; /* something is wrong */
  727. #ifdef USE_HTTTPS
  728. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr && !d->numhttps_rrs)
  729. #else
  730. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
  731. #endif
  732. /* nothing stored! */
  733. return DOH_NO_CONTENT;
  734. return DOH_OK; /* ok */
  735. }
  736. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  737. static void doh_show(struct Curl_easy *data,
  738. const struct dohentry *d)
  739. {
  740. int i;
  741. infof(data, "[DoH] TTL: %u seconds", d->ttl);
  742. for(i = 0; i < d->numaddr; i++) {
  743. const struct dohaddr *a = &d->addr[i];
  744. if(a->type == DNS_TYPE_A) {
  745. infof(data, "[DoH] A: %u.%u.%u.%u",
  746. a->ip.v4[0], a->ip.v4[1],
  747. a->ip.v4[2], a->ip.v4[3]);
  748. }
  749. else if(a->type == DNS_TYPE_AAAA) {
  750. int j;
  751. char buffer[128] = "[DoH] AAAA: ";
  752. size_t len = strlen(buffer);
  753. char *ptr = &buffer[len];
  754. len = sizeof(buffer) - len;
  755. for(j = 0; j < 16; j += 2) {
  756. size_t l;
  757. msnprintf(ptr, len, "%s%02x%02x", j ? ":" : "", d->addr[i].ip.v6[j],
  758. d->addr[i].ip.v6[j + 1]);
  759. l = strlen(ptr);
  760. len -= l;
  761. ptr += l;
  762. }
  763. infof(data, "%s", buffer);
  764. }
  765. }
  766. #ifdef USE_HTTPSRR
  767. for(i = 0; i < d->numhttps_rrs; i++) {
  768. # ifdef DEBUGBUILD
  769. doh_print_buf(data, "DoH HTTPS",
  770. d->https_rrs[i].val, d->https_rrs[i].len);
  771. # else
  772. infof(data, "DoH HTTPS RR: length %d", d->https_rrs[i].len);
  773. # endif
  774. }
  775. #endif
  776. for(i = 0; i < d->numcname; i++) {
  777. infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i]));
  778. }
  779. }
  780. #else
  781. #define doh_show(x,y)
  782. #endif
  783. /*
  784. * doh2ai()
  785. *
  786. * This function returns a pointer to the first element of a newly allocated
  787. * Curl_addrinfo struct linked list filled with the data from a set of DoH
  788. * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
  789. * a IPv6 stack, but usable also for IPv4, all hosts and environments.
  790. *
  791. * The memory allocated by this function *MUST* be free'd later on calling
  792. * Curl_freeaddrinfo(). For each successful call to this function there
  793. * must be an associated call later to Curl_freeaddrinfo().
  794. */
  795. static CURLcode doh2ai(const struct dohentry *de, const char *hostname,
  796. int port, struct Curl_addrinfo **aip)
  797. {
  798. struct Curl_addrinfo *ai;
  799. struct Curl_addrinfo *prevai = NULL;
  800. struct Curl_addrinfo *firstai = NULL;
  801. struct sockaddr_in *addr;
  802. #ifdef USE_IPV6
  803. struct sockaddr_in6 *addr6;
  804. #endif
  805. CURLcode result = CURLE_OK;
  806. int i;
  807. size_t hostlen = strlen(hostname) + 1; /* include null-terminator */
  808. DEBUGASSERT(de);
  809. if(!de->numaddr)
  810. return CURLE_COULDNT_RESOLVE_HOST;
  811. for(i = 0; i < de->numaddr; i++) {
  812. size_t ss_size;
  813. CURL_SA_FAMILY_T addrtype;
  814. if(de->addr[i].type == DNS_TYPE_AAAA) {
  815. #ifndef USE_IPV6
  816. /* we cannot handle IPv6 addresses */
  817. continue;
  818. #else
  819. ss_size = sizeof(struct sockaddr_in6);
  820. addrtype = AF_INET6;
  821. #endif
  822. }
  823. else {
  824. ss_size = sizeof(struct sockaddr_in);
  825. addrtype = AF_INET;
  826. }
  827. ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
  828. if(!ai) {
  829. result = CURLE_OUT_OF_MEMORY;
  830. break;
  831. }
  832. ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
  833. ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
  834. memcpy(ai->ai_canonname, hostname, hostlen);
  835. if(!firstai)
  836. /* store the pointer we want to return from this function */
  837. firstai = ai;
  838. if(prevai)
  839. /* make the previous entry point to this */
  840. prevai->ai_next = ai;
  841. ai->ai_family = addrtype;
  842. /* we return all names as STREAM, so when using this address for TFTP
  843. the type must be ignored and conn->socktype be used instead! */
  844. ai->ai_socktype = SOCK_STREAM;
  845. ai->ai_addrlen = (curl_socklen_t)ss_size;
  846. /* leave the rest of the struct filled with zero */
  847. switch(ai->ai_family) {
  848. case AF_INET:
  849. addr = (void *)ai->ai_addr; /* storage area for this info */
  850. DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
  851. memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
  852. addr->sin_family = (CURL_SA_FAMILY_T)addrtype;
  853. addr->sin_port = htons((unsigned short)port);
  854. break;
  855. #ifdef USE_IPV6
  856. case AF_INET6:
  857. addr6 = (void *)ai->ai_addr; /* storage area for this info */
  858. DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
  859. memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
  860. addr6->sin6_family = (CURL_SA_FAMILY_T)addrtype;
  861. addr6->sin6_port = htons((unsigned short)port);
  862. break;
  863. #endif
  864. }
  865. prevai = ai;
  866. }
  867. if(result) {
  868. Curl_freeaddrinfo(firstai);
  869. firstai = NULL;
  870. }
  871. *aip = firstai;
  872. return result;
  873. }
  874. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  875. static const char *doh_type2name(DNStype dnstype)
  876. {
  877. switch(dnstype) {
  878. case DNS_TYPE_A:
  879. return "A";
  880. case DNS_TYPE_AAAA:
  881. return "AAAA";
  882. #ifdef USE_HTTPSRR
  883. case DNS_TYPE_HTTPS:
  884. return "HTTPS";
  885. #endif
  886. default:
  887. return "unknown";
  888. }
  889. }
  890. #endif
  891. UNITTEST void de_cleanup(struct dohentry *d)
  892. {
  893. int i = 0;
  894. for(i = 0; i < d->numcname; i++) {
  895. Curl_dyn_free(&d->cname[i]);
  896. }
  897. #ifdef USE_HTTPSRR
  898. for(i = 0; i < d->numhttps_rrs; i++)
  899. Curl_safefree(d->https_rrs[i].val);
  900. #endif
  901. }
  902. #ifdef USE_HTTPSRR
  903. /*
  904. * @brief decode the DNS name in a binary RRData
  905. * @param buf points to the buffer (in/out)
  906. * @param remaining points to the remaining buffer length (in/out)
  907. * @param dnsname returns the string form name on success
  908. * @return is 1 for success, error otherwise
  909. *
  910. * The encoding here is defined in
  911. * https://tools.ietf.org/html/rfc1035#section-3.1
  912. *
  913. * The input buffer pointer will be modified so it points to
  914. * just after the end of the DNS name encoding on output. (And
  915. * that is why it is an "unsigned char **" :-)
  916. */
  917. static CURLcode doh_decode_rdata_name(unsigned char **buf, size_t *remaining,
  918. char **dnsname)
  919. {
  920. unsigned char *cp = NULL;
  921. int rem = 0;
  922. unsigned char clen = 0; /* chunk len */
  923. struct dynbuf thename;
  924. DEBUGASSERT(buf && remaining && dnsname);
  925. if(!buf || !remaining || !dnsname)
  926. return CURLE_OUT_OF_MEMORY;
  927. rem = (int)*remaining;
  928. if(rem <= 0) {
  929. Curl_dyn_free(&thename);
  930. return CURLE_OUT_OF_MEMORY;
  931. }
  932. Curl_dyn_init(&thename, CURL_MAXLEN_host_name);
  933. cp = *buf;
  934. clen = *cp++;
  935. if(clen == 0) {
  936. /* special case - return "." as name */
  937. if(Curl_dyn_addn(&thename, ".", 1))
  938. return CURLE_OUT_OF_MEMORY;
  939. }
  940. while(clen) {
  941. if(clen >= rem) {
  942. Curl_dyn_free(&thename);
  943. return CURLE_OUT_OF_MEMORY;
  944. }
  945. if(Curl_dyn_addn(&thename, cp, clen) ||
  946. Curl_dyn_addn(&thename, ".", 1))
  947. return CURLE_TOO_LARGE;
  948. cp += clen;
  949. rem -= (clen + 1);
  950. if(rem <= 0) {
  951. Curl_dyn_free(&thename);
  952. return CURLE_OUT_OF_MEMORY;
  953. }
  954. clen = *cp++;
  955. }
  956. *buf = cp;
  957. *remaining = rem - 1;
  958. *dnsname = Curl_dyn_ptr(&thename);
  959. return CURLE_OK;
  960. }
  961. static CURLcode doh_decode_rdata_alpn(unsigned char *rrval, size_t len,
  962. char **alpns)
  963. {
  964. /*
  965. * spec here is as per draft-ietf-dnsop-svcb-https, section-7.1.1
  966. * encoding is catenated list of strings each preceded by a one
  967. * octet length
  968. * output is comma-sep list of the strings
  969. * implementations may or may not handle quoting of comma within
  970. * string values, so we might see a comma within the wire format
  971. * version of a string, in which case we will precede that by a
  972. * backslash - same goes for a backslash character, and of course
  973. * we need to use two backslashes in strings when we mean one;-)
  974. */
  975. int remaining = (int) len;
  976. char *oval;
  977. size_t i;
  978. unsigned char *cp = rrval;
  979. struct dynbuf dval;
  980. if(!alpns)
  981. return CURLE_OUT_OF_MEMORY;
  982. Curl_dyn_init(&dval, DYN_DOH_RESPONSE);
  983. remaining = (int)len;
  984. cp = rrval;
  985. while(remaining > 0) {
  986. size_t tlen = (size_t) *cp++;
  987. /* if not 1st time, add comma */
  988. if(remaining != (int)len && Curl_dyn_addn(&dval, ",", 1))
  989. goto err;
  990. remaining--;
  991. if(tlen > (size_t)remaining)
  992. goto err;
  993. /* add escape char if needed, clunky but easier to read */
  994. for(i = 0; i != tlen; i++) {
  995. if('\\' == *cp || ',' == *cp) {
  996. if(Curl_dyn_addn(&dval, "\\", 1))
  997. goto err;
  998. }
  999. if(Curl_dyn_addn(&dval, cp++, 1))
  1000. goto err;
  1001. }
  1002. remaining -= (int)tlen;
  1003. }
  1004. /* this string is always null terminated */
  1005. oval = Curl_dyn_ptr(&dval);
  1006. if(!oval)
  1007. goto err;
  1008. *alpns = oval;
  1009. return CURLE_OK;
  1010. err:
  1011. Curl_dyn_free(&dval);
  1012. return CURLE_BAD_CONTENT_ENCODING;
  1013. }
  1014. #ifdef DEBUGBUILD
  1015. static CURLcode doh_test_alpn_escapes(void)
  1016. {
  1017. /* we will use an example from draft-ietf-dnsop-svcb, figure 10 */
  1018. static unsigned char example[] = {
  1019. 0x08, /* length 8 */
  1020. 0x66, 0x5c, 0x6f, 0x6f, 0x2c, 0x62, 0x61, 0x72, /* value "f\\oo,bar" */
  1021. 0x02, /* length 2 */
  1022. 0x68, 0x32 /* value "h2" */
  1023. };
  1024. size_t example_len = sizeof(example);
  1025. char *aval = NULL;
  1026. static const char *expected = "f\\\\oo\\,bar,h2";
  1027. if(doh_decode_rdata_alpn(example, example_len, &aval) != CURLE_OK)
  1028. return CURLE_BAD_CONTENT_ENCODING;
  1029. if(strlen(aval) != strlen(expected))
  1030. return CURLE_BAD_CONTENT_ENCODING;
  1031. if(memcmp(aval, expected, strlen(aval)))
  1032. return CURLE_BAD_CONTENT_ENCODING;
  1033. return CURLE_OK;
  1034. }
  1035. #endif
  1036. static CURLcode doh_resp_decode_httpsrr(unsigned char *rrval, size_t len,
  1037. struct Curl_https_rrinfo **hrr)
  1038. {
  1039. size_t remaining = len;
  1040. unsigned char *cp = rrval;
  1041. uint16_t pcode = 0, plen = 0;
  1042. struct Curl_https_rrinfo *lhrr = NULL;
  1043. char *dnsname = NULL;
  1044. #ifdef DEBUGBUILD
  1045. /* a few tests of escaping, should not be here but ok for now */
  1046. if(doh_test_alpn_escapes() != CURLE_OK)
  1047. return CURLE_OUT_OF_MEMORY;
  1048. #endif
  1049. lhrr = calloc(1, sizeof(struct Curl_https_rrinfo));
  1050. if(!lhrr)
  1051. return CURLE_OUT_OF_MEMORY;
  1052. lhrr->val = Curl_memdup(rrval, len);
  1053. if(!lhrr->val)
  1054. goto err;
  1055. lhrr->len = len;
  1056. if(remaining <= 2)
  1057. goto err;
  1058. lhrr->priority = (uint16_t)((cp[0] << 8) + cp[1]);
  1059. cp += 2;
  1060. remaining -= (uint16_t)2;
  1061. if(doh_decode_rdata_name(&cp, &remaining, &dnsname) != CURLE_OK)
  1062. goto err;
  1063. lhrr->target = dnsname;
  1064. while(remaining >= 4) {
  1065. pcode = (uint16_t)((*cp << 8) + (*(cp + 1)));
  1066. cp += 2;
  1067. plen = (uint16_t)((*cp << 8) + (*(cp + 1)));
  1068. cp += 2;
  1069. remaining -= 4;
  1070. if(pcode == HTTPS_RR_CODE_ALPN) {
  1071. if(doh_decode_rdata_alpn(cp, plen, &lhrr->alpns) != CURLE_OK)
  1072. goto err;
  1073. }
  1074. if(pcode == HTTPS_RR_CODE_NO_DEF_ALPN)
  1075. lhrr->no_def_alpn = TRUE;
  1076. else if(pcode == HTTPS_RR_CODE_IPV4) {
  1077. if(!plen)
  1078. goto err;
  1079. lhrr->ipv4hints = Curl_memdup(cp, plen);
  1080. if(!lhrr->ipv4hints)
  1081. goto err;
  1082. lhrr->ipv4hints_len = (size_t)plen;
  1083. }
  1084. else if(pcode == HTTPS_RR_CODE_ECH) {
  1085. if(!plen)
  1086. goto err;
  1087. lhrr->echconfiglist = Curl_memdup(cp, plen);
  1088. if(!lhrr->echconfiglist)
  1089. goto err;
  1090. lhrr->echconfiglist_len = (size_t)plen;
  1091. }
  1092. else if(pcode == HTTPS_RR_CODE_IPV6) {
  1093. if(!plen)
  1094. goto err;
  1095. lhrr->ipv6hints = Curl_memdup(cp, plen);
  1096. if(!lhrr->ipv6hints)
  1097. goto err;
  1098. lhrr->ipv6hints_len = (size_t)plen;
  1099. }
  1100. if(plen > 0 && plen <= remaining) {
  1101. cp += plen;
  1102. remaining -= plen;
  1103. }
  1104. }
  1105. DEBUGASSERT(!remaining);
  1106. *hrr = lhrr;
  1107. return CURLE_OK;
  1108. err:
  1109. if(lhrr) {
  1110. Curl_safefree(lhrr->target);
  1111. Curl_safefree(lhrr->echconfiglist);
  1112. Curl_safefree(lhrr->val);
  1113. Curl_safefree(lhrr->alpns);
  1114. Curl_safefree(lhrr);
  1115. }
  1116. return CURLE_OUT_OF_MEMORY;
  1117. }
  1118. # ifdef DEBUGBUILD
  1119. static void doh_print_httpsrr(struct Curl_easy *data,
  1120. struct Curl_https_rrinfo *hrr)
  1121. {
  1122. DEBUGASSERT(hrr);
  1123. infof(data, "HTTPS RR: priority %d, target: %s",
  1124. hrr->priority, hrr->target);
  1125. if(hrr->alpns)
  1126. infof(data, "HTTPS RR: alpns %s", hrr->alpns);
  1127. else
  1128. infof(data, "HTTPS RR: no alpns");
  1129. if(hrr->no_def_alpn)
  1130. infof(data, "HTTPS RR: no_def_alpn set");
  1131. else
  1132. infof(data, "HTTPS RR: no_def_alpn not set");
  1133. if(hrr->ipv4hints) {
  1134. doh_print_buf(data, "HTTPS RR: ipv4hints",
  1135. hrr->ipv4hints, hrr->ipv4hints_len);
  1136. }
  1137. else
  1138. infof(data, "HTTPS RR: no ipv4hints");
  1139. if(hrr->echconfiglist) {
  1140. doh_print_buf(data, "HTTPS RR: ECHConfigList",
  1141. hrr->echconfiglist, hrr->echconfiglist_len);
  1142. }
  1143. else
  1144. infof(data, "HTTPS RR: no ECHConfigList");
  1145. if(hrr->ipv6hints) {
  1146. doh_print_buf(data, "HTTPS RR: ipv6hint",
  1147. hrr->ipv6hints, hrr->ipv6hints_len);
  1148. }
  1149. else
  1150. infof(data, "HTTPS RR: no ipv6hints");
  1151. return;
  1152. }
  1153. # endif
  1154. #endif
  1155. CURLcode Curl_doh_is_resolved(struct Curl_easy *data,
  1156. struct Curl_dns_entry **dnsp)
  1157. {
  1158. CURLcode result;
  1159. struct doh_probes *dohp = data->req.doh;
  1160. *dnsp = NULL; /* defaults to no response */
  1161. if(!dohp)
  1162. return CURLE_OUT_OF_MEMORY;
  1163. if(dohp->probe[DOH_SLOT_IPV4].easy_mid < 0 &&
  1164. dohp->probe[DOH_SLOT_IPV6].easy_mid < 0) {
  1165. failf(data, "Could not DoH-resolve: %s", data->state.async.hostname);
  1166. return CONN_IS_PROXIED(data->conn) ? CURLE_COULDNT_RESOLVE_PROXY :
  1167. CURLE_COULDNT_RESOLVE_HOST;
  1168. }
  1169. else if(!dohp->pending) {
  1170. DOHcode rc[DOH_SLOT_COUNT];
  1171. struct dohentry de;
  1172. int slot;
  1173. memset(rc, 0, sizeof(rc));
  1174. /* remove DoH handles from multi handle and close them */
  1175. Curl_doh_close(data);
  1176. /* parse the responses, create the struct and return it! */
  1177. de_init(&de);
  1178. for(slot = 0; slot < DOH_SLOT_COUNT; slot++) {
  1179. struct doh_probe *p = &dohp->probe[slot];
  1180. if(!p->dnstype)
  1181. continue;
  1182. rc[slot] = doh_resp_decode(Curl_dyn_uptr(&p->resp_body),
  1183. Curl_dyn_len(&p->resp_body),
  1184. p->dnstype, &de);
  1185. Curl_dyn_free(&p->resp_body);
  1186. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1187. if(rc[slot]) {
  1188. infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]),
  1189. doh_type2name(p->dnstype), dohp->host);
  1190. }
  1191. #endif
  1192. } /* next slot */
  1193. result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
  1194. if(!rc[DOH_SLOT_IPV4] || !rc[DOH_SLOT_IPV6]) {
  1195. /* we have an address, of one kind or other */
  1196. struct Curl_dns_entry *dns;
  1197. struct Curl_addrinfo *ai;
  1198. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc)) {
  1199. infof(data, "[DoH] hostname: %s", dohp->host);
  1200. doh_show(data, &de);
  1201. }
  1202. result = doh2ai(&de, dohp->host, dohp->port, &ai);
  1203. if(result) {
  1204. de_cleanup(&de);
  1205. return result;
  1206. }
  1207. if(data->share)
  1208. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  1209. /* we got a response, store it in the cache */
  1210. dns = Curl_cache_addr(data, ai, dohp->host, 0, dohp->port, FALSE);
  1211. if(data->share)
  1212. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  1213. if(!dns) {
  1214. /* returned failure, bail out nicely */
  1215. Curl_freeaddrinfo(ai);
  1216. }
  1217. else {
  1218. data->state.async.dns = dns;
  1219. *dnsp = dns;
  1220. result = CURLE_OK; /* address resolution OK */
  1221. }
  1222. } /* address processing done */
  1223. /* Now process any build-specific attributes retrieved from DNS */
  1224. #ifdef USE_HTTPSRR
  1225. if(de.numhttps_rrs > 0 && result == CURLE_OK && *dnsp) {
  1226. struct Curl_https_rrinfo *hrr = NULL;
  1227. result = doh_resp_decode_httpsrr(de.https_rrs->val, de.https_rrs->len,
  1228. &hrr);
  1229. if(result) {
  1230. infof(data, "Failed to decode HTTPS RR");
  1231. return result;
  1232. }
  1233. infof(data, "Some HTTPS RR to process");
  1234. # ifdef DEBUGBUILD
  1235. doh_print_httpsrr(data, hrr);
  1236. # endif
  1237. (*dnsp)->hinfo = hrr;
  1238. }
  1239. #endif
  1240. /* All done */
  1241. de_cleanup(&de);
  1242. Curl_doh_cleanup(data);
  1243. return result;
  1244. } /* !dohp->pending */
  1245. /* else wait for pending DoH transactions to complete */
  1246. return CURLE_OK;
  1247. }
  1248. void Curl_doh_close(struct Curl_easy *data)
  1249. {
  1250. struct doh_probes *doh = data->req.doh;
  1251. if(doh && data->multi) {
  1252. struct Curl_easy *probe_data;
  1253. curl_off_t mid;
  1254. size_t slot;
  1255. for(slot = 0; slot < DOH_SLOT_COUNT; slot++) {
  1256. mid = doh->probe[slot].easy_mid;
  1257. if(mid < 0)
  1258. continue;
  1259. doh->probe[slot].easy_mid = -1;
  1260. /* should have been called before data is removed from multi handle */
  1261. DEBUGASSERT(data->multi);
  1262. probe_data = data->multi ? Curl_multi_get_handle(data->multi, mid) :
  1263. NULL;
  1264. if(!probe_data) {
  1265. DEBUGF(infof(data, "Curl_doh_close: xfer for mid=%"
  1266. FMT_OFF_T " not found!",
  1267. doh->probe[slot].easy_mid));
  1268. continue;
  1269. }
  1270. /* data->multi might already be reset at this time */
  1271. curl_multi_remove_handle(data->multi, probe_data);
  1272. Curl_close(&probe_data);
  1273. }
  1274. }
  1275. }
  1276. void Curl_doh_cleanup(struct Curl_easy *data)
  1277. {
  1278. struct doh_probes *doh = data->req.doh;
  1279. if(doh) {
  1280. Curl_doh_close(data);
  1281. curl_slist_free_all(doh->req_hds);
  1282. data->req.doh->req_hds = NULL;
  1283. Curl_safefree(data->req.doh);
  1284. }
  1285. }
  1286. #endif /* CURL_DISABLE_DOH */