Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/vdns/doh.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#ifndef CURL_DISABLE_DOH
27
28
#include "urldata.h"
29
#include "curl_addrinfo.h"
30
#include "curl_trc.h"
31
#include "multiif.h"
32
#include "url.h"
33
#include "connect.h"
34
#include "vdns/doh.h"
35
#include "vdns/httpsrr.h"
36
#include "curlx/strdup.h"
37
#include "curlx/dynbuf.h"
38
#include "escape.h"  /* for Curl_hexencode() */
39
#include "urlapi-int.h"
40
41
13.5k
#define DNS_CLASS_IN 0x01
42
43
static void doh_close(struct Curl_easy *data,
44
                      struct Curl_resolv_async *async);
45
46
#ifdef CURLVERBOSE
47
static const char * const doh_code_str[] = {
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
  "Name too long",
62
  "No such name",
63
  "Transport failed",
64
  "Out Of Memory"
65
};
66
67
static const char *doh_strerror(DOHcode code)
68
2
{
69
2
  if((size_t)code < CURL_ARRAYSIZE(doh_code_str))
70
2
    return doh_code_str[code];
71
0
  return "bad error code";
72
2
}
73
74
static const char *doh_type2name(DNStype dnstype)
75
128
{
76
128
  switch(dnstype) {
77
37
  case CURL_DNS_TYPE_A:
78
37
    return "A";
79
45
  case CURL_DNS_TYPE_AAAA:
80
45
    return "AAAA";
81
0
#ifdef USE_HTTPSRR
82
46
  case CURL_DNS_TYPE_HTTPS:
83
46
    return "HTTPS";
84
0
#endif
85
0
  default:
86
0
    return "unknown";
87
128
  }
88
128
}
89
90
#endif /* CURLVERBOSE */
91
92
/* @unittest 1655
93
 */
94
UNITTEST DOHcode doh_req_encode(const char *host,
95
                                DNStype dnstype,
96
                                unsigned char *dnsp,  /* buffer */
97
                                size_t len,  /* buffer size */
98
                                size_t *olen);  /* output length */
99
UNITTEST DOHcode doh_req_encode(const char *host,
100
                                DNStype dnstype,
101
                                unsigned char *dnsp, /* buffer */
102
                                size_t len,   /* buffer size */
103
                                size_t *olen) /* output length */
104
4.46k
{
105
4.46k
  const size_t hostlen = strlen(host);
106
4.46k
  unsigned char *orig = dnsp;
107
4.46k
  const char *hostp = host;
108
109
  /* The expected output length is 16 bytes more than the length of
110
   * the QNAME-encoding of the hostname.
111
   *
112
   * A valid DNS name may not contain a zero-length label, except at
113
   * the end. For this reason, a name beginning with a dot, or
114
   * containing a sequence of two or more consecutive dots, is invalid
115
   * and cannot be encoded as a QNAME.
116
   *
117
   * If the hostname ends with a trailing dot, the corresponding
118
   * QNAME-encoding is one byte longer than the hostname. If (as is
119
   * also valid) the hostname is shortened by the omission of the
120
   * trailing dot, then its QNAME-encoding will be two bytes longer
121
   * than the hostname.
122
   *
123
   * Each [ label, dot ] pair is encoded as [ length, label ],
124
   * preserving overall length. A final [ label ] without a dot is
125
   * also encoded as [ length, label ], increasing overall length
126
   * by one. The encoding is completed by appending a NUL byte,
127
   * representing the zero-length root label, again increasing
128
   * the overall length by one.
129
   */
130
131
4.46k
  size_t expected_len;
132
4.46k
  DEBUGASSERT(hostlen);
133
4.46k
  expected_len = 12 + 1 + hostlen + 4;
134
4.46k
  if(host[hostlen - 1] != '.')
135
4.44k
    expected_len++;
136
137
4.46k
  if(expected_len > DOH_MAX_DNSREQ_SIZE)
138
36
    return DOH_DNS_NAME_TOO_LONG;
139
140
4.42k
  if(len < expected_len)
141
0
    return DOH_TOO_SMALL_BUFFER;
142
143
4.42k
  *dnsp++ = 0; /* 16-bit id */
144
4.42k
  *dnsp++ = 0;
145
4.42k
  *dnsp++ = 0x01; /* |QR|   Opcode  |AA|TC|RD| Set the RD bit */
146
4.42k
  *dnsp++ = '\0'; /* |RA|   Z    |   RCODE   |                */
147
4.42k
  *dnsp++ = '\0';
148
4.42k
  *dnsp++ = 1;    /* QDCOUNT (number of entries in the question section) */
149
4.42k
  *dnsp++ = '\0';
150
4.42k
  *dnsp++ = '\0'; /* ANCOUNT */
151
4.42k
  *dnsp++ = '\0';
152
4.42k
  *dnsp++ = '\0'; /* NSCOUNT */
153
4.42k
  *dnsp++ = '\0';
154
4.42k
  *dnsp++ = '\0'; /* ARCOUNT */
155
156
  /* encode each label and store it in the QNAME */
157
13.5k
  while(*hostp) {
158
9.11k
    size_t labellen;
159
9.11k
    const char *dot = strchr(hostp, '.');
160
9.11k
    if(dot)
161
4.70k
      labellen = dot - hostp;
162
4.40k
    else
163
4.40k
      labellen = strlen(hostp);
164
9.11k
    if((labellen > 63) || (!labellen)) {
165
      /* label is too long or too short, error out */
166
29
      *olen = 0;
167
29
      return DOH_DNS_BAD_LABEL;
168
29
    }
169
    /* label is non-empty, process it */
170
9.08k
    *dnsp++ = (unsigned char)labellen;
171
9.08k
    memcpy(dnsp, hostp, labellen);
172
9.08k
    dnsp += labellen;
173
9.08k
    hostp += labellen;
174
    /* advance past dot, but only if there is one */
175
9.08k
    if(dot)
176
4.69k
      hostp++;
177
9.08k
  } /* next label */
178
179
4.39k
  *dnsp++ = 0; /* append zero-length label for root */
180
181
  /* There are assigned TYPE codes beyond 255: use range [1..65535] */
182
4.39k
  *dnsp++ = (unsigned char)(255 & (dnstype >> 8)); /* upper 8-bit TYPE */
183
4.39k
  *dnsp++ = (unsigned char)(255 & dnstype);        /* lower 8-bit TYPE */
184
185
4.39k
  *dnsp++ = '\0'; /* upper 8-bit CLASS */
186
4.39k
  *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
187
188
4.39k
  *olen = dnsp - orig;
189
190
  /* verify that our estimation of length is valid, since
191
   * this has led to buffer overflows in this function */
192
4.39k
  DEBUGASSERT(*olen == expected_len);
193
4.39k
  return DOH_OK;
194
4.39k
}
195
196
static size_t doh_probe_write_cb(char *contents, size_t size, size_t nmemb,
197
                                 void *userp)
198
3.39k
{
199
3.39k
  size_t realsize = size * nmemb;
200
3.39k
  struct Curl_easy *data = userp;
201
3.39k
  struct doh_request *doh_req = Curl_meta_get(data, CURL_EZM_DOH_PROBE);
202
3.39k
  if(!doh_req)
203
0
    return CURL_WRITEFUNC_ERROR;
204
205
3.39k
  if(curlx_dyn_addn(&doh_req->resp_body, contents, realsize))
206
0
    return 0;
207
208
3.39k
  return realsize;
209
3.39k
}
210
211
static void doh_probe_done(struct Curl_easy *doh,
212
                           struct Curl_easy *master, CURLcode result);
213
static void doh_probe_dtor(const void *key, size_t klen, void *e)
214
4.33k
{
215
4.33k
  (void)key;
216
4.33k
  (void)klen;
217
4.33k
  if(e) {
218
4.33k
    struct doh_request *doh_req = e;
219
4.33k
    curl_slist_free_all(doh_req->req_hds);
220
4.33k
    curlx_dyn_free(&doh_req->resp_body);
221
4.33k
    curlx_free(e);
222
4.33k
  }
223
4.33k
}
224
225
#define ERROR_CHECK_SETOPT(x, y)                        \
226
51.8k
  do {                                                  \
227
51.8k
    result = curl_easy_setopt((CURL *)doh, x, y);       \
228
51.8k
    if(result &&                                        \
229
51.8k
       result != CURLE_NOT_BUILT_IN &&                  \
230
51.8k
       result != CURLE_UNKNOWN_OPTION)                  \
231
51.8k
      goto error;                                       \
232
51.8k
  } while(0)
233
234
static CURLcode doh_probe_run(struct Curl_easy *data,
235
                              DNStype dnstype,
236
                              const char *host,
237
                              const char *url, CURLM *multi,
238
                              uint32_t resolv_id,
239
                              uint32_t *pmid)
240
4.35k
{
241
4.35k
  struct Curl_easy *doh = NULL;
242
4.35k
  CURLcode result = CURLE_OK;
243
4.35k
  timediff_t timeout_ms;
244
4.35k
  struct doh_request *doh_req;
245
4.35k
  DOHcode d;
246
4.35k
  bool maybe_https = !curl_strnequal(url, STRCONST("http:"));
247
248
4.35k
  *pmid = UINT32_MAX;
249
250
4.35k
  doh_req = curlx_calloc(1, sizeof(*doh_req));
251
4.35k
  if(!doh_req)
252
15
    return CURLE_OUT_OF_MEMORY;
253
4.33k
  doh_req->resolv_id = resolv_id;
254
4.33k
  doh_req->dnstype = dnstype;
255
4.33k
  curlx_dyn_init(&doh_req->resp_body, DYN_DOH_RESPONSE);
256
257
4.33k
  d = doh_req_encode(host, dnstype, doh_req->req_body,
258
4.33k
                     sizeof(doh_req->req_body),
259
4.33k
                     &doh_req->req_body_len);
260
4.33k
  if(d) {
261
0
    failf(data, "Failed to encode DoH packet [%d]", (int)d);
262
0
    result = CURLE_OUT_OF_MEMORY;
263
0
    goto error;
264
0
  }
265
266
4.33k
  timeout_ms = Curl_timeleft_ms(data);
267
4.33k
  if(timeout_ms < 0) {
268
0
    result = CURLE_OPERATION_TIMEDOUT;
269
0
    goto error;
270
0
  }
271
272
4.33k
  doh_req->req_hds =
273
4.33k
    curl_slist_append(NULL, "Content-Type: application/dns-message");
274
4.33k
  if(!doh_req->req_hds) {
275
22
    result = CURLE_OUT_OF_MEMORY;
276
22
    goto error;
277
22
  }
278
279
  /* Curl_open() is the internal version of curl_easy_init() */
280
4.31k
  result = Curl_open(&doh);
281
4.31k
  if(result)
282
9
    goto error;
283
284
  /* pass in the struct pointer via a local variable to please coverity and
285
     the gcc typecheck helpers */
286
4.30k
  VERBOSE(doh->state.feat = &Curl_trc_feat_doh);
287
4.30k
  ERROR_CHECK_SETOPT(CURLOPT_URL, url);
288
4.29k
  ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https");
289
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_probe_write_cb);
290
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, doh);
291
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, doh_req->req_body);
292
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)doh_req->req_body_len);
293
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, doh_req->req_hds);
294
4.28k
#ifdef USE_HTTP2
295
4.28k
  if(maybe_https) {
296
678
    ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
297
678
    ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L);
298
678
  }
299
4.28k
#endif
300
#ifndef DEBUGBUILD
301
  /* enforce HTTPS if not debug */
302
  ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
303
#else
304
  /* in debug mode, also allow http */
305
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
306
4.28k
#endif
307
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
308
4.28k
  ERROR_CHECK_SETOPT(CURLOPT_SHARE, (CURLSH *)data->share);
309
4.28k
  if(data->set.err && data->set.err != stderr)
310
91
    ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err);
311
4.28k
  if(Curl_trc_ft_is_verbose(data, &Curl_trc_feat_doh))
312
304
    ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
313
4.28k
  if(data->set.no_signal)
314
678
    ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
315
4.28k
  if(data->set.fdebug)
316
979
    ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug);
317
4.28k
  if(data->set.debugdata)
318
979
    ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata);
319
320
#ifdef USE_RESOLV_ARES
321
  if(CURL_EASY_STR(data, STRING_DNS_SERVERS)) {
322
    ERROR_CHECK_SETOPT(CURLOPT_DNS_SERVERS,
323
                       CURL_EASY_STR(data, STRING_DNS_SERVERS));
324
  }
325
  if(CURL_EASY_STR(data, STRING_DNS_INTERFACE)) {
326
    ERROR_CHECK_SETOPT(CURLOPT_DNS_INTERFACE,
327
                       CURL_EASY_STR(data, STRING_DNS_INTERFACE));
328
  }
329
  if(CURL_EASY_STR(data, STRING_DNS_LOCAL_IP4)) {
330
    ERROR_CHECK_SETOPT(CURLOPT_DNS_LOCAL_IP4,
331
                       CURL_EASY_STR(data, STRING_DNS_LOCAL_IP4));
332
  }
333
  if(CURL_EASY_STR(data, STRING_DNS_LOCAL_IP6)) {
334
    ERROR_CHECK_SETOPT(CURLOPT_DNS_LOCAL_IP6,
335
                       CURL_EASY_STR(data, STRING_DNS_LOCAL_IP6));
336
  }
337
#endif
338
4.28k
  if(maybe_https) {
339
678
    ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST,
340
678
                       data->set.doh_verifyhost ? 2L : 0L);
341
678
    ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER,
342
678
                       data->set.doh_verifypeer ? 1L : 0L);
343
678
    ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS,
344
678
                       data->set.doh_verifystatus ? 1L : 0L);
345
346
    /* Inherit *some* SSL options from the user's transfer. This is a
347
       best-guess as to which options are needed for compatibility. #3661
348
349
       Note DoH does not inherit the user's proxy server so proxy SSL settings
350
       have no effect and are not inherited. If that changes then two new
351
       options should be added to check doh proxy insecure separately,
352
       CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER.
353
       */
354
678
    doh->set.ssl.custom_cafile = data->set.ssl.custom_cafile;
355
678
    doh->set.ssl.custom_capath = data->set.ssl.custom_capath;
356
678
    doh->set.ssl.custom_cablob = data->set.ssl.custom_cablob;
357
678
    if(CURL_EASY_STR(data, STRING_SSL_CAFILE)) {
358
185
      ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
359
185
                         CURL_EASY_STR(data, STRING_SSL_CAFILE));
360
185
    }
361
677
    if(data->set.a.blobs[BLOB_CAINFO]) {
362
674
      ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB, data->set.a.blobs[BLOB_CAINFO]);
363
674
    }
364
672
    if(CURL_EASY_STR(data, STRING_SSL_CAPATH)) {
365
181
      ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
366
181
                         CURL_EASY_STR(data, STRING_SSL_CAPATH));
367
181
    }
368
671
    if(CURL_EASY_STR(data, STRING_SSL_CRLFILE)) {
369
180
      ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
370
180
                         CURL_EASY_STR(data, STRING_SSL_CRLFILE));
371
180
    }
372
668
    if(data->set.ssl.certinfo)
373
668
      ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
374
668
    if(data->set.ssl_fsslctx)
375
41
      ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl_fsslctx);
376
668
    if(data->set.ssl_fsslctxp)
377
41
      ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl_fsslctxp);
378
668
    if(CURL_EASY_STR(data, STRING_SSL_EC_CURVES)) {
379
656
      ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
380
656
                         CURL_EASY_STR(data, STRING_SSL_EC_CURVES));
381
656
    }
382
663
    (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS,
383
663
                           ((long)data->set.ssl.ssl_options &
384
663
                            ~CURLSSLOPT_AUTO_CLIENT_CERT));
385
663
  }
386
387
4.26k
  doh->state.internal = TRUE;
388
4.26k
  doh->master_mid = data->mid; /* master transfer of this one */
389
4.26k
  doh->sub_xfer_done = doh_probe_done;
390
391
4.26k
  result = Curl_meta_set(doh, CURL_EZM_DOH_PROBE, doh_req, doh_probe_dtor);
392
4.26k
  doh_req = NULL; /* call took ownership */
393
4.26k
  if(result)
394
14
    goto error;
395
396
  /* DoH handles must not inherit private_data. The handles may be passed to
397
     the user via callbacks and the user will be able to identify them as
398
     internal handles because private data is not set. The user can then set
399
     private_data via CURLOPT_PRIVATE if they so choose. */
400
4.25k
  DEBUGASSERT(!doh->set.private_data);
401
402
4.25k
  if(Curl_multi_add_handle(multi, doh))
403
0
    goto error;
404
405
4.25k
  *pmid = doh->mid;
406
4.25k
  return CURLE_OK;
407
408
86
error:
409
86
  Curl_close(&doh);
410
86
  if(doh_req)
411
72
    doh_probe_dtor(NULL, 0, doh_req);
412
86
  return result;
413
4.25k
}
414
415
/*
416
 * Curl_doh() starts a name resolve using DoH. It resolves a name and returns
417
 * a 'Curl_addrinfo *' with the address information.
418
 */
419
420
CURLcode Curl_doh(struct Curl_easy *data,
421
                  struct Curl_resolv_async *async)
422
2.92k
{
423
2.92k
  CURLcode result = CURLE_OK;
424
2.92k
  struct doh_probes *dohp = NULL;
425
2.92k
  size_t i;
426
427
2.92k
  DEBUGASSERT(!async->doh);
428
2.92k
  DEBUGASSERT(async->peer->hostname[0]);
429
2.92k
  if(async->doh) {
430
0
    DEBUGASSERT(0); /* should not happen */
431
0
    Curl_doh_cleanup(data, async);
432
0
  }
433
434
2.92k
  if(!async->dns_queries)
435
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
436
2.92k
#ifdef USE_HTTPSRR
437
2.92k
  if(CURL_DNSQ_IS_ADDR(async->dns_queries) &&
438
1.46k
     (async->dns_queries & CURL_DNSQ_HTTPS)) {
439
    /* Cannot mix those in the same async resolve */
440
0
    DEBUGASSERT(0);
441
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
442
0
  }
443
#else
444
  if(async->dns_queries & CURL_DNSQ_HTTPS) {
445
    DEBUGASSERT(0);
446
    return CURLE_NOT_BUILT_IN;
447
  }
448
#endif
449
450
  /* start clean, consider allocating this struct on demand */
451
2.92k
  async->doh = dohp = curlx_calloc(1, sizeof(struct doh_probes));
452
2.92k
  if(!dohp)
453
8
    return CURLE_OUT_OF_MEMORY;
454
455
11.6k
  for(i = 0; i < DOH_SLOT_COUNT; ++i) {
456
8.73k
    dohp->probe_rc[i] = DOH_OK;
457
8.73k
    dohp->probe_mid[i] = UINT32_MAX;
458
8.73k
  }
459
460
2.91k
#ifdef USE_IPV6
461
  /* AAAA results have preference in happy eyeballing, trigger first */
462
2.91k
  if(async->dns_queries & CURL_DNSQ_AAAA) {
463
    /* create IPv6 DoH request */
464
1.45k
    result = doh_probe_run(data, CURL_DNS_TYPE_AAAA,
465
1.45k
                           async->peer->hostname,
466
1.45k
                           CURL_EASY_STR(data, STRING_DOH),
467
1.45k
                           data->multi, async->id,
468
1.45k
                           &dohp->probe_mid[DOH_SLOT_IPV6]);
469
1.45k
    if(result)
470
18
      goto error;
471
1.44k
    async->queries_ongoing++;
472
1.44k
  }
473
2.89k
#endif
474
475
  /* create IPv4 DoH request */
476
2.89k
  if(async->dns_queries & CURL_DNSQ_A) {
477
1.44k
    result = doh_probe_run(data, CURL_DNS_TYPE_A,
478
1.44k
                           async->peer->hostname,
479
1.44k
                           CURL_EASY_STR(data, STRING_DOH),
480
1.44k
                           data->multi, async->id,
481
1.44k
                           &dohp->probe_mid[DOH_SLOT_IPV4]);
482
1.44k
    if(result)
483
20
      goto error;
484
1.42k
    async->queries_ongoing++;
485
1.42k
  }
486
487
2.87k
#ifdef USE_HTTPSRR
488
2.87k
  if(async->dns_queries & CURL_DNSQ_HTTPS) {
489
1.45k
    char *qname = NULL;
490
1.45k
    if(async->peer->port != PORT_HTTPS) {
491
0
      qname = curl_maprintf("_%u._https.%s",
492
0
                            async->peer->port, async->peer->hostname);
493
0
      if(!qname)
494
0
        goto error;
495
0
    }
496
1.45k
    result = doh_probe_run(data, CURL_DNS_TYPE_HTTPS,
497
1.45k
                           qname ? qname : async->peer->hostname,
498
1.45k
                           CURL_EASY_STR(data, STRING_DOH), data->multi,
499
1.45k
                           async->id,
500
1.45k
                           &dohp->probe_mid[DOH_SLOT_HTTPS_RR]);
501
1.45k
    curlx_free(qname);
502
1.45k
    if(result)
503
63
      goto error;
504
1.39k
    async->queries_ongoing++;
505
1.39k
  }
506
2.81k
#endif
507
2.81k
  return CURLE_OK;
508
509
101
error:
510
101
  Curl_doh_cleanup(data, async);
511
101
  return result;
512
2.87k
}
513
514
static DOHcode doh_skipqname(const unsigned char *doh, size_t dohlen,
515
                             unsigned int *indexp)
516
243k
{
517
243k
  unsigned char length;
518
975k
  do {
519
975k
    if(dohlen < (*indexp + 1))
520
225
      return DOH_DNS_OUT_OF_RANGE;
521
975k
    length = doh[*indexp];
522
975k
    if((length & 0xc0) == 0xc0) {
523
      /* name pointer, advance over it and be done */
524
22.8k
      if(dohlen < (*indexp + 2))
525
22
        return DOH_DNS_OUT_OF_RANGE;
526
22.8k
      *indexp += 2;
527
22.8k
      break;
528
22.8k
    }
529
952k
    if(length & 0xc0)
530
59
      return DOH_DNS_BAD_LABEL;
531
952k
    if(dohlen < (*indexp + 1 + length))
532
82
      return DOH_DNS_OUT_OF_RANGE;
533
952k
    *indexp += (unsigned int)(1 + length);
534
952k
  } while(length);
535
242k
  return DOH_OK;
536
243k
}
537
538
static unsigned short doh_get16bit(const unsigned char *doh,
539
                                   unsigned int index)
540
114k
{
541
114k
  return (unsigned short)((doh[index] << 8) | doh[index + 1]);
542
114k
}
543
544
static unsigned int doh_get32bit(const unsigned char *doh, unsigned int index)
545
9.07k
{
546
  /* make clang and gcc optimize this to bswap by incrementing
547
     the pointer first. */
548
9.07k
  doh += index;
549
550
  /* avoid undefined behavior by casting to unsigned before shifting
551
     24 bits, possibly into the sign bit. codegen is same, but
552
     ub sanitizer will not be upset */
553
9.07k
  return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) |
554
9.07k
         ((unsigned)doh[2] << 8) | doh[3];
555
9.07k
}
556
557
static void doh_store_a(const unsigned char *doh, int index,
558
                        struct dohentry *d)
559
1.84k
{
560
  /* silently ignore addresses over the limit */
561
1.84k
  if(d->numaddr < DOH_MAX_ADDR) {
562
1.50k
    struct dohaddr *a = &d->addr[d->numaddr];
563
1.50k
    a->type = CURL_DNS_TYPE_A;
564
1.50k
    memcpy(&a->ip.v4, &doh[index], 4);
565
1.50k
    d->numaddr++;
566
1.50k
  }
567
1.84k
}
568
569
static void doh_store_aaaa(const unsigned char *doh, int index,
570
                           struct dohentry *d)
571
1.79k
{
572
  /* silently ignore addresses over the limit */
573
1.79k
  if(d->numaddr < DOH_MAX_ADDR) {
574
1.47k
    struct dohaddr *a = &d->addr[d->numaddr];
575
1.47k
    a->type = CURL_DNS_TYPE_AAAA;
576
1.47k
    memcpy(&a->ip.v6, &doh[index], 16);
577
1.47k
    d->numaddr++;
578
1.47k
  }
579
1.79k
}
580
581
#ifdef USE_HTTPSRR
582
static DOHcode doh_store_https(const unsigned char *doh, int index,
583
                               struct dohentry *d, uint16_t len)
584
1.64k
{
585
  /* silently ignore RRs over the limit */
586
1.64k
  if(d->numhttps_rrs < DOH_MAX_HTTPS) {
587
1.23k
    struct dohhttps_rr *h = &d->https_rrs[d->numhttps_rrs];
588
1.23k
    h->val = curlx_memdup(&doh[index], len);
589
1.23k
    if(!h->val)
590
0
      return DOH_OUT_OF_MEM;
591
1.23k
    h->len = len;
592
1.23k
    d->numhttps_rrs++;
593
1.23k
  }
594
1.64k
  return DOH_OK;
595
1.64k
}
596
#endif
597
598
static DOHcode doh_rdata(const unsigned char *doh,
599
                         unsigned short rdlength,
600
                         unsigned short type,
601
                         int index,
602
                         struct dohentry *d)
603
8.91k
{
604
  /* RDATA
605
     - A (TYPE 1): 4 bytes
606
     - AAAA (TYPE 28): 16 bytes
607
     - HTTPS (TYPE 65): N bytes */
608
8.91k
  switch(type) {
609
1.84k
  case CURL_DNS_TYPE_A:
610
1.84k
    if(rdlength != 4)
611
5
      return DOH_DNS_RDATA_LEN;
612
1.84k
    doh_store_a(doh, index, d);
613
1.84k
    break;
614
1.81k
  case CURL_DNS_TYPE_AAAA:
615
1.81k
    if(rdlength != 16)
616
26
      return DOH_DNS_RDATA_LEN;
617
1.79k
    doh_store_aaaa(doh, index, d);
618
1.79k
    break;
619
0
#ifdef USE_HTTPSRR
620
1.64k
  case CURL_DNS_TYPE_HTTPS:
621
1.64k
    if(rdlength < 3)
622
3
      return DOH_DNS_RDATA_LEN;
623
1.64k
    return doh_store_https(doh, index, d, rdlength);
624
0
#endif
625
3.60k
  default:
626
    /* unsupported type, or type we do not store, skip it */
627
3.60k
    break;
628
8.91k
  }
629
7.24k
  return DOH_OK;
630
8.91k
}
631
632
/* @unittest 1655 */
633
UNITTEST void de_init(struct dohentry *de);
634
UNITTEST void de_init(struct dohentry *de)
635
5.22k
{
636
5.22k
  memset(de, 0, sizeof(*de));
637
5.22k
  de->ttl = INT_MAX;
638
5.22k
}
639
640
/* TTL value cap */
641
12.3k
#define MAX_DNS_TTL 86400U /* 24 hours */
642
/* @unittest 1650 */
643
UNITTEST DOHcode doh_resp_decode(const unsigned char *doh,
644
                                 size_t dohlen,
645
                                 DNStype dnstype,
646
                                 struct dohentry *d);
647
UNITTEST DOHcode doh_resp_decode(const unsigned char *doh,
648
                                 size_t dohlen,
649
                                 DNStype dnstype,
650
                                 struct dohentry *d)
651
4.52k
{
652
4.52k
  unsigned char rcode;
653
4.52k
  unsigned short qdcount;
654
4.52k
  unsigned short ancount;
655
4.52k
  unsigned short type = 0;
656
4.52k
  unsigned short rdlength;
657
4.52k
  unsigned short nscount;
658
4.52k
  unsigned short arcount;
659
4.52k
  unsigned int index = 12;
660
4.52k
  DOHcode rc;
661
662
4.52k
  if(dohlen < 12)
663
85
    return DOH_TOO_SMALL_BUFFER; /* too small */
664
4.43k
  if(!doh || doh[0] || doh[1])
665
10
    return DOH_DNS_BAD_ID; /* bad ID */
666
4.42k
  rcode = doh[3] & 0x0f;
667
4.42k
  if(rcode == 3)
668
1
    return DOH_DNS_NXDOMAIN; /* name does not exist */
669
4.42k
  if(rcode)
670
5
    return DOH_DNS_BAD_RCODE; /* bad rcode */
671
672
4.42k
  qdcount = doh_get16bit(doh, 4);
673
177k
  while(qdcount) {
674
173k
    rc = doh_skipqname(doh, dohlen, &index);
675
173k
    if(rc)
676
102
      return rc; /* bad qname */
677
173k
    if(dohlen < (index + 4))
678
56
      return DOH_DNS_OUT_OF_RANGE;
679
173k
    index += 4; /* skip question's type and class */
680
173k
    qdcount--;
681
173k
  }
682
683
4.26k
  ancount = doh_get16bit(doh, 6);
684
13.1k
  while(ancount) {
685
9.41k
    unsigned short dnsclass;
686
9.41k
    unsigned int ttl;
687
688
9.41k
    rc = doh_skipqname(doh, dohlen, &index);
689
9.41k
    if(rc)
690
155
      return rc; /* bad qname */
691
692
9.26k
    if(dohlen < (index + 2))
693
25
      return DOH_DNS_OUT_OF_RANGE;
694
695
9.23k
    type = doh_get16bit(doh, index);
696
9.23k
    if((type != CURL_DNS_TYPE_CNAME) &&  /* may be synthesized from DNAME */
697
5.82k
       (type != CURL_DNS_TYPE_DNAME) &&  /* if present, accept and ignore */
698
5.46k
       (type != dnstype))
699
      /* Not the same type as was asked for, nor CNAME nor DNAME */
700
90
      return DOH_DNS_UNEXPECTED_TYPE;
701
9.14k
    index += 2;
702
703
9.14k
    if(dohlen < (index + 2))
704
34
      return DOH_DNS_OUT_OF_RANGE;
705
9.11k
    dnsclass = doh_get16bit(doh, index);
706
9.11k
    if(DNS_CLASS_IN != dnsclass)
707
28
      return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
708
9.08k
    index += 2;
709
710
9.08k
    if(dohlen < (index + 4))
711
10
      return DOH_DNS_OUT_OF_RANGE;
712
713
9.07k
    ttl = doh_get32bit(doh, index);
714
9.07k
    if(ttl > MAX_DNS_TTL)
715
3.29k
      ttl = MAX_DNS_TTL;
716
9.07k
    if(ttl < d->ttl)
717
3.84k
      d->ttl = ttl;
718
9.07k
    index += 4;
719
720
9.07k
    if(dohlen < (index + 2))
721
120
      return DOH_DNS_OUT_OF_RANGE;
722
723
8.95k
    rdlength = doh_get16bit(doh, index);
724
8.95k
    index += 2;
725
8.95k
    if(dohlen < (index + rdlength))
726
38
      return DOH_DNS_OUT_OF_RANGE;
727
728
8.91k
    rc = doh_rdata(doh, rdlength, type, (int)index, d);
729
8.91k
    if(rc)
730
34
      return rc;
731
8.88k
    index += rdlength;
732
8.88k
    ancount--;
733
8.88k
  }
734
735
3.72k
  nscount = doh_get16bit(doh, 8);
736
43.8k
  while(nscount) {
737
40.2k
    rc = doh_skipqname(doh, dohlen, &index);
738
40.2k
    if(rc)
739
68
      return rc; /* bad qname */
740
741
40.1k
    if(dohlen < (index + 8))
742
47
      return DOH_DNS_OUT_OF_RANGE;
743
744
40.1k
    index += 2 + 2 + 4; /* type, dnsclass and ttl */
745
746
40.1k
    if(dohlen < (index + 2))
747
18
      return DOH_DNS_OUT_OF_RANGE;
748
749
40.1k
    rdlength = doh_get16bit(doh, index);
750
40.1k
    index += 2;
751
40.1k
    if(dohlen < (index + rdlength))
752
48
      return DOH_DNS_OUT_OF_RANGE;
753
40.0k
    index += rdlength;
754
40.0k
    nscount--;
755
40.0k
  }
756
757
3.54k
  arcount = doh_get16bit(doh, 10);
758
23.5k
  while(arcount) {
759
20.1k
    rc = doh_skipqname(doh, dohlen, &index);
760
20.1k
    if(rc)
761
63
      return rc; /* bad qname */
762
763
20.1k
    if(dohlen < (index + 8))
764
45
      return DOH_DNS_OUT_OF_RANGE;
765
766
20.0k
    index += 2 + 2 + 4; /* type, dnsclass and ttl */
767
768
20.0k
    if(dohlen < (index + 2))
769
16
      return DOH_DNS_OUT_OF_RANGE;
770
771
20.0k
    rdlength = doh_get16bit(doh, index);
772
20.0k
    index += 2;
773
20.0k
    if(dohlen < (index + rdlength))
774
53
      return DOH_DNS_OUT_OF_RANGE;
775
19.9k
    index += rdlength;
776
19.9k
    arcount--;
777
19.9k
  }
778
779
3.37k
  if(index != dohlen)
780
53
    return DOH_DNS_MALFORMAT; /* something is wrong */
781
782
3.31k
  return DOH_OK; /* ok */
783
3.37k
}
784
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
 * an 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
2.21k
{
798
2.21k
  struct Curl_addrinfo *ai;
799
2.21k
  struct Curl_addrinfo *prevai = NULL;
800
2.21k
  struct Curl_addrinfo *firstai = NULL;
801
2.21k
  struct sockaddr_in *addr;
802
2.21k
#ifdef USE_IPV6
803
2.21k
  struct sockaddr_in6 *addr6;
804
2.21k
#endif
805
2.21k
  size_t hostlen = strlen(hostname) + 1; /* include null-terminator */
806
2.21k
  CURLcode result = CURLE_OK;
807
2.21k
  int i;
808
809
4.43k
  for(i = 0; i < de->numaddr; i++) {
810
2.21k
    size_t ss_size;
811
2.21k
    CURL_SA_FAMILY_T addrtype;
812
2.21k
    if(de->addr[i].type == CURL_DNS_TYPE_AAAA) {
813
#ifndef USE_IPV6
814
      /* we cannot handle IPv6 addresses */
815
      continue;
816
#else
817
1.14k
      ss_size = sizeof(struct sockaddr_in6);
818
1.14k
      addrtype = AF_INET6;
819
1.14k
#endif
820
1.14k
    }
821
1.06k
    else {
822
1.06k
      ss_size = sizeof(struct sockaddr_in);
823
1.06k
      addrtype = AF_INET;
824
1.06k
    }
825
826
2.21k
    ai = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
827
2.21k
    if(!ai) {
828
0
      result = CURLE_OUT_OF_MEMORY;
829
0
      break;
830
0
    }
831
2.21k
    ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
832
2.21k
    ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
833
2.21k
    memcpy(ai->ai_canonname, hostname, hostlen);
834
835
2.21k
    if(!firstai)
836
      /* store the pointer we want to return from this function */
837
2.21k
      firstai = ai;
838
839
2.21k
    if(prevai)
840
      /* make the previous entry point to this */
841
0
      prevai->ai_next = ai;
842
843
2.21k
    ai->ai_family = addrtype;
844
845
    /* we return all names as STREAM, so when using this address for TFTP
846
       the type must be ignored and conn->socktype be used instead! */
847
2.21k
    ai->ai_socktype = SOCK_STREAM;
848
849
2.21k
    ai->ai_addrlen = (curl_socklen_t)ss_size;
850
851
    /* leave the rest of the struct filled with zero */
852
853
2.21k
    switch(ai->ai_family) {
854
1.06k
    case AF_INET:
855
1.06k
      addr = (void *)ai->ai_addr; /* storage area for this info */
856
1.06k
      DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
857
1.06k
      memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
858
1.06k
      addr->sin_family = addrtype;
859
1.06k
      addr->sin_port = htons((unsigned short)port);
860
1.06k
      break;
861
862
0
#ifdef USE_IPV6
863
1.14k
    case AF_INET6:
864
1.14k
      addr6 = (void *)ai->ai_addr; /* storage area for this info */
865
1.14k
      DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
866
1.14k
      memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
867
1.14k
      addr6->sin6_family = addrtype;
868
1.14k
      addr6->sin6_port = htons((unsigned short)port);
869
1.14k
      break;
870
2.21k
#endif
871
2.21k
    }
872
873
2.21k
    prevai = ai;
874
2.21k
  }
875
876
2.21k
  if(result) {
877
0
    Curl_freeaddrinfo(firstai);
878
0
    firstai = NULL;
879
0
  }
880
2.21k
  *aip = firstai;
881
882
2.21k
  return result;
883
2.21k
}
884
885
/* @unittest 1655 */
886
UNITTEST void de_cleanup(struct dohentry *d);
887
UNITTEST void de_cleanup(struct dohentry *d)
888
5.22k
{
889
5.22k
#ifdef USE_HTTPSRR
890
5.22k
  int i = 0;
891
6.45k
  for(i = 0; i < d->numhttps_rrs; i++)
892
1.23k
    curlx_safefree(d->https_rrs[i].val);
893
#else
894
  (void)d;
895
#endif
896
5.22k
}
897
898
#ifdef USE_HTTPSRR
899
900
/*
901
 * @brief decode the DNS name in a binary RRData
902
 * @param buf points to the buffer (in/out)
903
 * @param remaining points to the remaining buffer length (in/out)
904
 * @param dnsname returns the string form name on success
905
 * @return is 1 for success, error otherwise
906
 *
907
 * The encoding here is defined in
908
 * https://datatracker.ietf.org/doc/html/rfc1035#section-3.1
909
 *
910
 * The input buffer pointer will be modified so it points to after the end of
911
 * the DNS name encoding on output. (that is why it is an "unsigned char
912
 * **" :-)
913
 */
914
static CURLcode doh_decode_rdata_name(const unsigned char **buf,
915
                                      size_t *remaining, char **dnsname)
916
2.06k
{
917
2.06k
  const unsigned char *cp = NULL;
918
2.06k
  size_t rem = 0;
919
2.06k
  unsigned char clen = 0; /* chunk len */
920
2.06k
  struct dynbuf thename;
921
922
2.06k
  DEBUGASSERT(buf && remaining && dnsname);
923
2.06k
  if(!buf || !remaining || !dnsname || !*remaining)
924
0
    return CURLE_OUT_OF_MEMORY;
925
2.06k
  curlx_dyn_init(&thename, CURL_MAXLEN_HOST_NAME);
926
2.06k
  rem = *remaining;
927
2.06k
  cp = *buf;
928
2.06k
  clen = *cp++;
929
  /* RFC 9460 says it must be uncompressed */
930
2.06k
  if(clen > 63)
931
2
    return CURLE_WEIRD_SERVER_REPLY;
932
933
2.05k
  if(clen == 0) {
934
    /* special case - return "." as name */
935
1.89k
    if(curlx_dyn_addn(&thename, ".", 1))
936
0
      return CURLE_OUT_OF_MEMORY;
937
1.89k
  }
938
2.61k
  while(clen) {
939
621
    if(clen >= rem) {
940
13
      curlx_dyn_free(&thename);
941
13
      return CURLE_OUT_OF_MEMORY;
942
13
    }
943
608
    if(curlx_dyn_addn(&thename, cp, clen) ||
944
598
       curlx_dyn_addn(&thename, ".", 1))
945
11
      return CURLE_TOO_LARGE;
946
947
597
    cp += clen;
948
597
    rem -= (clen + 1);
949
597
    if(rem <= 0) {
950
30
      curlx_dyn_free(&thename);
951
30
      return CURLE_OUT_OF_MEMORY;
952
30
    }
953
567
    clen = *cp++;
954
567
    if(clen > 63) {
955
      /* invalid format */
956
7
      curlx_dyn_free(&thename);
957
7
      return CURLE_WEIRD_SERVER_REPLY;
958
7
    }
959
567
  }
960
1.99k
  *buf = cp;
961
1.99k
  *remaining = rem - 1;
962
1.99k
  *dnsname = curlx_dyn_ptr(&thename);
963
1.99k
  return CURLE_OK;
964
2.05k
}
965
966
/* scan for byte values <= 32 or 127 */
967
static CURLcode junkscan(const char *url)
968
1.99k
{
969
1.99k
  const unsigned char *p = (const unsigned char *)url;
970
6.84k
  while(*p) {
971
4.86k
    if(*p <= 0x20 || *p == 127)
972
15
      return CURLE_WEIRD_SERVER_REPLY;
973
4.84k
    p++;
974
4.84k
  }
975
1.98k
  return CURLE_OK;
976
1.99k
}
977
978
/* @unittest 1658 */
979
UNITTEST CURLcode doh_resp_decode_httpsrr(struct Curl_easy *data,
980
                                          const unsigned char *cp, size_t len,
981
                                          struct Curl_https_rrinfo **hrr);
982
UNITTEST CURLcode doh_resp_decode_httpsrr(struct Curl_easy *data,
983
                                          const unsigned char *cp, size_t len,
984
                                          struct Curl_https_rrinfo **hrr)
985
2.06k
{
986
2.06k
  uint16_t pcode = 0, plen = 0;
987
2.06k
  uint32_t expected_min_pcode = 0;
988
2.06k
  struct Curl_https_rrinfo *lhrr = NULL;
989
2.06k
  char *dnsname = NULL;
990
2.06k
  CURLcode result = CURLE_OUT_OF_MEMORY;
991
992
2.06k
  (void)data;
993
2.06k
  *hrr = NULL;
994
2.06k
  if(len <= 2)
995
2
    return CURLE_BAD_FUNCTION_ARGUMENT;
996
2.06k
  lhrr = curlx_calloc(1, sizeof(struct Curl_https_rrinfo));
997
2.06k
  if(!lhrr)
998
0
    return CURLE_OUT_OF_MEMORY;
999
2.06k
  lhrr->priority = doh_get16bit(cp, 0);
1000
2.06k
  cp += 2;
1001
2.06k
  len -= 2;
1002
2.06k
  if(doh_decode_rdata_name(&cp, &len, &dnsname) != CURLE_OK)
1003
63
    goto err;
1004
1.99k
  lhrr->target = dnsname;
1005
1.99k
  result = junkscan(dnsname);
1006
1.99k
  if(result) {
1007
    /* unacceptable hostname content */
1008
15
    goto err;
1009
15
  }
1010
6.26k
  while(len >= 4) {
1011
4.51k
    pcode = doh_get16bit(cp, 0);
1012
4.51k
    plen = doh_get16bit(cp, 2);
1013
4.51k
    cp += 4;
1014
4.51k
    len -= 4;
1015
4.51k
    if(pcode < expected_min_pcode || plen > len) {
1016
78
      result = CURLE_WEIRD_SERVER_REPLY;
1017
78
      goto err;
1018
78
    }
1019
4.44k
    result = Curl_httpsrr_set(lhrr, pcode, cp, plen);
1020
4.44k
    if(result)
1021
158
      goto err;
1022
4.28k
    Curl_httpsrr_trace(data, lhrr);
1023
4.28k
    cp += plen;
1024
4.28k
    len -= plen;
1025
4.28k
    expected_min_pcode = pcode + 1;
1026
4.28k
  }
1027
1.74k
  *hrr = lhrr;
1028
1.74k
  return CURLE_OK;
1029
314
err:
1030
314
  Curl_httpsrr_destroy(lhrr);
1031
314
  return result;
1032
1.98k
}
1033
1034
#endif /* USE_HTTPSRR */
1035
1036
/* called from multi when a sub transfer, e.g. doh probe, is done.
1037
 * Parse the response and set the results in the `async` context
1038
 * of master, using the id from the probe's CURL_EZM_DOH_PROBE
1039
 * meta data. */
1040
static void doh_probe_done(struct Curl_easy *doh,
1041
                           struct Curl_easy *master, CURLcode result)
1042
4.09k
{
1043
4.09k
  struct Curl_resolv_async *async = NULL;
1044
4.09k
  struct doh_probes *dohp = NULL;
1045
4.09k
  struct doh_request *doh_req = NULL;
1046
4.09k
  struct Curl_addrinfo **pdest_ai;
1047
4.09k
  struct dohentry de;
1048
4.09k
  int slot, httpcode;
1049
1050
4.09k
  de_init(&de);
1051
4.09k
  doh_req = Curl_meta_get(doh, CURL_EZM_DOH_PROBE);
1052
4.09k
  if(!doh_req) {
1053
    /* transfer `doh` is not a DoH probe. */
1054
0
    DEBUGASSERT(0);
1055
0
    goto out;
1056
0
  }
1057
1058
4.09k
  async = Curl_async_get(master, doh_req->resolv_id);
1059
4.09k
  if(!async) {
1060
0
    CURL_TRC_DNS(master, "[%u] ignoring outdated DoH response",
1061
0
                 doh_req->resolv_id);
1062
0
    goto out;
1063
0
  }
1064
4.09k
  dohp = async->doh;
1065
1066
8.24k
  for(slot = 0; slot < DOH_SLOT_COUNT; ++slot) {
1067
8.24k
    if(dohp->probe_mid[slot] == doh->mid)
1068
4.09k
      break;
1069
8.24k
  }
1070
  /* We really should have found the slot where to store the response */
1071
4.09k
  if(slot >= DOH_SLOT_COUNT) {
1072
0
    failf(master, "DoH: unknown sub request done");
1073
0
    DEBUGASSERT(0);
1074
0
    goto out;
1075
0
  }
1076
1077
4.09k
  async->queries_ongoing--;
1078
4.09k
  dohp = async->doh;
1079
4.09k
  httpcode = doh->info.httpcode;
1080
4.09k
  switch(slot) {
1081
1.31k
  case DOH_SLOT_IPV4:
1082
1.31k
    async->dns_responses |= CURL_DNSQ_A;
1083
1.31k
    break;
1084
0
#ifdef USE_IPV6
1085
1.42k
  case DOH_SLOT_IPV6:
1086
1.42k
    async->dns_responses |= CURL_DNSQ_AAAA;
1087
1.42k
    break;
1088
0
#endif
1089
0
#ifdef USE_HTTPSRR
1090
1.36k
  case DOH_SLOT_HTTPS_RR:
1091
1.36k
    async->dns_responses |= CURL_DNSQ_HTTPS;
1092
1.36k
    break;
1093
0
#endif
1094
0
  default:
1095
0
    DEBUGASSERT(0);
1096
0
    break;
1097
4.09k
  }
1098
1099
4.09k
  if(result) {
1100
554
    dohp->probe_rc[slot] = DOH_HTTP_FAILED;
1101
554
    infof(doh, "[DoH] [%s] error: %s",
1102
554
          doh_type2name(doh_req->dnstype), curl_easy_strerror(result));
1103
554
    goto out;
1104
554
  }
1105
3.54k
  else if((httpcode < 200) || (httpcode >= 300)) {
1106
148
    dohp->probe_rc[slot] = DOH_HTTP_FAILED;
1107
148
    infof(doh, "[DoH] [%s] error: HTTP status %d",
1108
148
          doh_type2name(doh_req->dnstype), httpcode);
1109
148
    goto out;
1110
148
  }
1111
1112
3.39k
  dohp->probe_rc[slot] = doh_resp_decode(curlx_dyn_uptr(&doh_req->resp_body),
1113
3.39k
                                         curlx_dyn_len(&doh_req->resp_body),
1114
3.39k
                                         doh_req->dnstype, &de);
1115
3.39k
  if(dohp->probe_rc[slot]) {
1116
79
#ifdef USE_HTTPSRR
1117
79
    if((dohp->probe_rc[slot] == DOH_NO_CONTENT) &&
1118
0
       (doh_req->dnstype == CURL_DNS_TYPE_HTTPS)) {
1119
0
      dohp->probe_rc[slot] = DOH_DNS_NXDOMAIN;
1120
0
    }
1121
79
#endif
1122
79
    infof(doh, "[DoH] [%s] error decoding response: %s",
1123
79
          doh_type2name(doh_req->dnstype),
1124
79
          doh_strerror(dohp->probe_rc[slot]));
1125
79
    goto out;
1126
79
  }
1127
1128
3.31k
  if(doh_req->dnstype == CURL_DNS_TYPE_A)
1129
1.06k
    pdest_ai = &async->ai_A;
1130
2.24k
  else if(doh_req->dnstype == CURL_DNS_TYPE_AAAA)
1131
1.14k
    pdest_ai = &async->ai_AAAA;
1132
1.09k
  else
1133
1.09k
    pdest_ai = NULL;
1134
1135
3.31k
  if(pdest_ai && de.numaddr) {
1136
2.21k
    if(*pdest_ai) {
1137
0
      Curl_freeaddrinfo(*pdest_ai);
1138
0
      *pdest_ai = NULL;
1139
0
    }
1140
2.21k
    result = doh2ai(&de, async->peer->hostname, async->peer->port, pdest_ai);
1141
2.21k
    if(result) { /* hard failure on our side, fail completely */
1142
0
      infof(doh, "[DoH] [%s] error creating addrinfo: %s",
1143
0
            doh_type2name(doh_req->dnstype), curl_easy_strerror(result));
1144
0
      dohp->probe_rc[slot] = DOH_OOM;
1145
0
      async->result = result;
1146
0
    }
1147
2.21k
  }
1148
1.09k
#ifdef USE_HTTPSRR
1149
1.09k
  else if((doh_req->dnstype == CURL_DNS_TYPE_HTTPS) && de.numhttps_rrs) {
1150
1.09k
    CURL_TRC_DNS(doh, "[HTTPS] got %d records", de.numhttps_rrs);
1151
1.09k
    result = doh_resp_decode_httpsrr(doh, de.https_rrs->val,
1152
1.09k
                                     de.https_rrs->len, &async->httpsrr);
1153
1.09k
    if(result) {
1154
0
      dohp->probe_rc[slot] = DOH_HTTP_FAILED;
1155
0
      infof(doh, "[DoH] error decoding HTTPS RR: %s",
1156
0
            curl_easy_strerror(result));
1157
0
      goto out;
1158
0
    }
1159
1.09k
  }
1160
3.31k
#endif /* USE_HTTPSRR */
1161
1162
  /* DoH request complete, run master to act on results */
1163
3.31k
  infof(doh, "DoH request complete, %u to go", async->queries_ongoing);
1164
1165
4.09k
out:
1166
4.09k
  Curl_multi_mark_dirty(master);
1167
4.09k
  de_cleanup(&de);
1168
4.09k
  Curl_meta_remove(doh, CURL_EZM_DOH_PROBE);
1169
4.09k
}
1170
1171
CURLcode Curl_doh_take_result(struct Curl_easy *data,
1172
                              struct Curl_resolv_async *async,
1173
                              struct Curl_dns_entry **pdns)
1174
11.4k
{
1175
11.4k
  struct doh_probes *dohp = async->doh;
1176
11.4k
  CURLcode result = CURLE_OK;
1177
1178
11.4k
  *pdns = NULL; /* defaults to no response */
1179
11.4k
  if(!dohp)
1180
0
    return CURLE_OUT_OF_MEMORY;
1181
1182
11.4k
  async->negative_answer = FALSE;
1183
11.4k
  if(async->result) {
1184
0
    result = async->result;
1185
0
    goto out;
1186
0
  }
1187
1188
11.4k
  if(CURL_DNSQ_IS_ADDR(async->dns_queries) &&
1189
6.14k
     dohp->probe_mid[DOH_SLOT_IPV4] == UINT32_MAX &&
1190
0
     dohp->probe_mid[DOH_SLOT_IPV6] == UINT32_MAX) {
1191
0
    failf(data, "Could not DoH-resolve: %s", async->peer->hostname);
1192
0
    return async->for_proxy ?
1193
0
      CURLE_COULDNT_RESOLVE_PROXY : CURLE_COULDNT_RESOLVE_HOST;
1194
0
  }
1195
11.4k
  else if(!async->queries_ongoing) {
1196
2.67k
    struct Curl_dns_entry *dns = NULL;
1197
2.67k
    bool negative = TRUE;
1198
2.67k
    int slot;
1199
1200
    /* remove DoH handles from multi handle and close them */
1201
2.67k
    doh_close(data, async);
1202
    /* parse the responses, create the struct and return it! */
1203
10.7k
    for(slot = 0; slot < DOH_SLOT_COUNT; slot++) {
1204
      /* Failing without an NXDOMAIN answer - a SERVFAIL-class rcode or
1205
         an undecodable response - says nothing about the name. Such a
1206
         failure must not be cached as a negative entry. */
1207
8.02k
      if(dohp->probe_rc[slot] && (dohp->probe_rc[slot] != DOH_DNS_NXDOMAIN))
1208
781
        negative = FALSE;
1209
8.02k
    } /* next slot */
1210
1211
2.67k
    if(async->ai_A || async->ai_AAAA) {
1212
1.07k
      dns = Curl_dnsc_mk_addr2(
1213
1.07k
        data, async->dns_queries, &async->ai_A, &async->ai_AAAA, async->peer);
1214
1.07k
      if(!dns) {
1215
0
        result = CURLE_OUT_OF_MEMORY;
1216
0
        goto out;
1217
0
      }
1218
1.07k
    }
1219
1.60k
#ifdef USE_HTTPSRR
1220
1.60k
    else if((async->dns_queries & CURL_DNSQ_HTTPS) &&
1221
1.36k
            !dohp->probe_rc[DOH_SLOT_HTTPS_RR]) {
1222
1.09k
      Curl_httpsrr_trace(data, async->httpsrr);
1223
1.09k
      dns = Curl_dnsc_mk_https(data, &async->httpsrr, async->peer);
1224
1.09k
      if(!dns) {
1225
0
        result = CURLE_OUT_OF_MEMORY;
1226
0
        goto out;
1227
0
      }
1228
1.09k
    }
1229
505
#endif /* USE_HTTPSRR */
1230
505
    else {
1231
      /* every query failed. Only NXDOMAIN answers for all of them
1232
         make this a negative answer, eligible for caching. */
1233
505
      async->negative_answer = negative;
1234
505
      result = async->for_proxy ?
1235
505
        CURLE_COULDNT_RESOLVE_PROXY : CURLE_COULDNT_RESOLVE_HOST;
1236
505
    }
1237
1238
    /* and add the entry to the cache */
1239
2.67k
    if(dns)
1240
2.17k
      result = Curl_dnscache_add(data, dns);
1241
2.67k
    *pdns = dns;
1242
2.67k
  } /* !async->queries_ongoing */
1243
8.80k
  else
1244
    /* wait for pending DoH transactions to complete */
1245
8.80k
    return CURLE_AGAIN;
1246
1247
2.67k
out:
1248
2.67k
  Curl_doh_cleanup(data, async);
1249
2.67k
  return result;
1250
11.4k
}
1251
1252
static void doh_close(struct Curl_easy *data,
1253
                      struct Curl_resolv_async *async)
1254
5.58k
{
1255
5.58k
  struct doh_probes *doh = async ? async->doh : NULL;
1256
5.58k
  if(doh && data->multi) {
1257
5.58k
    struct Curl_easy *probe_data;
1258
5.58k
    uint32_t mid;
1259
5.58k
    size_t slot;
1260
22.3k
    for(slot = 0; slot < DOH_SLOT_COUNT; slot++) {
1261
16.7k
      mid = doh->probe_mid[slot];
1262
16.7k
      if(mid == UINT32_MAX)
1263
12.5k
        continue;
1264
4.25k
      doh->probe_mid[slot] = UINT32_MAX;
1265
      /* should have been called before data is removed from multi handle */
1266
4.25k
      DEBUGASSERT(data->multi);
1267
4.25k
      probe_data = data->multi ? Curl_multi_get_easy(data->multi, mid) : NULL;
1268
4.25k
      if(!probe_data) {
1269
0
        DEBUGF(infof(data, "Curl_doh_close: xfer for mid=%u not found!", mid));
1270
0
        continue;
1271
0
      }
1272
4.25k
      probe_data->sub_xfer_done = NULL; /* No longer interested in result */
1273
      /* data->multi might already be reset at this time */
1274
4.25k
      Curl_multi_remove_handle(data->multi, probe_data);
1275
4.25k
      Curl_close(&probe_data);
1276
4.25k
    }
1277
5.58k
    CURL_TRC_DNS(data, "[DoH] probe done");
1278
5.58k
  }
1279
5.58k
}
1280
1281
void Curl_doh_cleanup(struct Curl_easy *data,
1282
                      struct Curl_resolv_async *async)
1283
24.4k
{
1284
24.4k
  struct doh_probes *dohp = async->doh;
1285
24.4k
  if(dohp) {
1286
2.91k
    doh_close(data, async);
1287
    curlx_safefree(async->doh);
1288
2.91k
  }
1289
24.4k
}
1290
1291
#endif /* CURL_DISABLE_DOH */