Coverage Report

Created: 2025-10-30 06:17

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