Debian Codegraph @

deps/curl/lib/doh.c

raw
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 2018 - 2020, Daniel Stenberg, <[email protected]>, 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.haxx.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 #include "curl_setup.h"
24
25 #ifndef CURL_DISABLE_DOH
26
27 #include "urldata.h"
28 #include "curl_addrinfo.h"
29 #include "doh.h"
30
31 #include "sendf.h"
32 #include "multiif.h"
33 #include "url.h"
34 #include "share.h"
35 #include "curl_base64.h"
36 #include "connect.h"
37 #include "strdup.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
43 #define DNS_CLASS_IN 0x01
44 #define DOH_MAX_RESPONSE_SIZE 3000 /* bytes */
45
46 #ifndef CURL_DISABLE_VERBOSE_STRINGS
47 static const char * const errors[]={
48 "",
49 "Bad label",
50 "Out of range",
51 "Label loop",
52 "Too small",
53 "Out of memory",
54 "RDATA length",
55 "Malformat",
56 "Bad RCODE",
57 "Unexpected TYPE",
58 "Unexpected CLASS",
59 "No content",
60 "Bad ID"
61 };
62
63 static const char *doh_strerror(DOHcode code)
64 {
65 if((code >= DOH_OK) && (code <= DOH_DNS_BAD_ID))
66 return errors[code];
67 return "bad error code";
68 }
69 #endif
70
71 #ifdef DEBUGBUILD
72 #define UNITTEST
73 #else
74 #define UNITTEST static
75 #endif
76
77 /* @unittest 1655
78 */
79 UNITTEST DOHcode doh_encode(const char *host,
80 DNStype dnstype,
81 unsigned char *dnsp, /* buffer */
82 size_t len, /* buffer size */
83 size_t *olen) /* output length */
84 {
85 const size_t hostlen = strlen(host);
86 unsigned char *orig = dnsp;
87 const char *hostp = host;
88
89 /* The expected output length is 16 bytes more than the length of
90 * the QNAME-encoding of the host name.
91 *
92 * A valid DNS name may not contain a zero-length label, except at
93 * the end. For this reason, a name beginning with a dot, or
94 * containing a sequence of two or more consecutive dots, is invalid
95 * and cannot be encoded as a QNAME.
96 *
97 * If the host name ends with a trailing dot, the corresponding
98 * QNAME-encoding is one byte longer than the host name. If (as is
99 * also valid) the hostname is shortened by the omission of the
100 * trailing dot, then its QNAME-encoding will be two bytes longer
101 * than the host name.
102 *
103 * Each [ label, dot ] pair is encoded as [ length, label ],
104 * preserving overall length. A final [ label ] without a dot is
105 * also encoded as [ length, label ], increasing overall length
106 * by one. The encoding is completed by appending a zero byte,
107 * representing the zero-length root label, again increasing
108 * the overall length by one.
109 */
110
111 size_t expected_len;
112 DEBUGASSERT(hostlen);
113 expected_len = 12 + 1 + hostlen + 4;
114 if(host[hostlen-1]!='.')
115 expected_len++;
116
117 if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
118 return DOH_DNS_NAME_TOO_LONG;
119
120 if(len < expected_len)
121 return DOH_TOO_SMALL_BUFFER;
122
123 *dnsp++ = 0; /* 16 bit id */
124 *dnsp++ = 0;
125 *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
126 *dnsp++ = '\0'; /* |RA| Z | RCODE | */
127 *dnsp++ = '\0';
128 *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
129 *dnsp++ = '\0';
130 *dnsp++ = '\0'; /* ANCOUNT */
131 *dnsp++ = '\0';
132 *dnsp++ = '\0'; /* NSCOUNT */
133 *dnsp++ = '\0';
134 *dnsp++ = '\0'; /* ARCOUNT */
135
136 /* encode each label and store it in the QNAME */
137 while(*hostp) {
138 size_t labellen;
139 char *dot = strchr(hostp, '.');
140 if(dot)
141 labellen = dot - hostp;
142 else
143 labellen = strlen(hostp);
144 if((labellen > 63) || (!labellen)) {
145 /* label is too long or too short, error out */
146 *olen = 0;
147 return DOH_DNS_BAD_LABEL;
148 }
149 /* label is non-empty, process it */
150 *dnsp++ = (unsigned char)labellen;
151 memcpy(dnsp, hostp, labellen);
152 dnsp += labellen;
153 hostp += labellen;
154 /* advance past dot, but only if there is one */
155 if(dot)
156 hostp++;
157 } /* next label */
158
159 *dnsp++ = 0; /* append zero-length label for root */
160
161 /* There are assigned TYPE codes beyond 255: use range [1..65535] */
162 *dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */
163 *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
164
165 *dnsp++ = '\0'; /* upper 8 bit CLASS */
166 *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
167
168 *olen = dnsp - orig;
169
170 /* verify that our estimation of length is valid, since
171 * this has led to buffer overflows in this function */
172 DEBUGASSERT(*olen == expected_len);
173 return DOH_OK;
174 }
175
176 static size_t
177 doh_write_cb(void *contents, size_t size, size_t nmemb, void *userp)
178 {
179 size_t realsize = size * nmemb;
180 struct dohresponse *mem = (struct dohresponse *)userp;
181
182 if((mem->size + realsize) > DOH_MAX_RESPONSE_SIZE)
183 /* suspiciously much for us */
184 return 0;
185
186 mem->memory = Curl_saferealloc(mem->memory, mem->size + realsize);
187 if(!mem->memory)
188 /* out of memory! */
189 return 0;
190
191 memcpy(&(mem->memory[mem->size]), contents, realsize);
192 mem->size += realsize;
193
194 return realsize;
195 }
196
197 /* called from multi.c when this DOH transfer is complete */
198 static int Curl_doh_done(struct Curl_easy *doh, CURLcode result)
199 {
200 struct Curl_easy *data = doh->set.dohfor;
201 /* so one of the DOH request done for the 'data' transfer is now complete! */
202 data->req.doh.pending--;
203 infof(data, "a DOH request is completed, %u to go\n", data->req.doh.pending);
204 if(result)
205 infof(data, "DOH request %s\n", curl_easy_strerror(result));
206
207 if(!data->req.doh.pending) {
208 /* DOH completed */
209 curl_slist_free_all(data->req.doh.headers);
210 data->req.doh.headers = NULL;
211 Curl_expire(data, 0, EXPIRE_RUN_NOW);
212 }
213 return 0;
214 }
215
216 #define ERROR_CHECK_SETOPT(x,y) \
217 do { \
218 result = curl_easy_setopt(doh, x, y); \
219 if(result) \
220 goto error; \
221 } while(0)
222
223 static CURLcode dohprobe(struct Curl_easy *data,
224 struct dnsprobe *p, DNStype dnstype,
225 const char *host,
226 const char *url, CURLM *multi,
227 struct curl_slist *headers)
228 {
229 struct Curl_easy *doh = NULL;
230 char *nurl = NULL;
231 CURLcode result = CURLE_OK;
232 timediff_t timeout_ms;
233 DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
234 &p->dohlen);
235 if(d) {
236 failf(data, "Failed to encode DOH packet [%d]\n", d);
237 return CURLE_OUT_OF_MEMORY;
238 }
239
240 p->dnstype = dnstype;
241 p->serverdoh.memory = NULL;
242 /* the memory will be grown as needed by realloc in the doh_write_cb
243 function */
244 p->serverdoh.size = 0;
245
246 /* Note: this is code for sending the DoH request with GET but there's still
247 no logic that actually enables this. We should either add that ability or
248 yank out the GET code. Discuss! */
249 if(data->set.doh_get) {
250 char *b64;
251 size_t b64len;
252 result = Curl_base64url_encode(data, (char *)p->dohbuffer, p->dohlen,
253 &b64, &b64len);
254 if(result)
255 goto error;
256 nurl = aprintf("%s?dns=%s", url, b64);
257 free(b64);
258 if(!nurl) {
259 result = CURLE_OUT_OF_MEMORY;
260 goto error;
261 }
262 url = nurl;
263 }
264
265 timeout_ms = Curl_timeleft(data, NULL, TRUE);
266 if(timeout_ms <= 0) {
267 result = CURLE_OPERATION_TIMEDOUT;
268 goto error;
269 }
270 /* Curl_open() is the internal version of curl_easy_init() */
271 result = Curl_open(&doh);
272 if(!result) {
273 /* pass in the struct pointer via a local variable to please coverity and
274 the gcc typecheck helpers */
275 struct dohresponse *resp = &p->serverdoh;
276 ERROR_CHECK_SETOPT(CURLOPT_URL, url);
277 ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
278 ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
279 if(!data->set.doh_get) {
280 ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
281 ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
282 }
283 ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
284 #ifdef USE_NGHTTP2
285 ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
286 #endif
287 #ifndef CURLDEBUG
288 /* enforce HTTPS if not debug */
289 ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
290 #else
291 /* in debug mode, also allow http */
292 ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
293 #endif
294 ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
295 if(data->set.verbose)
296 ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
297 if(data->set.no_signal)
298 ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
299
300 /* Inherit *some* SSL options from the user's transfer. This is a
301 best-guess as to which options are needed for compatibility. #3661 */
302 if(data->set.ssl.falsestart)
303 ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
304 if(data->set.ssl.primary.verifyhost)
305 ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, 2L);
306 #ifndef CURL_DISABLE_PROXY
307 if(data->set.proxy_ssl.primary.verifyhost)
308 ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYHOST, 2L);
309 if(data->set.proxy_ssl.primary.verifypeer)
310 ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYPEER, 1L);
311 if(data->set.str[STRING_SSL_CAFILE_PROXY]) {
312 ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAINFO,
313 data->set.str[STRING_SSL_CAFILE_PROXY]);
314 }
315 if(data->set.str[STRING_SSL_CRLFILE_PROXY]) {
316 ERROR_CHECK_SETOPT(CURLOPT_PROXY_CRLFILE,
317 data->set.str[STRING_SSL_CRLFILE_PROXY]);
318 }
319 if(data->set.proxy_ssl.no_revoke)
320 ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
321 if(data->set.str[STRING_SSL_CAPATH_PROXY]) {
322 ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAPATH,
323 data->set.str[STRING_SSL_CAPATH_PROXY]);
324 }
325 #endif
326 if(data->set.ssl.primary.verifypeer)
327 ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, 1L);
328 if(data->set.ssl.primary.verifystatus)
329 ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, 1L);
330 if(data->set.str[STRING_SSL_CAFILE_ORIG]) {
331 ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
332 data->set.str[STRING_SSL_CAFILE_ORIG]);
333 }
334 if(data->set.str[STRING_SSL_CAPATH_ORIG]) {
335 ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
336 data->set.str[STRING_SSL_CAPATH_ORIG]);
337 }
338 if(data->set.str[STRING_SSL_CRLFILE_ORIG]) {
339 ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
340 data->set.str[STRING_SSL_CRLFILE_ORIG]);
341 }
342 if(data->set.ssl.certinfo)
343 ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
344 if(data->set.str[STRING_SSL_RANDOM_FILE]) {
345 ERROR_CHECK_SETOPT(CURLOPT_RANDOM_FILE,
346 data->set.str[STRING_SSL_RANDOM_FILE]);
347 }
348 if(data->set.str[STRING_SSL_EGDSOCKET]) {
349 ERROR_CHECK_SETOPT(CURLOPT_EGDSOCKET,
350 data->set.str[STRING_SSL_EGDSOCKET]);
351 }
352 if(data->set.ssl.no_revoke)
353 ERROR_CHECK_SETOPT(CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
354 if(data->set.ssl.fsslctx)
355 ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
356 if(data->set.ssl.fsslctxp)
357 ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
358
359 doh->set.fmultidone = Curl_doh_done;
360 doh->set.dohfor = data; /* identify for which transfer this is done */
361 p->easy = doh;
362
363 /* add this transfer to the multi handle */
364 if(curl_multi_add_handle(multi, doh))
365 goto error;
366 }
367 else
368 goto error;
369 free(nurl);
370 return CURLE_OK;
371
372 error:
373 free(nurl);
374 Curl_close(&doh);
375 return result;
376 }
377
378 /*
379 * Curl_doh() resolves a name using DOH. It resolves a name and returns a
380 * 'Curl_addrinfo *' with the address information.
381 */
382
383 Curl_addrinfo *Curl_doh(struct connectdata *conn,
384 const char *hostname,
385 int port,
386 int *waitp)
387 {
388 struct Curl_easy *data = conn->data;
389 CURLcode result = CURLE_OK;
390 int slot;
391 *waitp = TRUE; /* this never returns synchronously */
392 (void)conn;
393 (void)hostname;
394 (void)port;
395
396 /* start clean, consider allocating this struct on demand */
397 memset(&data->req.doh, 0, sizeof(struct dohdata));
398
399 data->req.doh.host = hostname;
400 data->req.doh.port = port;
401 data->req.doh.headers =
402 curl_slist_append(NULL,
403 "Content-Type: application/dns-message");
404 if(!data->req.doh.headers)
405 goto error;
406
407 if(conn->ip_version != CURL_IPRESOLVE_V6) {
408 /* create IPv4 DOH request */
409 result = dohprobe(data, &data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V4],
410 DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
411 data->multi, data->req.doh.headers);
412 if(result)
413 goto error;
414 data->req.doh.pending++;
415 }
416
417 if(conn->ip_version != CURL_IPRESOLVE_V4) {
418 /* create IPv6 DOH request */
419 result = dohprobe(data, &data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V6],
420 DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
421 data->multi, data->req.doh.headers);
422 if(result)
423 goto error;
424 data->req.doh.pending++;
425 }
426 return NULL;
427
428 error:
429 curl_slist_free_all(data->req.doh.headers);
430 data->req.doh.headers = NULL;
431 for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
432 Curl_close(&data->req.doh.probe[slot].easy);
433 }
434 return NULL;
435 }
436
437 static DOHcode skipqname(unsigned char *doh, size_t dohlen,
438 unsigned int *indexp)
439 {
440 unsigned char length;
441 do {
442 if(dohlen < (*indexp + 1))
443 return DOH_DNS_OUT_OF_RANGE;
444 length = doh[*indexp];
445 if((length & 0xc0) == 0xc0) {
446 /* name pointer, advance over it and be done */
447 if(dohlen < (*indexp + 2))
448 return DOH_DNS_OUT_OF_RANGE;
449 *indexp += 2;
450 break;
451 }
452 if(length & 0xc0)
453 return DOH_DNS_BAD_LABEL;
454 if(dohlen < (*indexp + 1 + length))
455 return DOH_DNS_OUT_OF_RANGE;
456 *indexp += 1 + length;
457 } while(length);
458 return DOH_OK;
459 }
460
461 static unsigned short get16bit(unsigned char *doh, int index)
462 {
463 return (unsigned short)((doh[index] << 8) | doh[index + 1]);
464 }
465
466 static unsigned int get32bit(unsigned char *doh, int index)
467 {
468 /* make clang and gcc optimize this to bswap by incrementing
469 the pointer first. */
470 doh += index;
471
472 /* avoid undefined behaviour by casting to unsigned before shifting
473 24 bits, possibly into the sign bit. codegen is same, but
474 ub sanitizer won't be upset */
475 return ( (unsigned)doh[0] << 24) | (doh[1] << 16) |(doh[2] << 8) | doh[3];
476 }
477
478 static DOHcode store_a(unsigned char *doh, int index, struct dohentry *d)
479 {
480 /* silently ignore addresses over the limit */
481 if(d->numaddr < DOH_MAX_ADDR) {
482 struct dohaddr *a = &d->addr[d->numaddr];
483 a->type = DNS_TYPE_A;
484 memcpy(&a->ip.v4, &doh[index], 4);
485 d->numaddr++;
486 }
487 return DOH_OK;
488 }
489
490 static DOHcode store_aaaa(unsigned char *doh, int index, struct dohentry *d)
491 {
492 /* silently ignore addresses over the limit */
493 if(d->numaddr < DOH_MAX_ADDR) {
494 struct dohaddr *a = &d->addr[d->numaddr];
495 a->type = DNS_TYPE_AAAA;
496 memcpy(&a->ip.v6, &doh[index], 16);
497 d->numaddr++;
498 }
499 return DOH_OK;
500 }
501
502 static DOHcode cnameappend(struct cnamestore *c,
503 unsigned char *src,
504 size_t len)
505 {
506 if(!c->alloc) {
507 c->allocsize = len + 1;
508 c->alloc = malloc(c->allocsize);
509 if(!c->alloc)
510 return DOH_OUT_OF_MEM;
511 }
512 else if(c->allocsize < (c->allocsize + len + 1)) {
513 char *ptr;
514 c->allocsize += len + 1;
515 ptr = realloc(c->alloc, c->allocsize);
516 if(!ptr) {
517 free(c->alloc);
518 return DOH_OUT_OF_MEM;
519 }
520 c->alloc = ptr;
521 }
522 memcpy(&c->alloc[c->len], src, len);
523 c->len += len;
524 c->alloc[c->len] = 0; /* keep it zero terminated */
525 return DOH_OK;
526 }
527
528 static DOHcode store_cname(unsigned char *doh,
529 size_t dohlen,
530 unsigned int index,
531 struct dohentry *d)
532 {
533 struct cnamestore *c;
534 unsigned int loop = 128; /* a valid DNS name can never loop this much */
535 unsigned char length;
536
537 if(d->numcname == DOH_MAX_CNAME)
538 return DOH_OK; /* skip! */
539
540 c = &d->cname[d->numcname++];
541 do {
542 if(index >= dohlen)
543 return DOH_DNS_OUT_OF_RANGE;
544 length = doh[index];
545 if((length & 0xc0) == 0xc0) {
546 int newpos;
547 /* name pointer, get the new offset (14 bits) */
548 if((index + 1) >= dohlen)
549 return DOH_DNS_OUT_OF_RANGE;
550
551 /* move to the new index */
552 newpos = (length & 0x3f) << 8 | doh[index + 1];
553 index = newpos;
554 continue;
555 }
556 else if(length & 0xc0)
557 return DOH_DNS_BAD_LABEL; /* bad input */
558 else
559 index++;
560
561 if(length) {
562 DOHcode rc;
563 if(c->len) {
564 rc = cnameappend(c, (unsigned char *)".", 1);
565 if(rc)
566 return rc;
567 }
568 if((index + length) > dohlen)
569 return DOH_DNS_BAD_LABEL;
570
571 rc = cnameappend(c, &doh[index], length);
572 if(rc)
573 return rc;
574 index += length;
575 }
576 } while(length && --loop);
577
578 if(!loop)
579 return DOH_DNS_LABEL_LOOP;
580 return DOH_OK;
581 }
582
583 static DOHcode rdata(unsigned char *doh,
584 size_t dohlen,
585 unsigned short rdlength,
586 unsigned short type,
587 int index,
588 struct dohentry *d)
589 {
590 /* RDATA
591 - A (TYPE 1): 4 bytes
592 - AAAA (TYPE 28): 16 bytes
593 - NS (TYPE 2): N bytes */
594 DOHcode rc;
595
596 switch(type) {
597 case DNS_TYPE_A:
598 if(rdlength != 4)
599 return DOH_DNS_RDATA_LEN;
600 rc = store_a(doh, index, d);
601 if(rc)
602 return rc;
603 break;
604 case DNS_TYPE_AAAA:
605 if(rdlength != 16)
606 return DOH_DNS_RDATA_LEN;
607 rc = store_aaaa(doh, index, d);
608 if(rc)
609 return rc;
610 break;
611 case DNS_TYPE_CNAME:
612 rc = store_cname(doh, dohlen, index, d);
613 if(rc)
614 return rc;
615 break;
616 case DNS_TYPE_DNAME:
617 /* explicit for clarity; just skip; rely on synthesized CNAME */
618 break;
619 default:
620 /* unsupported type, just skip it */
621 break;
622 }
623 return DOH_OK;
624 }
625
626 static void init_dohentry(struct dohentry *de)
627 {
628 memset(de, 0, sizeof(*de));
629 de->ttl = INT_MAX;
630 }
631
632
633 UNITTEST DOHcode doh_decode(unsigned char *doh,
634 size_t dohlen,
635 DNStype dnstype,
636 struct dohentry *d)
637 {
638 unsigned char rcode;
639 unsigned short qdcount;
640 unsigned short ancount;
641 unsigned short type = 0;
642 unsigned short rdlength;
643 unsigned short nscount;
644 unsigned short arcount;
645 unsigned int index = 12;
646 DOHcode rc;
647
648 if(dohlen < 12)
649 return DOH_TOO_SMALL_BUFFER; /* too small */
650 if(!doh || doh[0] || doh[1])
651 return DOH_DNS_BAD_ID; /* bad ID */
652 rcode = doh[3] & 0x0f;
653 if(rcode)
654 return DOH_DNS_BAD_RCODE; /* bad rcode */
655
656 qdcount = get16bit(doh, 4);
657 while(qdcount) {
658 rc = skipqname(doh, dohlen, &index);
659 if(rc)
660 return rc; /* bad qname */
661 if(dohlen < (index + 4))
662 return DOH_DNS_OUT_OF_RANGE;
663 index += 4; /* skip question's type and class */
664 qdcount--;
665 }
666
667 ancount = get16bit(doh, 6);
668 while(ancount) {
669 unsigned short class;
670 unsigned int ttl;
671
672 rc = skipqname(doh, dohlen, &index);
673 if(rc)
674 return rc; /* bad qname */
675
676 if(dohlen < (index + 2))
677 return DOH_DNS_OUT_OF_RANGE;
678
679 type = get16bit(doh, index);
680 if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
681 && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
682 && (type != dnstype))
683 /* Not the same type as was asked for nor CNAME nor DNAME */
684 return DOH_DNS_UNEXPECTED_TYPE;
685 index += 2;
686
687 if(dohlen < (index + 2))
688 return DOH_DNS_OUT_OF_RANGE;
689 class = get16bit(doh, index);
690 if(DNS_CLASS_IN != class)
691 return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
692 index += 2;
693
694 if(dohlen < (index + 4))
695 return DOH_DNS_OUT_OF_RANGE;
696
697 ttl = get32bit(doh, index);
698 if(ttl < d->ttl)
699 d->ttl = ttl;
700 index += 4;
701
702 if(dohlen < (index + 2))
703 return DOH_DNS_OUT_OF_RANGE;
704
705 rdlength = get16bit(doh, index);
706 index += 2;
707 if(dohlen < (index + rdlength))
708 return DOH_DNS_OUT_OF_RANGE;
709
710 rc = rdata(doh, dohlen, rdlength, type, index, d);
711 if(rc)
712 return rc; /* bad rdata */
713 index += rdlength;
714 ancount--;
715 }
716
717 nscount = get16bit(doh, 8);
718 while(nscount) {
719 rc = skipqname(doh, dohlen, &index);
720 if(rc)
721 return rc; /* bad qname */
722
723 if(dohlen < (index + 8))
724 return DOH_DNS_OUT_OF_RANGE;
725
726 index += 2 + 2 + 4; /* type, class and ttl */
727
728 if(dohlen < (index + 2))
729 return DOH_DNS_OUT_OF_RANGE;
730
731 rdlength = get16bit(doh, index);
732 index += 2;
733 if(dohlen < (index + rdlength))
734 return DOH_DNS_OUT_OF_RANGE;
735 index += rdlength;
736 nscount--;
737 }
738
739 arcount = get16bit(doh, 10);
740 while(arcount) {
741 rc = skipqname(doh, dohlen, &index);
742 if(rc)
743 return rc; /* bad qname */
744
745 if(dohlen < (index + 8))
746 return DOH_DNS_OUT_OF_RANGE;
747
748 index += 2 + 2 + 4; /* type, class and ttl */
749
750 if(dohlen < (index + 2))
751 return DOH_DNS_OUT_OF_RANGE;
752
753 rdlength = get16bit(doh, index);
754 index += 2;
755 if(dohlen < (index + rdlength))
756 return DOH_DNS_OUT_OF_RANGE;
757 index += rdlength;
758 arcount--;
759 }
760
761 if(index != dohlen)
762 return DOH_DNS_MALFORMAT; /* something is wrong */
763
764 if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
765 /* nothing stored! */
766 return DOH_NO_CONTENT;
767
768 return DOH_OK; /* ok */
769 }
770
771 #ifndef CURL_DISABLE_VERBOSE_STRINGS
772 static void showdoh(struct Curl_easy *data,
773 struct dohentry *d)
774 {
775 int i;
776 infof(data, "TTL: %u seconds\n", d->ttl);
777 for(i = 0; i < d->numaddr; i++) {
778 struct dohaddr *a = &d->addr[i];
779 if(a->type == DNS_TYPE_A) {
780 infof(data, "DOH A: %u.%u.%u.%u\n",
781 a->ip.v4[0], a->ip.v4[1],
782 a->ip.v4[2], a->ip.v4[3]);
783 }
784 else if(a->type == DNS_TYPE_AAAA) {
785 int j;
786 char buffer[128];
787 char *ptr;
788 size_t len;
789 msnprintf(buffer, 128, "DOH AAAA: ");
790 ptr = &buffer[10];
791 len = 118;
792 for(j = 0; j < 16; j += 2) {
793 size_t l;
794 msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
795 d->addr[i].ip.v6[j + 1]);
796 l = strlen(ptr);
797 len -= l;
798 ptr += l;
799 }
800 infof(data, "%s\n", buffer);
801 }
802 }
803 for(i = 0; i < d->numcname; i++) {
804 infof(data, "CNAME: %s\n", d->cname[i].alloc);
805 }
806 }
807 #else
808 #define showdoh(x,y)
809 #endif
810
811 /*
812 * doh2ai()
813 *
814 * This function returns a pointer to the first element of a newly allocated
815 * Curl_addrinfo struct linked list filled with the data from a set of DOH
816 * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
817 * a IPv6 stack, but usable also for IPv4, all hosts and environments.
818 *
819 * The memory allocated by this function *MUST* be free'd later on calling
820 * Curl_freeaddrinfo(). For each successful call to this function there
821 * must be an associated call later to Curl_freeaddrinfo().
822 */
823
824 static Curl_addrinfo *
825 doh2ai(const struct dohentry *de, const char *hostname, int port)
826 {
827 Curl_addrinfo *ai;
828 Curl_addrinfo *prevai = NULL;
829 Curl_addrinfo *firstai = NULL;
830 struct sockaddr_in *addr;
831 #ifdef ENABLE_IPV6
832 struct sockaddr_in6 *addr6;
833 #endif
834 CURLcode result = CURLE_OK;
835 int i;
836
837 if(!de)
838 /* no input == no output! */
839 return NULL;
840
841 for(i = 0; i < de->numaddr; i++) {
842 size_t ss_size;
843 CURL_SA_FAMILY_T addrtype;
844 if(de->addr[i].type == DNS_TYPE_AAAA) {
845 #ifndef ENABLE_IPV6
846 /* we can't handle IPv6 addresses */
847 continue;
848 #else
849 ss_size = sizeof(struct sockaddr_in6);
850 addrtype = AF_INET6;
851 #endif
852 }
853 else {
854 ss_size = sizeof(struct sockaddr_in);
855 addrtype = AF_INET;
856 }
857
858 ai = calloc(1, sizeof(Curl_addrinfo));
859 if(!ai) {
860 result = CURLE_OUT_OF_MEMORY;
861 break;
862 }
863 ai->ai_canonname = strdup(hostname);
864 if(!ai->ai_canonname) {
865 result = CURLE_OUT_OF_MEMORY;
866 free(ai);
867 break;
868 }
869 ai->ai_addr = calloc(1, ss_size);
870 if(!ai->ai_addr) {
871 result = CURLE_OUT_OF_MEMORY;
872 free(ai->ai_canonname);
873 free(ai);
874 break;
875 }
876
877 if(!firstai)
878 /* store the pointer we want to return from this function */
879 firstai = ai;
880
881 if(prevai)
882 /* make the previous entry point to this */
883 prevai->ai_next = ai;
884
885 ai->ai_family = addrtype;
886
887 /* we return all names as STREAM, so when using this address for TFTP
888 the type must be ignored and conn->socktype be used instead! */
889 ai->ai_socktype = SOCK_STREAM;
890
891 ai->ai_addrlen = (curl_socklen_t)ss_size;
892
893 /* leave the rest of the struct filled with zero */
894
895 switch(ai->ai_family) {
896 case AF_INET:
897 addr = (void *)ai->ai_addr; /* storage area for this info */
898 DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
899 memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
900 addr->sin_family = (CURL_SA_FAMILY_T)addrtype;
901 addr->sin_port = htons((unsigned short)port);
902 break;
903
904 #ifdef ENABLE_IPV6
905 case AF_INET6:
906 addr6 = (void *)ai->ai_addr; /* storage area for this info */
907 DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
908 memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
909 addr6->sin6_family = (CURL_SA_FAMILY_T)addrtype;
910 addr6->sin6_port = htons((unsigned short)port);
911 break;
912 #endif
913 }
914
915 prevai = ai;
916 }
917
918 if(result) {
919 Curl_freeaddrinfo(firstai);
920 firstai = NULL;
921 }
922
923 return firstai;
924 }
925
926 #ifndef CURL_DISABLE_VERBOSE_STRINGS
927 static const char *type2name(DNStype dnstype)
928 {
929 return (dnstype == DNS_TYPE_A)?"A":"AAAA";
930 }
931 #endif
932
933 UNITTEST void de_cleanup(struct dohentry *d)
934 {
935 int i = 0;
936 for(i = 0; i < d->numcname; i++) {
937 free(d->cname[i].alloc);
938 }
939 }
940
941 CURLcode Curl_doh_is_resolved(struct connectdata *conn,
942 struct Curl_dns_entry **dnsp)
943 {
944 CURLcode result;
945 struct Curl_easy *data = conn->data;
946 *dnsp = NULL; /* defaults to no response */
947
948 if(!data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
949 !data->req.doh.probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
950 failf(data, "Could not DOH-resolve: %s", conn->async.hostname);
951 return conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY:
952 CURLE_COULDNT_RESOLVE_HOST;
953 }
954 else if(!data->req.doh.pending) {
955 DOHcode rc[DOH_PROBE_SLOTS];
956 struct dohentry de;
957 int slot;
958 /* remove DOH handles from multi handle and close them */
959 for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
960 curl_multi_remove_handle(data->multi, data->req.doh.probe[slot].easy);
961 Curl_close(&data->req.doh.probe[slot].easy);
962 }
963 /* parse the responses, create the struct and return it! */
964 init_dohentry(&de);
965 for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
966 rc[slot] = doh_decode(data->req.doh.probe[slot].serverdoh.memory,
967 data->req.doh.probe[slot].serverdoh.size,
968 data->req.doh.probe[slot].dnstype,
969 &de);
970 Curl_safefree(data->req.doh.probe[slot].serverdoh.memory);
971 if(rc[slot]) {
972 infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc[slot]),
973 type2name(data->req.doh.probe[slot].dnstype),
974 data->req.doh.host);
975 }
976 } /* next slot */
977
978 result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
979 if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
980 /* we have an address, of one kind or other */
981 struct Curl_dns_entry *dns;
982 struct Curl_addrinfo *ai;
983
984 infof(data, "DOH Host name: %s\n", data->req.doh.host);
985 showdoh(data, &de);
986
987 ai = doh2ai(&de, data->req.doh.host, data->req.doh.port);
988 if(!ai) {
989 de_cleanup(&de);
990 return CURLE_OUT_OF_MEMORY;
991 }
992
993 if(data->share)
994 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
995
996 /* we got a response, store it in the cache */
997 dns = Curl_cache_addr(data, ai, data->req.doh.host, data->req.doh.port);
998
999 if(data->share)
1000 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1001
1002 if(!dns) {
1003 /* returned failure, bail out nicely */
1004 Curl_freeaddrinfo(ai);
1005 }
1006 else {
1007 conn->async.dns = dns;
1008 *dnsp = dns;
1009 result = CURLE_OK; /* address resolution OK */
1010 }
1011 } /* address processing done */
1012
1013 /* Now process any build-specific attributes retrieved from DNS */
1014
1015 /* All done */
1016 de_cleanup(&de);
1017 return result;
1018
1019 } /* !data->req.doh.pending */
1020
1021 /* else wait for pending DOH transactions to complete */
1022 return CURLE_OK;
1023 }
1024
1025 #endif /* CURL_DISABLE_DOH */