Coverage Report

Created: 2026-01-17 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/hostip.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
#ifdef HAVE_NETINET_IN_H
27
#include <netinet/in.h>
28
#endif
29
#ifdef HAVE_NETINET_IN6_H
30
#include <netinet/in6.h>
31
#endif
32
#ifdef HAVE_NETDB_H
33
#include <netdb.h>
34
#endif
35
#ifdef HAVE_ARPA_INET_H
36
#include <arpa/inet.h>
37
#endif
38
#ifdef __VMS
39
#include <in.h>
40
#include <inet.h>
41
#endif
42
43
#include <setjmp.h>  /* for sigjmp_buf, sigsetjmp() */
44
#include <signal.h>
45
46
#include "urldata.h"
47
#include "curl_trc.h"
48
#include "connect.h"
49
#include "hostip.h"
50
#include "hash.h"
51
#include "rand.h"
52
#include "curl_share.h"
53
#include "url.h"
54
#include "curlx/inet_ntop.h"
55
#include "curlx/inet_pton.h"
56
#include "multiif.h"
57
#include "doh.h"
58
#include "progress.h"
59
#include "select.h"
60
#include "strcase.h"
61
#include "easy_lock.h"
62
#include "curlx/strcopy.h"
63
#include "curlx/strparse.h"
64
65
#if defined(CURLRES_SYNCH) &&                   \
66
  defined(HAVE_ALARM) &&                        \
67
  defined(SIGALRM) &&                           \
68
  defined(HAVE_SIGSETJMP) &&                    \
69
  defined(GLOBAL_INIT_IS_THREADSAFE)
70
/* alarm-based timeouts can only be used with all the dependencies satisfied */
71
#define USE_ALARM_TIMEOUT
72
#endif
73
74
#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */
75
76
0
#define MAX_DNS_CACHE_SIZE 29999
77
78
/*
79
 * hostip.c explained
80
 * ==================
81
 *
82
 * The main COMPILE-TIME DEFINES to keep in mind when reading the host*.c
83
 * source file are these:
84
 *
85
 * CURLRES_IPV6 - this host has getaddrinfo() and family, and thus we use
86
 * that. The host may not be able to resolve IPv6, but we do not really have to
87
 * take that into account. Hosts that are not IPv6-enabled have CURLRES_IPV4
88
 * defined.
89
 *
90
 * CURLRES_ARES - is defined if libcurl is built to use c-ares for
91
 * asynchronous name resolves. This can be Windows or *nix.
92
 *
93
 * CURLRES_THREADED - is defined if libcurl is built to run under (native)
94
 * Windows, and then the name resolve will be done in a new thread, and the
95
 * supported API will be the same as for ares-builds.
96
 *
97
 * If any of the two previous are defined, CURLRES_ASYNCH is defined too. If
98
 * libcurl is not built to use an asynchronous resolver, CURLRES_SYNCH is
99
 * defined.
100
 *
101
 * The host*.c sources files are split up like this:
102
 *
103
 * hostip.c   - method-independent resolver functions and utility functions
104
 * hostip4.c  - IPv4 specific functions
105
 * hostip6.c  - IPv6 specific functions
106
 * asyn.h     - common functions for all async resolvers
107
 * The two asynchronous name resolver backends are implemented in:
108
 * asyn-ares.c - async resolver using c-ares
109
 * asyn-thread.c - async resolver using POSIX threads
110
 *
111
 * The hostip.h is the united header file for all this. It defines the
112
 * CURLRES_* defines based on the config*.h and curl_setup.h defines.
113
 */
114
115
#ifndef CURL_DISABLE_VERBOSE_STRINGS
116
static void show_resolve_info(struct Curl_easy *data,
117
                              struct Curl_dns_entry *dns);
118
#else
119
#define show_resolve_info(x, y) Curl_nop_stmt
120
#endif
121
122
static void dnscache_entry_free(struct Curl_dns_entry *dns)
123
0
{
124
0
  Curl_freeaddrinfo(dns->addr);
125
#ifdef USE_HTTPSRR
126
  if(dns->hinfo) {
127
    Curl_httpsrr_cleanup(dns->hinfo);
128
    curlx_free(dns->hinfo);
129
  }
130
#endif
131
0
  curlx_free(dns);
132
0
}
133
134
/*
135
 * Curl_printable_address() stores a printable version of the 1st address
136
 * given in the 'ai' argument. The result will be stored in the buf that is
137
 * bufsize bytes big.
138
 *
139
 * If the conversion fails, the target buffer is empty.
140
 */
141
void Curl_printable_address(const struct Curl_addrinfo *ai, char *buf,
142
                            size_t bufsize)
143
0
{
144
0
  DEBUGASSERT(bufsize);
145
0
  buf[0] = 0;
146
147
0
  switch(ai->ai_family) {
148
0
  case AF_INET: {
149
0
    const struct sockaddr_in *sa4 = (const void *)ai->ai_addr;
150
0
    const struct in_addr *ipaddr4 = &sa4->sin_addr;
151
0
    (void)curlx_inet_ntop(ai->ai_family, (const void *)ipaddr4, buf, bufsize);
152
0
    break;
153
0
  }
154
0
#ifdef USE_IPV6
155
0
  case AF_INET6: {
156
0
    const struct sockaddr_in6 *sa6 = (const void *)ai->ai_addr;
157
0
    const struct in6_addr *ipaddr6 = &sa6->sin6_addr;
158
0
    (void)curlx_inet_ntop(ai->ai_family, (const void *)ipaddr6, buf, bufsize);
159
0
    break;
160
0
  }
161
0
#endif
162
0
  default:
163
0
    break;
164
0
  }
165
0
}
166
167
/*
168
 * Create a hostcache id string for the provided host + port, to be used by
169
 * the DNS caching. Without alloc. Return length of the id string.
170
 */
171
static size_t create_dnscache_id(const char *name,
172
                                 size_t nlen, /* 0 or actual name length */
173
                                 int port, char *ptr, size_t buflen)
174
0
{
175
0
  size_t len = nlen ? nlen : strlen(name);
176
0
  DEBUGASSERT(buflen >= MAX_HOSTCACHE_LEN);
177
0
  if(len > (buflen - 7))
178
0
    len = buflen - 7;
179
  /* store and lower case the name */
180
0
  Curl_strntolower(ptr, name, len);
181
0
  return curl_msnprintf(&ptr[len], 7, ":%u", port) + len;
182
0
}
183
184
struct dnscache_prune_data {
185
  struct curltime now;
186
  timediff_t oldest_ms; /* oldest time in cache not pruned. */
187
  timediff_t max_age_ms;
188
};
189
190
/*
191
 * This function is set as a callback to be called for every entry in the DNS
192
 * cache when we want to prune old unused entries.
193
 *
194
 * Returning non-zero means remove the entry, return 0 to keep it in the
195
 * cache.
196
 */
197
static int dnscache_entry_is_stale(void *datap, void *hc)
198
0
{
199
0
  struct dnscache_prune_data *prune = (struct dnscache_prune_data *)datap;
200
0
  struct Curl_dns_entry *dns = (struct Curl_dns_entry *)hc;
201
202
0
  if(dns->timestamp.tv_sec || dns->timestamp.tv_usec) {
203
    /* get age in milliseconds */
204
0
    timediff_t age = curlx_ptimediff_ms(&prune->now, &dns->timestamp);
205
0
    if(!dns->addr)
206
0
      age *= 2; /* negative entries age twice as fast */
207
0
    if(age >= prune->max_age_ms)
208
0
      return TRUE;
209
0
    if(age > prune->oldest_ms)
210
0
      prune->oldest_ms = age;
211
0
  }
212
0
  return FALSE;
213
0
}
214
215
/*
216
 * Prune the DNS cache. This assumes that a lock has already been taken.
217
 * Returns the 'age' of the oldest still kept entry - in milliseconds.
218
 */
219
static timediff_t dnscache_prune(struct Curl_hash *hostcache,
220
                                 timediff_t cache_timeout_ms,
221
                                 struct curltime now)
222
0
{
223
0
  struct dnscache_prune_data user;
224
225
0
  user.max_age_ms = cache_timeout_ms;
226
0
  user.now = now;
227
0
  user.oldest_ms = 0;
228
229
0
  Curl_hash_clean_with_criterium(hostcache,
230
0
                                 (void *)&user,
231
0
                                 dnscache_entry_is_stale);
232
233
0
  return user.oldest_ms;
234
0
}
235
236
static struct Curl_dnscache *dnscache_get(struct Curl_easy *data)
237
0
{
238
0
  if(data->share && data->share->specifier & (1 << CURL_LOCK_DATA_DNS))
239
0
    return &data->share->dnscache;
240
0
  if(data->multi)
241
0
    return &data->multi->dnscache;
242
0
  return NULL;
243
0
}
244
245
static void dnscache_lock(struct Curl_easy *data,
246
                          struct Curl_dnscache *dnscache)
247
0
{
248
0
  if(data->share && dnscache == &data->share->dnscache)
249
0
    Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
250
0
}
251
252
static void dnscache_unlock(struct Curl_easy *data,
253
                            struct Curl_dnscache *dnscache)
254
0
{
255
0
  if(data->share && dnscache == &data->share->dnscache)
256
0
    Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
257
0
}
258
259
/*
260
 * Library-wide function for pruning the DNS cache. This function takes and
261
 * returns the appropriate locks.
262
 */
263
void Curl_dnscache_prune(struct Curl_easy *data)
264
0
{
265
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
266
  /* the timeout may be set -1 (forever) */
267
0
  timediff_t timeout_ms = data->set.dns_cache_timeout_ms;
268
269
0
  if(!dnscache || (timeout_ms == -1))
270
    /* NULL hostcache means we cannot do it */
271
0
    return;
272
273
0
  dnscache_lock(data, dnscache);
274
275
0
  do {
276
    /* Remove outdated and unused entries from the hostcache */
277
0
    timediff_t oldest_ms =
278
0
      dnscache_prune(&dnscache->entries, timeout_ms, *Curl_pgrs_now(data));
279
280
0
    if(Curl_hash_count(&dnscache->entries) > MAX_DNS_CACHE_SIZE)
281
      /* prune the ones over half this age */
282
0
      timeout_ms = oldest_ms / 2;
283
0
    else
284
0
      break;
285
286
    /* if the cache size is still too big, use the oldest age as new prune
287
       limit */
288
0
  } while(timeout_ms);
289
290
0
  dnscache_unlock(data, dnscache);
291
0
}
292
293
void Curl_dnscache_clear(struct Curl_easy *data)
294
0
{
295
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
296
0
  if(dnscache) {
297
0
    dnscache_lock(data, dnscache);
298
0
    Curl_hash_clean(&dnscache->entries);
299
0
    dnscache_unlock(data, dnscache);
300
0
  }
301
0
}
302
303
#ifdef USE_ALARM_TIMEOUT
304
/* Beware this is a global and unique instance. This is used to store the
305
   return address that we can jump back to from inside a signal handler. This
306
   is not thread-safe stuff. */
307
static sigjmp_buf curl_jmpenv;
308
static curl_simple_lock curl_jmpenv_lock;
309
#endif
310
311
/* lookup address, returns entry if found and not stale */
312
static struct Curl_dns_entry *fetch_addr(struct Curl_easy *data,
313
                                         struct Curl_dnscache *dnscache,
314
                                         const char *hostname,
315
                                         int port,
316
                                         int ip_version)
317
0
{
318
0
  struct Curl_dns_entry *dns = NULL;
319
0
  char entry_id[MAX_HOSTCACHE_LEN];
320
0
  size_t entry_len;
321
322
0
  if(!dnscache)
323
0
    return NULL;
324
325
  /* Create an entry id, based upon the hostname and port */
326
0
  entry_len = create_dnscache_id(hostname, 0, port,
327
0
                                 entry_id, sizeof(entry_id));
328
329
  /* See if it is already in our dns cache */
330
0
  dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);
331
332
  /* No entry found in cache, check if we might have a wildcard entry */
333
0
  if(!dns && data->state.wildcard_resolve) {
334
0
    entry_len = create_dnscache_id("*", 1, port, entry_id, sizeof(entry_id));
335
336
    /* See if it is already in our dns cache */
337
0
    dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);
338
0
  }
339
340
0
  if(dns && (data->set.dns_cache_timeout_ms != -1)) {
341
    /* See whether the returned entry is stale. Done before we release lock */
342
0
    struct dnscache_prune_data user;
343
344
0
    user.now = *Curl_pgrs_now(data);
345
0
    user.max_age_ms = data->set.dns_cache_timeout_ms;
346
0
    user.oldest_ms = 0;
347
348
0
    if(dnscache_entry_is_stale(&user, dns)) {
349
0
      infof(data, "Hostname in DNS cache was stale, zapped");
350
0
      dns = NULL; /* the memory deallocation is being handled by the hash */
351
0
      Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
352
0
    }
353
0
  }
354
355
  /* See if the returned entry matches the required resolve mode */
356
0
  if(dns && ip_version != CURL_IPRESOLVE_WHATEVER) {
357
0
    int pf = PF_INET;
358
0
    bool found = FALSE;
359
0
    struct Curl_addrinfo *addr = dns->addr;
360
361
0
#ifdef PF_INET6
362
0
    if(ip_version == CURL_IPRESOLVE_V6)
363
0
      pf = PF_INET6;
364
0
#endif
365
366
0
    while(addr) {
367
0
      if(addr->ai_family == pf) {
368
0
        found = TRUE;
369
0
        break;
370
0
      }
371
0
      addr = addr->ai_next;
372
0
    }
373
374
0
    if(!found) {
375
0
      infof(data, "Hostname in DNS cache does not have needed family, zapped");
376
0
      dns = NULL; /* the memory deallocation is being handled by the hash */
377
0
      Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
378
0
    }
379
0
  }
380
0
  return dns;
381
0
}
382
383
/*
384
 * Curl_dnscache_get() fetches a 'Curl_dns_entry' already in the DNS cache.
385
 *
386
 * Curl_resolv() checks initially and multi_runsingle() checks each time
387
 * it discovers the handle in the state WAITRESOLVE whether the hostname
388
 * has already been resolved and the address has already been stored in
389
 * the DNS cache. This short circuits waiting for a lot of pending
390
 * lookups for the same hostname requested by different handles.
391
 *
392
 * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
393
 *
394
 * The returned data *MUST* be "released" with Curl_resolv_unlink() after
395
 * use, or we will leak memory!
396
 */
397
struct Curl_dns_entry *Curl_dnscache_get(struct Curl_easy *data,
398
                                         const char *hostname,
399
                                         int port,
400
                                         int ip_version)
401
0
{
402
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
403
0
  struct Curl_dns_entry *dns = NULL;
404
405
0
  dnscache_lock(data, dnscache);
406
407
0
  dns = fetch_addr(data, dnscache, hostname, port, ip_version);
408
0
  if(dns)
409
0
    dns->refcount++; /* we use it! */
410
411
0
  dnscache_unlock(data, dnscache);
412
413
0
  return dns;
414
0
}
415
416
#ifndef CURL_DISABLE_SHUFFLE_DNS
417
/*
418
 * Return # of addresses in a Curl_addrinfo struct
419
 */
420
static int num_addresses(const struct Curl_addrinfo *addr)
421
0
{
422
0
  int i = 0;
423
0
  while(addr) {
424
0
    addr = addr->ai_next;
425
0
    i++;
426
0
  }
427
0
  return i;
428
0
}
429
430
UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
431
                                    struct Curl_addrinfo **addr);
432
/*
433
 * Curl_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
434
 * struct by re-linking its linked list.
435
 *
436
 * The addr argument should be the address of a pointer to the head node of a
437
 * `Curl_addrinfo` list and it will be modified to point to the new head after
438
 * shuffling.
439
 *
440
 * Not declared static only to make it easy to use in a unit test!
441
 *
442
 * @unittest: 1608
443
 */
444
UNITTEST CURLcode Curl_shuffle_addr(struct Curl_easy *data,
445
                                    struct Curl_addrinfo **addr)
446
0
{
447
0
  CURLcode result = CURLE_OK;
448
0
  const int num_addrs = num_addresses(*addr);
449
450
0
  if(num_addrs > 1) {
451
0
    struct Curl_addrinfo **nodes;
452
0
    infof(data, "Shuffling %i addresses", num_addrs);
453
454
0
    nodes = curlx_malloc(num_addrs * sizeof(*nodes));
455
0
    if(nodes) {
456
0
      int i;
457
0
      unsigned int *rnd;
458
0
      const size_t rnd_size = num_addrs * sizeof(*rnd);
459
460
      /* build a plain array of Curl_addrinfo pointers */
461
0
      nodes[0] = *addr;
462
0
      for(i = 1; i < num_addrs; i++) {
463
0
        nodes[i] = nodes[i - 1]->ai_next;
464
0
      }
465
466
0
      rnd = curlx_malloc(rnd_size);
467
0
      if(rnd) {
468
        /* Fisher-Yates shuffle */
469
0
        if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
470
0
          struct Curl_addrinfo *swap_tmp;
471
0
          for(i = num_addrs - 1; i > 0; i--) {
472
0
            swap_tmp = nodes[rnd[i] % (unsigned int)(i + 1)];
473
0
            nodes[rnd[i] % (unsigned int)(i + 1)] = nodes[i];
474
0
            nodes[i] = swap_tmp;
475
0
          }
476
477
          /* relink list in the new order */
478
0
          for(i = 1; i < num_addrs; i++) {
479
0
            nodes[i - 1]->ai_next = nodes[i];
480
0
          }
481
482
0
          nodes[num_addrs - 1]->ai_next = NULL;
483
0
          *addr = nodes[0];
484
0
        }
485
0
        curlx_free(rnd);
486
0
      }
487
0
      else
488
0
        result = CURLE_OUT_OF_MEMORY;
489
0
      curlx_free(nodes);
490
0
    }
491
0
    else
492
0
      result = CURLE_OUT_OF_MEMORY;
493
0
  }
494
0
  return result;
495
0
}
496
#endif
497
498
struct Curl_dns_entry *
499
Curl_dnscache_mk_entry(struct Curl_easy *data,
500
                       struct Curl_addrinfo *addr,
501
                       const char *hostname,
502
                       size_t hostlen, /* length or zero */
503
                       int port,
504
                       bool permanent)
505
0
{
506
0
  struct Curl_dns_entry *dns;
507
508
0
#ifndef CURL_DISABLE_SHUFFLE_DNS
509
  /* shuffle addresses if requested */
510
0
  if(data->set.dns_shuffle_addresses) {
511
0
    CURLcode result = Curl_shuffle_addr(data, &addr);
512
0
    if(result)
513
0
      return NULL;
514
0
  }
515
#else
516
  (void)data;
517
#endif
518
0
  if(!hostlen)
519
0
    hostlen = strlen(hostname);
520
521
  /* Create a new cache entry */
522
0
  dns = curlx_calloc(1, sizeof(struct Curl_dns_entry) + hostlen);
523
0
  if(!dns)
524
0
    return NULL;
525
526
0
  dns->refcount = 1; /* the cache has the first reference */
527
0
  dns->addr = addr; /* this is the address(es) */
528
0
  if(permanent) {
529
0
    dns->timestamp.tv_sec = 0; /* an entry that never goes stale */
530
0
    dns->timestamp.tv_usec = 0; /* an entry that never goes stale */
531
0
  }
532
0
  else {
533
0
    dns->timestamp = *Curl_pgrs_now(data);
534
0
  }
535
0
  dns->hostport = port;
536
0
  if(hostlen)
537
0
    memcpy(dns->hostname, hostname, hostlen);
538
539
0
  return dns;
540
0
}
541
542
static struct Curl_dns_entry *
543
dnscache_add_addr(struct Curl_easy *data,
544
                  struct Curl_dnscache *dnscache,
545
                  struct Curl_addrinfo *addr,
546
                  const char *hostname,
547
                  size_t hlen, /* length or zero */
548
                  int port,
549
                  bool permanent)
550
0
{
551
0
  char entry_id[MAX_HOSTCACHE_LEN];
552
0
  size_t entry_len;
553
0
  struct Curl_dns_entry *dns;
554
0
  struct Curl_dns_entry *dns2;
555
556
0
  dns = Curl_dnscache_mk_entry(data, addr, hostname, hlen, port, permanent);
557
0
  if(!dns)
558
0
    return NULL;
559
560
  /* Create an entry id, based upon the hostname and port */
561
0
  entry_len = create_dnscache_id(hostname, hlen, port,
562
0
                                 entry_id, sizeof(entry_id));
563
564
  /* Store the resolved data in our DNS cache. */
565
0
  dns2 = Curl_hash_add(&dnscache->entries, entry_id, entry_len + 1,
566
0
                       (void *)dns);
567
0
  if(!dns2) {
568
0
    dns->addr = NULL;
569
0
    dnscache_entry_free(dns);
570
0
    return NULL;
571
0
  }
572
573
0
  dns = dns2;
574
0
  dns->refcount++;         /* mark entry as in-use */
575
0
  return dns;
576
0
}
577
578
CURLcode Curl_dnscache_add(struct Curl_easy *data,
579
                           struct Curl_dns_entry *entry)
580
0
{
581
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
582
0
  char id[MAX_HOSTCACHE_LEN];
583
0
  size_t idlen;
584
585
0
  if(!dnscache)
586
0
    return CURLE_FAILED_INIT;
587
  /* Create an entry id, based upon the hostname and port */
588
0
  idlen = create_dnscache_id(entry->hostname, 0, entry->hostport,
589
0
                             id, sizeof(id));
590
591
  /* Store the resolved data in our DNS cache and up ref count */
592
0
  dnscache_lock(data, dnscache);
593
0
  if(!Curl_hash_add(&dnscache->entries, id, idlen + 1, (void *)entry)) {
594
0
    dnscache_unlock(data, dnscache);
595
0
    return CURLE_OUT_OF_MEMORY;
596
0
  }
597
0
  entry->refcount++;
598
0
  dnscache_unlock(data, dnscache);
599
0
  return CURLE_OK;
600
0
}
601
602
#ifdef USE_IPV6
603
/* return a static IPv6 ::1 for the name */
604
static struct Curl_addrinfo *get_localhost6(int port, const char *name)
605
0
{
606
0
  struct Curl_addrinfo *ca;
607
0
  const size_t ss_size = sizeof(struct sockaddr_in6);
608
0
  const size_t hostlen = strlen(name);
609
0
  struct sockaddr_in6 sa6;
610
0
  unsigned char ipv6[16];
611
0
  unsigned short port16 = (unsigned short)(port & 0xffff);
612
0
  ca = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1);
613
0
  if(!ca)
614
0
    return NULL;
615
616
0
  sa6.sin6_family = AF_INET6;
617
0
  sa6.sin6_port = htons(port16);
618
0
  sa6.sin6_flowinfo = 0;
619
0
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
620
0
  sa6.sin6_scope_id = 0;
621
0
#endif
622
623
0
  (void)curlx_inet_pton(AF_INET6, "::1", ipv6);
624
0
  memcpy(&sa6.sin6_addr, ipv6, sizeof(ipv6));
625
626
0
  ca->ai_flags     = 0;
627
0
  ca->ai_family    = AF_INET6;
628
0
  ca->ai_socktype  = SOCK_STREAM;
629
0
  ca->ai_protocol  = IPPROTO_TCP;
630
0
  ca->ai_addrlen   = (curl_socklen_t)ss_size;
631
0
  ca->ai_next      = NULL;
632
0
  ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
633
0
  memcpy(ca->ai_addr, &sa6, ss_size);
634
0
  ca->ai_canonname = (char *)ca->ai_addr + ss_size;
635
0
  curlx_strcopy(ca->ai_canonname, hostlen + 1, name, hostlen);
636
0
  return ca;
637
0
}
638
#else
639
#define get_localhost6(x, y) NULL
640
#endif
641
642
/* return a static IPv4 127.0.0.1 for the given name */
643
static struct Curl_addrinfo *get_localhost(int port, const char *name)
644
0
{
645
0
  struct Curl_addrinfo *ca;
646
0
  struct Curl_addrinfo *ca6;
647
0
  const size_t ss_size = sizeof(struct sockaddr_in);
648
0
  const size_t hostlen = strlen(name);
649
0
  struct sockaddr_in sa;
650
0
  unsigned int ipv4;
651
0
  unsigned short port16 = (unsigned short)(port & 0xffff);
652
653
  /* memset to clear the sa.sin_zero field */
654
0
  memset(&sa, 0, sizeof(sa));
655
0
  sa.sin_family = AF_INET;
656
0
  sa.sin_port = htons(port16);
657
0
  if(curlx_inet_pton(AF_INET, "127.0.0.1", (char *)&ipv4) < 1)
658
0
    return NULL;
659
0
  memcpy(&sa.sin_addr, &ipv4, sizeof(ipv4));
660
661
0
  ca = curlx_calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen + 1);
662
0
  if(!ca)
663
0
    return NULL;
664
0
  ca->ai_flags     = 0;
665
0
  ca->ai_family    = AF_INET;
666
0
  ca->ai_socktype  = SOCK_STREAM;
667
0
  ca->ai_protocol  = IPPROTO_TCP;
668
0
  ca->ai_addrlen   = (curl_socklen_t)ss_size;
669
0
  ca->ai_addr = (void *)((char *)ca + sizeof(struct Curl_addrinfo));
670
0
  memcpy(ca->ai_addr, &sa, ss_size);
671
0
  ca->ai_canonname = (char *)ca->ai_addr + ss_size;
672
0
  curlx_strcopy(ca->ai_canonname, hostlen + 1, name, hostlen);
673
674
0
  ca6 = get_localhost6(port, name);
675
0
  if(!ca6)
676
0
    return ca;
677
0
  ca6->ai_next = ca;
678
0
  return ca6;
679
0
}
680
681
#ifdef USE_IPV6
682
/*
683
 * Curl_ipv6works() returns TRUE if IPv6 seems to work.
684
 */
685
bool Curl_ipv6works(struct Curl_easy *data)
686
0
{
687
0
  if(data) {
688
    /* the nature of most system is that IPv6 status does not come and go
689
       during a program's lifetime so we only probe the first time and then we
690
       have the info kept for fast reuse */
691
0
    DEBUGASSERT(data);
692
0
    DEBUGASSERT(data->multi);
693
0
    if(data->multi->ipv6_up == IPV6_UNKNOWN) {
694
0
      bool works = Curl_ipv6works(NULL);
695
0
      data->multi->ipv6_up = works ? IPV6_WORKS : IPV6_DEAD;
696
0
    }
697
0
    return data->multi->ipv6_up == IPV6_WORKS;
698
0
  }
699
0
  else {
700
0
    int ipv6_works = -1;
701
    /* probe to see if we have a working IPv6 stack */
702
0
    curl_socket_t s = CURL_SOCKET(PF_INET6, SOCK_DGRAM, 0);
703
0
    if(s == CURL_SOCKET_BAD)
704
      /* an IPv6 address was requested but we cannot get/use one */
705
0
      ipv6_works = 0;
706
0
    else {
707
0
      ipv6_works = 1;
708
0
      sclose(s);
709
0
    }
710
0
    return ipv6_works > 0;
711
0
  }
712
0
}
713
#endif /* USE_IPV6 */
714
715
/*
716
 * Curl_host_is_ipnum() returns TRUE if the given string is a numerical IPv4
717
 * (or IPv6 if supported) address.
718
 */
719
bool Curl_host_is_ipnum(const char *hostname)
720
196
{
721
196
  struct in_addr in;
722
196
#ifdef USE_IPV6
723
196
  struct in6_addr in6;
724
196
#endif
725
196
  if(curlx_inet_pton(AF_INET, hostname, &in) > 0
726
194
#ifdef USE_IPV6
727
194
     || curlx_inet_pton(AF_INET6, hostname, &in6) > 0
728
196
#endif
729
196
    )
730
4
    return TRUE;
731
192
  return FALSE;
732
196
}
733
734
/* return TRUE if 'part' is a case insensitive tail of 'full' */
735
static bool tailmatch(const char *full, size_t flen,
736
                      const char *part, size_t plen)
737
0
{
738
0
  if(plen > flen)
739
0
    return FALSE;
740
0
  return curl_strnequal(part, &full[flen - plen], plen);
741
0
}
742
743
static bool can_resolve_ip_version(struct Curl_easy *data, int ip_version)
744
0
{
745
0
#ifdef CURLRES_IPV6
746
0
  if(ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data))
747
0
    return FALSE;
748
#elif defined(CURLRES_IPV4)
749
  (void)data;
750
  if(ip_version == CURL_IPRESOLVE_V6)
751
    return FALSE;
752
#else
753
#error either CURLRES_IPV6 or CURLRES_IPV4 need to be defined
754
#endif
755
0
  return TRUE;
756
0
}
757
758
static CURLcode store_negative_resolve(struct Curl_easy *data,
759
                                       const char *host,
760
                                       int port)
761
0
{
762
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
763
0
  struct Curl_dns_entry *dns;
764
0
  DEBUGASSERT(dnscache);
765
0
  if(!dnscache)
766
0
    return CURLE_FAILED_INIT;
767
768
  /* put this new host in the cache */
769
0
  dns = dnscache_add_addr(data, dnscache, NULL, host, 0, port, FALSE);
770
0
  if(dns) {
771
    /* release the returned reference; the cache itself will keep the
772
     * entry alive: */
773
0
    dns->refcount--;
774
0
    infof(data, "Store negative name resolve for %s:%d", host, port);
775
0
    return CURLE_OK;
776
0
  }
777
0
  return CURLE_OUT_OF_MEMORY;
778
0
}
779
780
/*
781
 * Curl_resolv() is the main name resolve function within libcurl. It resolves
782
 * a name and returns a pointer to the entry in the 'entry' argument. This
783
 * function might return immediately if we are using asynch resolves. See the
784
 * return codes.
785
 *
786
 * The cache entry we return will get its 'inuse' counter increased when this
787
 * function is used. You MUST call Curl_resolv_unlink() later (when you are
788
 * done using this struct) to decrease the reference counter again.
789
 *
790
 * Return codes:
791
 * CURLE_OK = success, *entry set to non-NULL
792
 * CURLE_AGAIN = resolving in progress, *entry == NULL
793
 * CURLE_COULDNT_RESOLVE_HOST = error, *entry == NULL
794
 * CURLE_OPERATION_TIMEDOUT = timeout expired, *entry == NULL
795
 */
796
CURLcode Curl_resolv(struct Curl_easy *data,
797
                     const char *hostname,
798
                     int port,
799
                     int ip_version,
800
                     bool allowDOH,
801
                     struct Curl_dns_entry **entry)
802
0
{
803
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
804
0
  struct Curl_dns_entry *dns = NULL;
805
0
  struct Curl_addrinfo *addr = NULL;
806
0
  bool respwait = FALSE;
807
0
  size_t hostname_len;
808
0
  CURLcode result = CURLE_COULDNT_RESOLVE_HOST;
809
810
0
  *entry = NULL;
811
812
0
#ifndef CURL_DISABLE_DOH
813
0
  data->conn->bits.doh = FALSE; /* default is not */
814
#else
815
  (void)allowDOH;
816
#endif
817
0
  DEBUGASSERT(dnscache);
818
0
  if(!dnscache) {
819
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
820
0
    goto error;
821
0
  }
822
823
  /* We should intentionally error and not resolve .onion TLDs */
824
0
  hostname_len = strlen(hostname);
825
0
  DEBUGASSERT(hostname_len);
826
0
  if(hostname_len >= 7 &&
827
0
     (curl_strequal(&hostname[hostname_len - 6], ".onion") ||
828
0
      curl_strequal(&hostname[hostname_len - 7], ".onion."))) {
829
0
    failf(data, "Not resolving .onion address (RFC 7686)");
830
0
    goto error;
831
0
  }
832
833
  /* Let's check our DNS cache first */
834
0
  dnscache_lock(data, dnscache);
835
0
  dns = fetch_addr(data, dnscache, hostname, port, ip_version);
836
0
  if(dns)
837
0
    dns->refcount++; /* we pass out the reference. */
838
0
  dnscache_unlock(data, dnscache);
839
0
  if(dns) {
840
0
    infof(data, "Hostname %s was found in DNS cache", hostname);
841
0
    result = CURLE_OK;
842
0
    goto out;
843
0
  }
844
845
  /* No luck, we need to resolve hostname. Notify user callback. */
846
0
  if(data->set.resolver_start) {
847
0
    void *resolver = NULL;
848
0
    int st;
849
0
#ifdef CURLRES_ASYNCH
850
0
    result = Curl_async_get_impl(data, &resolver);
851
0
    if(result)
852
0
      goto error;
853
0
#endif
854
0
    Curl_set_in_callback(data, TRUE);
855
0
    st = data->set.resolver_start(resolver, NULL,
856
0
                                  data->set.resolver_start_client);
857
0
    Curl_set_in_callback(data, FALSE);
858
0
    if(st) {
859
0
      result = CURLE_ABORTED_BY_CALLBACK;
860
0
      goto error;
861
0
    }
862
0
  }
863
864
0
  if(Curl_is_ipaddr(hostname)) {
865
0
#ifndef USE_RESOLVE_ON_IPS
866
    /* shortcut literal IP addresses, if we are not told to resolve them. */
867
0
    result = Curl_str2addr(hostname, port, &addr);
868
0
    if(result)
869
0
      goto error;
870
0
    goto out;
871
0
#endif
872
0
  }
873
874
0
  if(curl_strequal(hostname, "localhost") ||
875
0
     curl_strequal(hostname, "localhost.") ||
876
0
     tailmatch(hostname, hostname_len, STRCONST(".localhost")) ||
877
0
     tailmatch(hostname, hostname_len, STRCONST(".localhost."))) {
878
0
    addr = get_localhost(port, hostname);
879
0
    result = addr ? CURLE_OK : CURLE_OUT_OF_MEMORY;
880
0
  }
881
0
#ifndef CURL_DISABLE_DOH
882
0
  else if(!Curl_is_ipaddr(hostname) && allowDOH && data->set.doh) {
883
0
    result = Curl_doh(data, hostname, port, ip_version);
884
0
    respwait = TRUE;
885
0
  }
886
0
#endif
887
0
  else {
888
    /* Can we provide the requested IP specifics in resolving? */
889
0
    if(!can_resolve_ip_version(data, ip_version)) {
890
0
      result = CURLE_COULDNT_RESOLVE_HOST;
891
0
      goto error;
892
0
    }
893
894
0
#ifdef CURLRES_ASYNCH
895
0
    result = Curl_async_getaddrinfo(data, hostname, port, ip_version);
896
0
    respwait = TRUE;
897
#else
898
    respwait = FALSE; /* no async waiting here */
899
    addr = Curl_sync_getaddrinfo(data, hostname, port, ip_version);
900
    if(addr)
901
      result = CURLE_OK;
902
#endif
903
0
  }
904
905
0
out:
906
  /* We either have found a `dns` or looked up the `addr` or `respwait` is set
907
   * for an async operation. Everything else is a failure to resolve. */
908
0
  if(result)
909
0
    ;
910
0
  else if(dns) {
911
0
    if(!dns->addr) {
912
0
      infof(data, "Negative DNS entry");
913
0
      dns->refcount--;
914
0
      return CURLE_COULDNT_RESOLVE_HOST;
915
0
    }
916
0
    *entry = dns;
917
0
    return CURLE_OK;
918
0
  }
919
0
  else if(addr) {
920
    /* we got a response, create a dns entry, add to cache, return */
921
0
    dns = Curl_dnscache_mk_entry(data, addr, hostname, 0, port, FALSE);
922
0
    if(!dns || Curl_dnscache_add(data, dns)) {
923
      /* this is OOM or similar, do not store such negative resolves */
924
0
      Curl_freeaddrinfo(addr);
925
0
      if(dns)
926
        /* avoid a dangling pointer to addr in the dying dns entry */
927
0
        dns->addr = NULL;
928
0
      result = CURLE_OUT_OF_MEMORY;
929
0
      goto error;
930
0
    }
931
0
    show_resolve_info(data, dns);
932
0
    *entry = dns;
933
0
    return CURLE_OK;
934
0
  }
935
0
  else if(respwait) {
936
0
    if(!Curl_resolv_check(data, &dns)) {
937
0
      *entry = dns;
938
0
      return dns ? CURLE_OK : CURLE_AGAIN;
939
0
    }
940
0
    result = CURLE_COULDNT_RESOLVE_HOST;
941
0
  }
942
0
error:
943
0
  if(dns)
944
0
    Curl_resolv_unlink(data, &dns);
945
0
  Curl_async_shutdown(data);
946
0
  if(result == CURLE_COULDNT_RESOLVE_HOST)
947
0
    store_negative_resolve(data, hostname, port);
948
0
  DEBUGASSERT(result);
949
0
  return result;
950
0
}
951
952
CURLcode Curl_resolv_blocking(struct Curl_easy *data,
953
                              const char *hostname,
954
                              int port,
955
                              int ip_version,
956
                              struct Curl_dns_entry **dnsentry)
957
0
{
958
0
  CURLcode result;
959
0
  DEBUGASSERT(hostname && *hostname);
960
0
  *dnsentry = NULL;
961
0
  result = Curl_resolv(data, hostname, port, ip_version, FALSE, dnsentry);
962
0
  switch(result) {
963
0
  case CURLE_OK:
964
0
    DEBUGASSERT(*dnsentry);
965
0
    return CURLE_OK;
966
0
  case CURLE_AGAIN:
967
0
    DEBUGASSERT(!*dnsentry);
968
0
    result = Curl_async_await(data, dnsentry);
969
0
    if(result || !*dnsentry) {
970
      /* close the connection, since we cannot return failure here without
971
         cleaning up this connection properly. */
972
0
      connclose(data->conn, "async resolve failed");
973
0
    }
974
0
    return result;
975
0
  default:
976
0
    return result;
977
0
  }
978
0
}
979
980
#ifdef USE_ALARM_TIMEOUT
981
/*
982
 * This signal handler jumps back into the main libcurl code and continues
983
 * execution. This effectively causes the remainder of the application to run
984
 * within a signal handler which is nonportable and could lead to problems.
985
 */
986
CURL_NORETURN static void alarmfunc(int sig)
987
{
988
  (void)sig;
989
  siglongjmp(curl_jmpenv, 1);
990
}
991
#endif /* USE_ALARM_TIMEOUT */
992
993
/*
994
 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
995
 * timeout. This function might return immediately if we are using asynch
996
 * resolves. See the return codes.
997
 *
998
 * The cache entry we return will get its 'inuse' counter increased when this
999
 * function is used. You MUST call Curl_resolv_unlink() later (when you are
1000
 * done using this struct) to decrease the reference counter again.
1001
 *
1002
 * If built with a synchronous resolver and use of signals is not
1003
 * disabled by the application, then a nonzero timeout will cause a
1004
 * timeout after the specified number of milliseconds. Otherwise, timeout
1005
 * is ignored.
1006
 *
1007
 * Return codes:
1008
 * CURLE_OK = success, *entry set to non-NULL
1009
 * CURLE_AGAIN = resolving in progress, *entry == NULL
1010
 * CURLE_COULDNT_RESOLVE_HOST = error, *entry == NULL
1011
 * CURLE_OPERATION_TIMEDOUT = timeout expired, *entry == NULL
1012
 */
1013
1014
CURLcode Curl_resolv_timeout(struct Curl_easy *data,
1015
                             const char *hostname,
1016
                             int port,
1017
                             int ip_version,
1018
                             struct Curl_dns_entry **entry,
1019
                             timediff_t timeoutms)
1020
0
{
1021
#ifdef USE_ALARM_TIMEOUT
1022
#ifdef HAVE_SIGACTION
1023
  struct sigaction keep_sigact; /* store the old struct here */
1024
  volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
1025
  struct sigaction sigact;
1026
#else
1027
#ifdef HAVE_SIGNAL
1028
  void (*keep_sigact)(int);       /* store the old handler here */
1029
#endif /* HAVE_SIGNAL */
1030
#endif /* HAVE_SIGACTION */
1031
  volatile long timeout;
1032
  volatile unsigned int prev_alarm = 0;
1033
#endif /* USE_ALARM_TIMEOUT */
1034
0
  CURLcode result;
1035
1036
0
  DEBUGASSERT(hostname && *hostname);
1037
0
  *entry = NULL;
1038
1039
0
  if(timeoutms < 0)
1040
    /* got an already expired timeout */
1041
0
    return CURLE_OPERATION_TIMEDOUT;
1042
1043
#ifdef USE_ALARM_TIMEOUT
1044
  if(data->set.no_signal)
1045
    /* Ignore the timeout when signals are disabled */
1046
    timeout = 0;
1047
  else
1048
    timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
1049
1050
  if(!timeout
1051
#ifndef CURL_DISABLE_DOH
1052
     || data->set.doh
1053
#endif
1054
    )
1055
    /* USE_ALARM_TIMEOUT defined, but no timeout actually requested or resolve
1056
       done using DoH */
1057
    return Curl_resolv(data, hostname, port, ip_version, TRUE, entry);
1058
1059
  if(timeout < 1000) {
1060
    /* The alarm() function only provides integer second resolution, so if
1061
       we want to wait less than one second we must bail out already now. */
1062
    failf(data,
1063
          "remaining timeout of %ld too small to resolve via SIGALRM method",
1064
          timeout);
1065
    return CURLE_OPERATION_TIMEDOUT;
1066
  }
1067
  /* This allows us to time-out from the name resolver, as the timeout
1068
     will generate a signal and we will siglongjmp() from that here.
1069
     This technique has problems (see alarmfunc).
1070
     This should be the last thing we do before calling Curl_resolv(),
1071
     as otherwise we would have to worry about variables that get modified
1072
     before we invoke Curl_resolv() (and thus use "volatile"). */
1073
  curl_simple_lock_lock(&curl_jmpenv_lock);
1074
1075
  if(sigsetjmp(curl_jmpenv, 1)) {
1076
    /* this is coming from a siglongjmp() after an alarm signal */
1077
    failf(data, "name lookup timed out");
1078
    result = CURLE_OPERATION_TIMEDOUT;
1079
    goto clean_up;
1080
  }
1081
  else {
1082
    /*************************************************************
1083
     * Set signal handler to catch SIGALRM
1084
     * Store the old value to be able to set it back later!
1085
     *************************************************************/
1086
#ifdef HAVE_SIGACTION
1087
    sigaction(SIGALRM, NULL, &sigact);
1088
    keep_sigact = sigact;
1089
    keep_copysig = TRUE; /* yes, we have a copy */
1090
    sigact.sa_handler = alarmfunc;
1091
#ifdef SA_RESTART
1092
    /* HP-UX does not have SA_RESTART but defaults to that behavior! */
1093
    sigact.sa_flags &= ~SA_RESTART;
1094
#endif
1095
    /* now set the new struct */
1096
    sigaction(SIGALRM, &sigact, NULL);
1097
#else /* HAVE_SIGACTION */
1098
    /* no sigaction(), revert to the much lamer signal() */
1099
#ifdef HAVE_SIGNAL
1100
    keep_sigact = signal(SIGALRM, alarmfunc);
1101
#endif
1102
#endif /* HAVE_SIGACTION */
1103
1104
    /* alarm() makes a signal get sent when the timeout fires off, and that
1105
       will abort system calls */
1106
    prev_alarm = alarm(curlx_sltoui(timeout / 1000L));
1107
  }
1108
1109
#else /* !USE_ALARM_TIMEOUT */
1110
#ifndef CURLRES_ASYNCH
1111
  if(timeoutms)
1112
    infof(data, "timeout on name lookup is not supported");
1113
#else
1114
0
  (void)timeoutms;
1115
0
#endif
1116
0
#endif /* USE_ALARM_TIMEOUT */
1117
1118
  /* Perform the actual name resolution. This might be interrupted by an
1119
   * alarm if it takes too long.
1120
   */
1121
0
  result = Curl_resolv(data, hostname, port, ip_version, TRUE, entry);
1122
1123
#ifdef USE_ALARM_TIMEOUT
1124
clean_up:
1125
1126
  if(!prev_alarm)
1127
    /* deactivate a possibly active alarm before uninstalling the handler */
1128
    alarm(0);
1129
1130
#ifdef HAVE_SIGACTION
1131
  if(keep_copysig) {
1132
    /* we got a struct as it looked before, now put that one back nice
1133
       and clean */
1134
    sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
1135
  }
1136
#else
1137
#ifdef HAVE_SIGNAL
1138
  /* restore the previous SIGALRM handler */
1139
  signal(SIGALRM, keep_sigact);
1140
#endif
1141
#endif /* HAVE_SIGACTION */
1142
1143
  curl_simple_lock_unlock(&curl_jmpenv_lock);
1144
1145
  /* switch back the alarm() to either zero or to what it was before minus
1146
     the time we spent until now! */
1147
  if(prev_alarm) {
1148
    /* there was an alarm() set before us, now put it back */
1149
    timediff_t elapsed_secs = curlx_ptimediff_ms(Curl_pgrs_now(data),
1150
                                                 &data->conn->created) / 1000;
1151
1152
    /* the alarm period is counted in even number of seconds */
1153
    unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
1154
1155
    if(!alarm_set ||
1156
       ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000))) {
1157
      /* if the alarm time-left reached zero or turned "negative" (counted
1158
         with unsigned values), we should fire off a SIGALRM here, but we
1159
         will not, and zero would be to switch it off so we never set it to
1160
         less than 1! */
1161
      alarm(1);
1162
      result = CURLE_OPERATION_TIMEDOUT;
1163
      failf(data, "Previous alarm fired off");
1164
    }
1165
    else
1166
      alarm((unsigned int)alarm_set);
1167
  }
1168
#endif /* USE_ALARM_TIMEOUT */
1169
1170
0
  return result;
1171
0
}
1172
1173
/*
1174
 * Curl_resolv_unlink() releases a reference to the given cached DNS entry.
1175
 * When the reference count reaches 0, the entry is destroyed. It is important
1176
 * that only one unlink is made for each Curl_resolv() call.
1177
 *
1178
 * May be called with 'data' == NULL for global cache.
1179
 */
1180
void Curl_resolv_unlink(struct Curl_easy *data, struct Curl_dns_entry **pdns)
1181
12.5k
{
1182
12.5k
  if(*pdns) {
1183
0
    struct Curl_dnscache *dnscache = dnscache_get(data);
1184
0
    struct Curl_dns_entry *dns = *pdns;
1185
0
    *pdns = NULL;
1186
0
    dnscache_lock(data, dnscache);
1187
0
    dns->refcount--;
1188
0
    if(dns->refcount == 0)
1189
0
      dnscache_entry_free(dns);
1190
0
    dnscache_unlock(data, dnscache);
1191
0
  }
1192
12.5k
}
1193
1194
static void dnscache_entry_dtor(void *entry)
1195
0
{
1196
0
  struct Curl_dns_entry *dns = (struct Curl_dns_entry *)entry;
1197
0
  DEBUGASSERT(dns && (dns->refcount > 0));
1198
0
  dns->refcount--;
1199
0
  if(dns->refcount == 0)
1200
0
    dnscache_entry_free(dns);
1201
0
}
1202
1203
/*
1204
 * Curl_dnscache_init() inits a new DNS cache.
1205
 */
1206
void Curl_dnscache_init(struct Curl_dnscache *dns, size_t size)
1207
0
{
1208
0
  Curl_hash_init(&dns->entries, size, Curl_hash_str, curlx_str_key_compare,
1209
0
                 dnscache_entry_dtor);
1210
0
}
1211
1212
void Curl_dnscache_destroy(struct Curl_dnscache *dns)
1213
0
{
1214
0
  Curl_hash_destroy(&dns->entries);
1215
0
}
1216
1217
CURLcode Curl_loadhostpairs(struct Curl_easy *data)
1218
0
{
1219
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
1220
0
  struct curl_slist *hostp;
1221
1222
0
  if(!dnscache)
1223
0
    return CURLE_FAILED_INIT;
1224
1225
  /* Default is no wildcard found */
1226
0
  data->state.wildcard_resolve = FALSE;
1227
1228
0
  for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
1229
0
    char entry_id[MAX_HOSTCACHE_LEN];
1230
0
    const char *host = hostp->data;
1231
0
    struct Curl_str source;
1232
0
    if(!host)
1233
0
      continue;
1234
0
    if(*host == '-') {
1235
0
      curl_off_t num = 0;
1236
0
      size_t entry_len;
1237
0
      host++;
1238
0
      if(!curlx_str_single(&host, '[')) {
1239
0
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
1240
0
           curlx_str_single(&host, ']') ||
1241
0
           curlx_str_single(&host, ':'))
1242
0
          continue;
1243
0
      }
1244
0
      else {
1245
0
        if(curlx_str_until(&host, &source, 4096, ':') ||
1246
0
           curlx_str_single(&host, ':')) {
1247
0
          continue;
1248
0
        }
1249
0
      }
1250
1251
0
      if(!curlx_str_number(&host, &num, 0xffff)) {
1252
        /* Create an entry id, based upon the hostname and port */
1253
0
        entry_len = create_dnscache_id(curlx_str(&source),
1254
0
                                       curlx_strlen(&source), (int)num,
1255
0
                                       entry_id, sizeof(entry_id));
1256
0
        dnscache_lock(data, dnscache);
1257
        /* delete entry, ignore if it did not exist */
1258
0
        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
1259
0
        dnscache_unlock(data, dnscache);
1260
0
      }
1261
0
    }
1262
0
    else {
1263
0
      struct Curl_dns_entry *dns;
1264
0
      struct Curl_addrinfo *head = NULL, *tail = NULL;
1265
0
      size_t entry_len;
1266
0
      char address[64];
1267
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1268
0
      const char *addresses = NULL;
1269
0
#endif
1270
0
      curl_off_t port = 0;
1271
0
      bool permanent = TRUE;
1272
0
      bool error = TRUE;
1273
1274
0
      if(*host == '+') {
1275
0
        host++;
1276
0
        permanent = FALSE;
1277
0
      }
1278
0
      if(!curlx_str_single(&host, '[')) {
1279
0
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
1280
0
           curlx_str_single(&host, ']'))
1281
0
          continue;
1282
0
      }
1283
0
      else {
1284
0
        if(curlx_str_until(&host, &source, 4096, ':'))
1285
0
          continue;
1286
0
      }
1287
0
      if(curlx_str_single(&host, ':') ||
1288
0
         curlx_str_number(&host, &port, 0xffff) ||
1289
0
         curlx_str_single(&host, ':'))
1290
0
        goto err;
1291
1292
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1293
0
      addresses = host;
1294
0
#endif
1295
1296
      /* start the address section */
1297
0
      while(*host) {
1298
0
        struct Curl_str target;
1299
0
        struct Curl_addrinfo *ai;
1300
0
        CURLcode result;
1301
1302
0
        if(!curlx_str_single(&host, '[')) {
1303
0
          if(curlx_str_until(&host, &target, MAX_IPADR_LEN, ']') ||
1304
0
             curlx_str_single(&host, ']'))
1305
0
            goto err;
1306
0
        }
1307
0
        else {
1308
0
          if(curlx_str_until(&host, &target, 4096, ',')) {
1309
0
            if(curlx_str_single(&host, ','))
1310
0
              goto err;
1311
            /* survive nothing but just a comma */
1312
0
            continue;
1313
0
          }
1314
0
        }
1315
#ifndef USE_IPV6
1316
        if(memchr(curlx_str(&target), ':', curlx_strlen(&target))) {
1317
          infof(data, "Ignoring resolve address '%.*s', missing IPv6 support.",
1318
                (int)curlx_strlen(&target), curlx_str(&target));
1319
          if(curlx_str_single(&host, ','))
1320
            goto err;
1321
          continue;
1322
        }
1323
#endif
1324
1325
0
        if(curlx_strlen(&target) >= sizeof(address))
1326
0
          goto err;
1327
1328
0
        memcpy(address, curlx_str(&target), curlx_strlen(&target));
1329
0
        address[curlx_strlen(&target)] = '\0';
1330
1331
0
        result = Curl_str2addr(address, (int)port, &ai);
1332
0
        if(result) {
1333
0
          infof(data, "Resolve address '%s' found illegal", address);
1334
0
          goto err;
1335
0
        }
1336
1337
0
        if(tail) {
1338
0
          tail->ai_next = ai;
1339
0
          tail = tail->ai_next;
1340
0
        }
1341
0
        else {
1342
0
          head = tail = ai;
1343
0
        }
1344
0
        if(curlx_str_single(&host, ','))
1345
0
          break;
1346
0
      }
1347
1348
0
      if(!head)
1349
0
        goto err;
1350
1351
0
      error = FALSE;
1352
0
err:
1353
0
      if(error) {
1354
0
        failf(data, "Could not parse CURLOPT_RESOLVE entry '%s'", hostp->data);
1355
0
        Curl_freeaddrinfo(head);
1356
0
        return CURLE_SETOPT_OPTION_SYNTAX;
1357
0
      }
1358
1359
      /* Create an entry id, based upon the hostname and port */
1360
0
      entry_len = create_dnscache_id(curlx_str(&source), curlx_strlen(&source),
1361
0
                                     (int)port,
1362
0
                                     entry_id, sizeof(entry_id));
1363
1364
0
      dnscache_lock(data, dnscache);
1365
1366
      /* See if it is already in our dns cache */
1367
0
      dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);
1368
1369
0
      if(dns) {
1370
0
        infof(data, "RESOLVE %.*s:%" CURL_FORMAT_CURL_OFF_T
1371
0
              " - old addresses discarded", (int)curlx_strlen(&source),
1372
0
              curlx_str(&source), port);
1373
        /* delete old entry, there are two reasons for this
1374
         1. old entry may have different addresses.
1375
         2. even if entry with correct addresses is already in the cache,
1376
            but if it is close to expire, then by the time next http
1377
            request is made, it can get expired and pruned because old
1378
            entry is not necessarily marked as permanent.
1379
         3. when adding a non-permanent entry, we want it to remove and
1380
            replace an existing permanent entry.
1381
         4. when adding a non-permanent entry, we want it to get a "fresh"
1382
            timeout that starts _now_. */
1383
1384
0
        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
1385
0
      }
1386
1387
      /* put this new host in the cache */
1388
0
      dns = dnscache_add_addr(data, dnscache, head, curlx_str(&source),
1389
0
                              curlx_strlen(&source), (int)port, permanent);
1390
0
      if(dns)
1391
        /* release the returned reference; the cache itself will keep the
1392
         * entry alive: */
1393
0
        dns->refcount--;
1394
0
      else
1395
0
        Curl_freeaddrinfo(head);
1396
1397
0
      dnscache_unlock(data, dnscache);
1398
1399
0
      if(!dns)
1400
0
        return CURLE_OUT_OF_MEMORY;
1401
1402
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1403
0
      infof(data, "Added %.*s:%" CURL_FORMAT_CURL_OFF_T ":%s to DNS cache%s",
1404
0
            (int)curlx_strlen(&source), curlx_str(&source), port, addresses,
1405
0
            permanent ? "" : " (non-permanent)");
1406
0
#endif
1407
1408
      /* Wildcard hostname */
1409
0
      if(curlx_str_casecompare(&source, "*")) {
1410
0
        infof(data, "RESOLVE *:%" CURL_FORMAT_CURL_OFF_T " using wildcard",
1411
0
              port);
1412
0
        data->state.wildcard_resolve = TRUE;
1413
0
      }
1414
0
    }
1415
0
  }
1416
0
  data->state.resolve = NULL; /* dealt with now */
1417
1418
0
  return CURLE_OK;
1419
0
}
1420
1421
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1422
static void show_resolve_info(struct Curl_easy *data,
1423
                              struct Curl_dns_entry *dns)
1424
0
{
1425
0
  struct Curl_addrinfo *a;
1426
0
  CURLcode result = CURLE_OK;
1427
0
#ifdef CURLRES_IPV6
1428
0
  struct dynbuf out[2];
1429
#else
1430
  struct dynbuf out[1];
1431
#endif
1432
0
  DEBUGASSERT(data);
1433
0
  DEBUGASSERT(dns);
1434
1435
0
  if(!data->set.verbose ||
1436
     /* ignore no name or numerical IP addresses */
1437
0
     !dns->hostname[0] || Curl_host_is_ipnum(dns->hostname))
1438
0
    return;
1439
1440
0
  a = dns->addr;
1441
1442
0
  infof(data, "Host %s:%d was resolved.",
1443
0
        (dns->hostname[0] ? dns->hostname : "(none)"), dns->hostport);
1444
1445
0
  curlx_dyn_init(&out[0], 1024);
1446
0
#ifdef CURLRES_IPV6
1447
0
  curlx_dyn_init(&out[1], 1024);
1448
0
#endif
1449
1450
0
  while(a) {
1451
0
    if(
1452
0
#ifdef CURLRES_IPV6
1453
0
       a->ai_family == PF_INET6 ||
1454
0
#endif
1455
0
       a->ai_family == PF_INET) {
1456
0
      char buf[MAX_IPADR_LEN];
1457
0
      struct dynbuf *d = &out[(a->ai_family != PF_INET)];
1458
0
      Curl_printable_address(a, buf, sizeof(buf));
1459
0
      if(curlx_dyn_len(d))
1460
0
        result = curlx_dyn_addn(d, ", ", 2);
1461
0
      if(!result)
1462
0
        result = curlx_dyn_add(d, buf);
1463
0
      if(result) {
1464
0
        infof(data, "too many IP, cannot show");
1465
0
        goto fail;
1466
0
      }
1467
0
    }
1468
0
    a = a->ai_next;
1469
0
  }
1470
1471
0
#ifdef CURLRES_IPV6
1472
0
  infof(data, "IPv6: %s",
1473
0
        (curlx_dyn_len(&out[1]) ? curlx_dyn_ptr(&out[1]) : "(none)"));
1474
0
#endif
1475
0
  infof(data, "IPv4: %s",
1476
0
        (curlx_dyn_len(&out[0]) ? curlx_dyn_ptr(&out[0]) : "(none)"));
1477
1478
0
fail:
1479
0
  curlx_dyn_free(&out[0]);
1480
0
#ifdef CURLRES_IPV6
1481
0
  curlx_dyn_free(&out[1]);
1482
0
#endif
1483
0
}
1484
#endif
1485
1486
#ifdef USE_CURL_ASYNC
1487
CURLcode Curl_resolv_check(struct Curl_easy *data,
1488
                           struct Curl_dns_entry **dns)
1489
0
{
1490
0
  CURLcode result;
1491
1492
  /* If async resolving is ongoing, this must be set */
1493
0
  if(!data->state.async.hostname)
1494
0
    return CURLE_FAILED_INIT;
1495
1496
  /* check if we have the name resolved by now (from someone else) */
1497
0
  *dns = Curl_dnscache_get(data, data->state.async.hostname,
1498
0
                           data->state.async.port,
1499
0
                           data->state.async.ip_version);
1500
0
  if(*dns) {
1501
    /* Tell a possibly async resolver we no longer need the results. */
1502
0
    infof(data, "Hostname '%s' was found in DNS cache",
1503
0
          data->state.async.hostname);
1504
0
    Curl_async_shutdown(data);
1505
0
    data->state.async.dns = *dns;
1506
0
    data->state.async.done = TRUE;
1507
0
    return CURLE_OK;
1508
0
  }
1509
1510
0
#ifndef CURL_DISABLE_DOH
1511
0
  if(data->conn->bits.doh) {
1512
0
    result = Curl_doh_is_resolved(data, dns);
1513
0
    if(result)
1514
0
      Curl_resolver_error(data, NULL);
1515
0
  }
1516
0
  else
1517
0
#endif
1518
0
  result = Curl_async_is_resolved(data, dns);
1519
0
  if(*dns)
1520
0
    show_resolve_info(data, *dns);
1521
0
  if((result == CURLE_COULDNT_RESOLVE_HOST) ||
1522
0
     (result == CURLE_COULDNT_RESOLVE_PROXY))
1523
0
    store_negative_resolve(data, data->state.async.hostname,
1524
0
                           data->state.async.port);
1525
0
  return result;
1526
0
}
1527
#endif
1528
1529
CURLcode Curl_resolv_pollset(struct Curl_easy *data,
1530
                             struct easy_pollset *ps)
1531
0
{
1532
0
#ifdef CURLRES_ASYNCH
1533
0
#ifndef CURL_DISABLE_DOH
1534
0
  if(data->conn->bits.doh)
1535
    /* nothing to wait for during DoH resolve, those handles have their own
1536
       sockets */
1537
0
    return CURLE_OK;
1538
0
#endif
1539
0
  return Curl_async_pollset(data, ps);
1540
#else
1541
  (void)data;
1542
  (void)ps;
1543
  return CURLE_OK;
1544
#endif
1545
0
}
1546
1547
/* Call this function after Curl_connect() has returned async=TRUE and
1548
   then a successful name resolve has been received.
1549
1550
   Note: this function disconnects and frees the conn data in case of
1551
   resolve failure */
1552
CURLcode Curl_once_resolved(struct Curl_easy *data,
1553
                            struct Curl_dns_entry *dns,
1554
                            bool *protocol_done)
1555
0
{
1556
0
  CURLcode result;
1557
0
  struct connectdata *conn = data->conn;
1558
1559
0
#ifdef USE_CURL_ASYNC
1560
0
  if(data->state.async.dns) {
1561
0
    DEBUGASSERT(data->state.async.dns == dns);
1562
0
    data->state.async.dns = NULL;
1563
0
  }
1564
0
#endif
1565
1566
0
  result = Curl_setup_conn(data, dns, protocol_done);
1567
1568
0
  if(result) {
1569
0
    Curl_detach_connection(data);
1570
0
    Curl_conn_terminate(data, conn, TRUE);
1571
0
  }
1572
0
  return result;
1573
0
}
1574
1575
/*
1576
 * Curl_resolver_error() calls failf() with the appropriate message after a
1577
 * resolve error
1578
 */
1579
1580
#ifdef USE_CURL_ASYNC
1581
CURLcode Curl_resolver_error(struct Curl_easy *data, const char *detail)
1582
0
{
1583
0
  struct connectdata *conn = data->conn;
1584
0
  const char *host_or_proxy = "host";
1585
0
  const char *name = conn->host.dispname;
1586
0
  CURLcode result = CURLE_COULDNT_RESOLVE_HOST;
1587
1588
0
#ifndef CURL_DISABLE_PROXY
1589
0
  if(conn->bits.proxy) {
1590
0
    host_or_proxy = "proxy";
1591
0
    result = CURLE_COULDNT_RESOLVE_PROXY;
1592
0
    name = conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
1593
0
      conn->http_proxy.host.dispname;
1594
0
  }
1595
0
#endif
1596
1597
0
  failf(data, "Could not resolve %s: %s%s%s%s", host_or_proxy, name,
1598
0
        detail ? " (" : "", detail ? detail : "", detail ? ")" : "");
1599
0
  return result;
1600
0
}
1601
#endif /* USE_CURL_ASYNC */