Coverage Report

Created: 2025-10-10 06:31

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
#ifndef CURL_DISABLE_DOH
852
0
  data->conn->bits.doh = FALSE; /* default is not */
853
#else
854
  (void)allowDOH;
855
#endif
856
0
  if(!dnscache)
857
0
    goto error;
858
859
  /* We should intentionally error and not resolve .onion TLDs */
860
0
  hostname_len = strlen(hostname);
861
0
  if(hostname_len >= 7 &&
862
0
     (curl_strequal(&hostname[hostname_len - 6], ".onion") ||
863
0
      curl_strequal(&hostname[hostname_len - 7], ".onion."))) {
864
0
    failf(data, "Not resolving .onion address (RFC 7686)");
865
0
    goto error;
866
0
  }
867
868
  /* Let's check our DNS cache first */
869
0
  dnscache_lock(data, dnscache);
870
0
  dns = fetch_addr(data, dnscache, hostname, port, ip_version);
871
0
  if(dns)
872
0
    dns->refcount++; /* we pass out the reference. */
873
0
  dnscache_unlock(data, dnscache);
874
0
  if(dns) {
875
0
    infof(data, "Hostname %s was found in DNS cache", hostname);
876
0
    goto out;
877
0
  }
878
879
  /* No luck, we need to resolve hostname. Notify user callback. */
880
0
  if(data->set.resolver_start) {
881
0
    void *resolver = NULL;
882
0
    int st;
883
0
#ifdef CURLRES_ASYNCH
884
0
    if(Curl_async_get_impl(data, &resolver))
885
0
      goto error;
886
0
#endif
887
0
    Curl_set_in_callback(data, TRUE);
888
0
    st = data->set.resolver_start(resolver, NULL,
889
0
                                  data->set.resolver_start_client);
890
0
    Curl_set_in_callback(data, FALSE);
891
0
    if(st) {
892
0
      keep_negative = FALSE;
893
0
      goto error;
894
0
    }
895
0
  }
896
897
  /* shortcut literal IP addresses, if we are not told to resolve them. */
898
0
  addr = convert_ipaddr_direct(hostname, port, &is_ipaddr);
899
0
  if(addr)
900
0
    goto out;
901
902
0
#ifndef USE_RESOLVE_ON_IPS
903
  /* allowed to convert, hostname is IP address, then NULL means error */
904
0
  if(is_ipaddr)
905
0
    goto error;
906
0
#endif
907
908
  /* Really need a resolver for hostname. */
909
0
  if(ip_version == CURL_IPRESOLVE_V6 && !Curl_ipv6works(data))
910
0
    goto error;
911
912
0
  if(!is_ipaddr &&
913
0
     (curl_strequal(hostname, "localhost") ||
914
0
      curl_strequal(hostname, "localhost.") ||
915
0
      tailmatch(hostname, hostname_len, STRCONST(".localhost")) ||
916
0
      tailmatch(hostname, hostname_len, STRCONST(".localhost.")))) {
917
0
    addr = get_localhost(port, hostname);
918
0
  }
919
0
#ifndef CURL_DISABLE_DOH
920
0
  else if(!is_ipaddr && allowDOH && data->set.doh) {
921
0
    addr = Curl_doh(data, hostname, port, ip_version, &respwait);
922
0
  }
923
0
#endif
924
0
  else {
925
    /* Can we provide the requested IP specifics in resolving? */
926
0
    if(!can_resolve_ip_version(data, ip_version))
927
0
      goto error;
928
929
0
#ifdef CURLRES_ASYNCH
930
0
    addr = Curl_async_getaddrinfo(data, hostname, port, ip_version, &respwait);
931
#else
932
    respwait = 0; /* no async waiting here */
933
    addr = Curl_sync_getaddrinfo(data, hostname, port, ip_version);
934
#endif
935
0
  }
936
937
0
out:
938
  /* We either have found a `dns` or looked up the `addr`
939
   * or `respwait` is set for an async operation.
940
   * Everything else is a failure to resolve. */
941
0
  if(dns) {
942
0
    if(!dns->addr) {
943
0
      infof(data, "Negative DNS entry");
944
0
      dns->refcount--;
945
0
      return CURLE_COULDNT_RESOLVE_HOST;
946
0
    }
947
0
    *entry = dns;
948
0
    return CURLE_OK;
949
0
  }
950
0
  else if(addr) {
951
    /* we got a response, create a dns entry, add to cache, return */
952
0
    dns = Curl_dnscache_mk_entry(data, addr, hostname, 0, port, FALSE);
953
0
    if(!dns || Curl_dnscache_add(data, dns)) {
954
      /* this is OOM or similar, don't store such negative resolves */
955
0
      keep_negative = FALSE;
956
0
      goto error;
957
0
    }
958
0
    show_resolve_info(data, dns);
959
0
    *entry = dns;
960
0
    return CURLE_OK;
961
0
  }
962
0
  else if(respwait) {
963
0
    if(!Curl_resolv_check(data, &dns)) {
964
0
      *entry = dns;
965
0
      return dns ? CURLE_OK : CURLE_AGAIN;
966
0
    }
967
0
  }
968
0
error:
969
0
  if(dns)
970
0
    Curl_resolv_unlink(data, &dns);
971
0
  *entry = NULL;
972
0
  Curl_async_shutdown(data);
973
0
  if(keep_negative)
974
0
    store_negative_resolve(data, hostname, port);
975
0
  return CURLE_COULDNT_RESOLVE_HOST;
976
0
}
977
978
CURLcode Curl_resolv_blocking(struct Curl_easy *data,
979
                              const char *hostname,
980
                              int port,
981
                              int ip_version,
982
                              struct Curl_dns_entry **dnsentry)
983
0
{
984
0
  CURLcode result;
985
986
0
  *dnsentry = NULL;
987
0
  result = Curl_resolv(data, hostname, port, ip_version, FALSE, dnsentry);
988
0
  switch(result) {
989
0
  case CURLE_OK:
990
0
    DEBUGASSERT(*dnsentry);
991
0
    return CURLE_OK;
992
0
  case CURLE_AGAIN:
993
0
    DEBUGASSERT(!*dnsentry);
994
0
    result = Curl_async_await(data, dnsentry);
995
0
    if(result || !*dnsentry) {
996
      /* close the connection, since we cannot return failure here without
997
         cleaning up this connection properly. */
998
0
      connclose(data->conn, "async resolve failed");
999
0
    }
1000
0
    return result;
1001
0
  default:
1002
0
    return result;
1003
0
  }
1004
0
}
1005
1006
#ifdef USE_ALARM_TIMEOUT
1007
/*
1008
 * This signal handler jumps back into the main libcurl code and continues
1009
 * execution. This effectively causes the remainder of the application to run
1010
 * within a signal handler which is nonportable and could lead to problems.
1011
 */
1012
CURL_NORETURN static
1013
void alarmfunc(int sig)
1014
{
1015
  (void)sig;
1016
  siglongjmp(curl_jmpenv, 1);
1017
}
1018
#endif /* USE_ALARM_TIMEOUT */
1019
1020
/*
1021
 * Curl_resolv_timeout() is the same as Curl_resolv() but specifies a
1022
 * timeout. This function might return immediately if we are using asynch
1023
 * resolves. See the return codes.
1024
 *
1025
 * The cache entry we return will get its 'inuse' counter increased when this
1026
 * function is used. You MUST call Curl_resolv_unlink() later (when you are
1027
 * done using this struct) to decrease the reference counter again.
1028
 *
1029
 * If built with a synchronous resolver and use of signals is not
1030
 * disabled by the application, then a nonzero timeout will cause a
1031
 * timeout after the specified number of milliseconds. Otherwise, timeout
1032
 * is ignored.
1033
 *
1034
 * Return codes:
1035
 * CURLE_OK = success, *entry set to non-NULL
1036
 * CURLE_AGAIN = resolving in progress, *entry == NULL
1037
 * CURLE_COULDNT_RESOLVE_HOST = error, *entry == NULL
1038
 * CURLE_OPERATION_TIMEDOUT = timeout expired, *entry == NULL
1039
 */
1040
1041
CURLcode Curl_resolv_timeout(struct Curl_easy *data,
1042
                             const char *hostname,
1043
                             int port,
1044
                             int ip_version,
1045
                             struct Curl_dns_entry **entry,
1046
                             timediff_t timeoutms)
1047
0
{
1048
#ifdef USE_ALARM_TIMEOUT
1049
#ifdef HAVE_SIGACTION
1050
  struct sigaction keep_sigact;   /* store the old struct here */
1051
  volatile bool keep_copysig = FALSE; /* whether old sigact has been saved */
1052
  struct sigaction sigact;
1053
#else
1054
#ifdef HAVE_SIGNAL
1055
  void (*keep_sigact)(int);       /* store the old handler here */
1056
#endif /* HAVE_SIGNAL */
1057
#endif /* HAVE_SIGACTION */
1058
  volatile long timeout;
1059
  volatile unsigned int prev_alarm = 0;
1060
#endif /* USE_ALARM_TIMEOUT */
1061
0
  CURLcode result;
1062
1063
0
  *entry = NULL;
1064
1065
0
  if(timeoutms < 0)
1066
    /* got an already expired timeout */
1067
0
    return CURLE_OPERATION_TIMEDOUT;
1068
1069
#ifdef USE_ALARM_TIMEOUT
1070
  if(data->set.no_signal)
1071
    /* Ignore the timeout when signals are disabled */
1072
    timeout = 0;
1073
  else
1074
    timeout = (timeoutms > LONG_MAX) ? LONG_MAX : (long)timeoutms;
1075
1076
  if(!timeout
1077
#ifndef CURL_DISABLE_DOH
1078
     || data->set.doh
1079
#endif
1080
    )
1081
    /* USE_ALARM_TIMEOUT defined, but no timeout actually requested or resolve
1082
       done using DoH */
1083
    return Curl_resolv(data, hostname, port, ip_version, TRUE, entry);
1084
1085
  if(timeout < 1000) {
1086
    /* The alarm() function only provides integer second resolution, so if
1087
       we want to wait less than one second we must bail out already now. */
1088
    failf(data,
1089
        "remaining timeout of %ld too small to resolve via SIGALRM method",
1090
        timeout);
1091
    return CURLE_OPERATION_TIMEDOUT;
1092
  }
1093
  /* This allows us to time-out from the name resolver, as the timeout
1094
     will generate a signal and we will siglongjmp() from that here.
1095
     This technique has problems (see alarmfunc).
1096
     This should be the last thing we do before calling Curl_resolv(),
1097
     as otherwise we would have to worry about variables that get modified
1098
     before we invoke Curl_resolv() (and thus use "volatile"). */
1099
  curl_simple_lock_lock(&curl_jmpenv_lock);
1100
1101
  if(sigsetjmp(curl_jmpenv, 1)) {
1102
    /* this is coming from a siglongjmp() after an alarm signal */
1103
    failf(data, "name lookup timed out");
1104
    result = CURLE_OPERATION_TIMEDOUT;
1105
    goto clean_up;
1106
  }
1107
  else {
1108
    /*************************************************************
1109
     * Set signal handler to catch SIGALRM
1110
     * Store the old value to be able to set it back later!
1111
     *************************************************************/
1112
#ifdef HAVE_SIGACTION
1113
    sigaction(SIGALRM, NULL, &sigact);
1114
    keep_sigact = sigact;
1115
    keep_copysig = TRUE; /* yes, we have a copy */
1116
    sigact.sa_handler = alarmfunc;
1117
#ifdef SA_RESTART
1118
    /* HP-UX does not have SA_RESTART but defaults to that behavior! */
1119
    sigact.sa_flags &= ~SA_RESTART;
1120
#endif
1121
    /* now set the new struct */
1122
    sigaction(SIGALRM, &sigact, NULL);
1123
#else /* HAVE_SIGACTION */
1124
    /* no sigaction(), revert to the much lamer signal() */
1125
#ifdef HAVE_SIGNAL
1126
    keep_sigact = signal(SIGALRM, alarmfunc);
1127
#endif
1128
#endif /* HAVE_SIGACTION */
1129
1130
    /* alarm() makes a signal get sent when the timeout fires off, and that
1131
       will abort system calls */
1132
    prev_alarm = alarm(curlx_sltoui(timeout/1000L));
1133
  }
1134
1135
#else /* !USE_ALARM_TIMEOUT */
1136
#ifndef CURLRES_ASYNCH
1137
  if(timeoutms)
1138
    infof(data, "timeout on name lookup is not supported");
1139
#else
1140
0
  (void)timeoutms;
1141
0
#endif
1142
0
#endif /* USE_ALARM_TIMEOUT */
1143
1144
  /* Perform the actual name resolution. This might be interrupted by an
1145
   * alarm if it takes too long.
1146
   */
1147
0
  result = Curl_resolv(data, hostname, port, ip_version, TRUE, entry);
1148
1149
#ifdef USE_ALARM_TIMEOUT
1150
clean_up:
1151
1152
  if(!prev_alarm)
1153
    /* deactivate a possibly active alarm before uninstalling the handler */
1154
    alarm(0);
1155
1156
#ifdef HAVE_SIGACTION
1157
  if(keep_copysig) {
1158
    /* we got a struct as it looked before, now put that one back nice
1159
       and clean */
1160
    sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
1161
  }
1162
#else
1163
#ifdef HAVE_SIGNAL
1164
  /* restore the previous SIGALRM handler */
1165
  signal(SIGALRM, keep_sigact);
1166
#endif
1167
#endif /* HAVE_SIGACTION */
1168
1169
  curl_simple_lock_unlock(&curl_jmpenv_lock);
1170
1171
  /* switch back the alarm() to either zero or to what it was before minus
1172
     the time we spent until now! */
1173
  if(prev_alarm) {
1174
    /* there was an alarm() set before us, now put it back */
1175
    timediff_t elapsed_secs = curlx_timediff(curlx_now(),
1176
                                            data->conn->created) / 1000;
1177
1178
    /* the alarm period is counted in even number of seconds */
1179
    unsigned long alarm_set = (unsigned long)(prev_alarm - elapsed_secs);
1180
1181
    if(!alarm_set ||
1182
       ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
1183
      /* if the alarm time-left reached zero or turned "negative" (counted
1184
         with unsigned values), we should fire off a SIGALRM here, but we
1185
         will not, and zero would be to switch it off so we never set it to
1186
         less than 1! */
1187
      alarm(1);
1188
      result = CURLE_OPERATION_TIMEDOUT;
1189
      failf(data, "Previous alarm fired off");
1190
    }
1191
    else
1192
      alarm((unsigned int)alarm_set);
1193
  }
1194
#endif /* USE_ALARM_TIMEOUT */
1195
1196
0
  return result;
1197
0
}
1198
1199
static void dnscache_entry_free(struct Curl_dns_entry *dns)
1200
0
{
1201
0
  Curl_freeaddrinfo(dns->addr);
1202
#ifdef USE_HTTPSRR
1203
  if(dns->hinfo) {
1204
    Curl_httpsrr_cleanup(dns->hinfo);
1205
    free(dns->hinfo);
1206
  }
1207
#endif
1208
0
  free(dns);
1209
0
}
1210
1211
/*
1212
 * Curl_resolv_unlink() releases a reference to the given cached DNS entry.
1213
 * When the reference count reaches 0, the entry is destroyed. It is important
1214
 * that only one unlink is made for each Curl_resolv() call.
1215
 *
1216
 * May be called with 'data' == NULL for global cache.
1217
 */
1218
void Curl_resolv_unlink(struct Curl_easy *data, struct Curl_dns_entry **pdns)
1219
0
{
1220
0
  if(*pdns) {
1221
0
    struct Curl_dnscache *dnscache = dnscache_get(data);
1222
0
    struct Curl_dns_entry *dns = *pdns;
1223
0
    *pdns = NULL;
1224
0
    dnscache_lock(data, dnscache);
1225
0
    dns->refcount--;
1226
0
    if(dns->refcount == 0)
1227
0
      dnscache_entry_free(dns);
1228
0
    dnscache_unlock(data, dnscache);
1229
0
  }
1230
0
}
1231
1232
static void dnscache_entry_dtor(void *entry)
1233
0
{
1234
0
  struct Curl_dns_entry *dns = (struct Curl_dns_entry *) entry;
1235
0
  DEBUGASSERT(dns && (dns->refcount > 0));
1236
0
  dns->refcount--;
1237
0
  if(dns->refcount == 0)
1238
0
    dnscache_entry_free(dns);
1239
0
}
1240
1241
/*
1242
 * Curl_dnscache_init() inits a new DNS cache.
1243
 */
1244
void Curl_dnscache_init(struct Curl_dnscache *dns, size_t size)
1245
0
{
1246
0
  Curl_hash_init(&dns->entries, size, Curl_hash_str, curlx_str_key_compare,
1247
0
                 dnscache_entry_dtor);
1248
0
}
1249
1250
void Curl_dnscache_destroy(struct Curl_dnscache *dns)
1251
0
{
1252
0
  Curl_hash_destroy(&dns->entries);
1253
0
}
1254
1255
CURLcode Curl_loadhostpairs(struct Curl_easy *data)
1256
0
{
1257
0
  struct Curl_dnscache *dnscache = dnscache_get(data);
1258
0
  struct curl_slist *hostp;
1259
1260
0
  if(!dnscache)
1261
0
    return CURLE_FAILED_INIT;
1262
1263
  /* Default is no wildcard found */
1264
0
  data->state.wildcard_resolve = FALSE;
1265
1266
0
  for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
1267
0
    char entry_id[MAX_HOSTCACHE_LEN];
1268
0
    const char *host = hostp->data;
1269
0
    struct Curl_str source;
1270
0
    if(!host)
1271
0
      continue;
1272
0
    if(*host == '-') {
1273
0
      curl_off_t num = 0;
1274
0
      size_t entry_len;
1275
0
      host++;
1276
0
      if(!curlx_str_single(&host, '[')) {
1277
0
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
1278
0
           curlx_str_single(&host, ']') ||
1279
0
           curlx_str_single(&host, ':'))
1280
0
          continue;
1281
0
      }
1282
0
      else {
1283
0
        if(curlx_str_until(&host, &source, 4096, ':') ||
1284
0
           curlx_str_single(&host, ':')) {
1285
0
          continue;
1286
0
        }
1287
0
      }
1288
1289
0
      if(!curlx_str_number(&host, &num, 0xffff)) {
1290
        /* Create an entry id, based upon the hostname and port */
1291
0
        entry_len = create_dnscache_id(curlx_str(&source),
1292
0
                                       curlx_strlen(&source), (int)num,
1293
0
                                       entry_id, sizeof(entry_id));
1294
0
        dnscache_lock(data, dnscache);
1295
        /* delete entry, ignore if it did not exist */
1296
0
        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
1297
0
        dnscache_unlock(data, dnscache);
1298
0
      }
1299
0
    }
1300
0
    else {
1301
0
      struct Curl_dns_entry *dns;
1302
0
      struct Curl_addrinfo *head = NULL, *tail = NULL;
1303
0
      size_t entry_len;
1304
0
      char address[64];
1305
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1306
0
      const char *addresses = NULL;
1307
0
#endif
1308
0
      curl_off_t port = 0;
1309
0
      bool permanent = TRUE;
1310
0
      bool error = TRUE;
1311
1312
0
      if(*host == '+') {
1313
0
        host++;
1314
0
        permanent = FALSE;
1315
0
      }
1316
0
      if(!curlx_str_single(&host, '[')) {
1317
0
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
1318
0
           curlx_str_single(&host, ']'))
1319
0
          continue;
1320
0
      }
1321
0
      else {
1322
0
        if(curlx_str_until(&host, &source, 4096, ':'))
1323
0
          continue;
1324
0
      }
1325
0
      if(curlx_str_single(&host, ':') ||
1326
0
         curlx_str_number(&host, &port, 0xffff) ||
1327
0
         curlx_str_single(&host, ':'))
1328
0
        goto err;
1329
1330
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1331
0
      addresses = host;
1332
0
#endif
1333
1334
      /* start the address section */
1335
0
      while(*host) {
1336
0
        struct Curl_str target;
1337
0
        struct Curl_addrinfo *ai;
1338
1339
0
        if(!curlx_str_single(&host, '[')) {
1340
0
          if(curlx_str_until(&host, &target, MAX_IPADR_LEN, ']') ||
1341
0
             curlx_str_single(&host, ']'))
1342
0
            goto err;
1343
0
        }
1344
0
        else {
1345
0
          if(curlx_str_until(&host, &target, 4096, ',')) {
1346
0
            if(curlx_str_single(&host, ','))
1347
0
              goto err;
1348
            /* survive nothing but just a comma */
1349
0
            continue;
1350
0
          }
1351
0
        }
1352
#ifndef USE_IPV6
1353
        if(memchr(target.str, ':', target.len)) {
1354
          infof(data, "Ignoring resolve address '%s', missing IPv6 support.",
1355
                address);
1356
          if(curlx_str_single(&host, ','))
1357
            goto err;
1358
          continue;
1359
        }
1360
#endif
1361
1362
0
        if(curlx_strlen(&target) >= sizeof(address))
1363
0
          goto err;
1364
1365
0
        memcpy(address, curlx_str(&target), curlx_strlen(&target));
1366
0
        address[curlx_strlen(&target)] = '\0';
1367
1368
0
        ai = Curl_str2addr(address, (int)port);
1369
0
        if(!ai) {
1370
0
          infof(data, "Resolve address '%s' found illegal", address);
1371
0
          goto err;
1372
0
        }
1373
1374
0
        if(tail) {
1375
0
          tail->ai_next = ai;
1376
0
          tail = tail->ai_next;
1377
0
        }
1378
0
        else {
1379
0
          head = tail = ai;
1380
0
        }
1381
0
        if(curlx_str_single(&host, ','))
1382
0
          break;
1383
0
      }
1384
1385
0
      if(!head)
1386
0
        goto err;
1387
1388
0
      error = FALSE;
1389
0
err:
1390
0
      if(error) {
1391
0
        failf(data, "Couldn't parse CURLOPT_RESOLVE entry '%s'",
1392
0
              hostp->data);
1393
0
        Curl_freeaddrinfo(head);
1394
0
        return CURLE_SETOPT_OPTION_SYNTAX;
1395
0
      }
1396
1397
      /* Create an entry id, based upon the hostname and port */
1398
0
      entry_len = create_dnscache_id(curlx_str(&source), curlx_strlen(&source),
1399
0
                                     (int)port,
1400
0
                                     entry_id, sizeof(entry_id));
1401
1402
0
      dnscache_lock(data, dnscache);
1403
1404
      /* See if it is already in our dns cache */
1405
0
      dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);
1406
1407
0
      if(dns) {
1408
0
        infof(data, "RESOLVE %.*s:%" CURL_FORMAT_CURL_OFF_T
1409
0
              " - old addresses discarded", (int)curlx_strlen(&source),
1410
0
              curlx_str(&source), port);
1411
        /* delete old entry, there are two reasons for this
1412
         1. old entry may have different addresses.
1413
         2. even if entry with correct addresses is already in the cache,
1414
            but if it is close to expire, then by the time next http
1415
            request is made, it can get expired and pruned because old
1416
            entry is not necessarily marked as permanent.
1417
         3. when adding a non-permanent entry, we want it to remove and
1418
            replace an existing permanent entry.
1419
         4. when adding a non-permanent entry, we want it to get a "fresh"
1420
            timeout that starts _now_. */
1421
1422
0
        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
1423
0
      }
1424
1425
      /* put this new host in the cache */
1426
0
      dns = dnscache_add_addr(data, dnscache, head, curlx_str(&source),
1427
0
                              curlx_strlen(&source), (int)port, permanent);
1428
0
      if(dns) {
1429
        /* release the returned reference; the cache itself will keep the
1430
         * entry alive: */
1431
0
        dns->refcount--;
1432
0
      }
1433
1434
0
      dnscache_unlock(data, dnscache);
1435
1436
0
      if(!dns)
1437
0
        return CURLE_OUT_OF_MEMORY;
1438
1439
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1440
0
      infof(data, "Added %.*s:%" CURL_FORMAT_CURL_OFF_T ":%s to DNS cache%s",
1441
0
            (int)curlx_strlen(&source), curlx_str(&source), port, addresses,
1442
0
            permanent ? "" : " (non-permanent)");
1443
0
#endif
1444
1445
      /* Wildcard hostname */
1446
0
      if(curlx_str_casecompare(&source, "*")) {
1447
0
        infof(data, "RESOLVE *:%" CURL_FORMAT_CURL_OFF_T " using wildcard",
1448
0
              port);
1449
0
        data->state.wildcard_resolve = TRUE;
1450
0
      }
1451
0
    }
1452
0
  }
1453
0
  data->state.resolve = NULL; /* dealt with now */
1454
1455
0
  return CURLE_OK;
1456
0
}
1457
1458
#ifndef CURL_DISABLE_VERBOSE_STRINGS
1459
static void show_resolve_info(struct Curl_easy *data,
1460
                              struct Curl_dns_entry *dns)
1461
0
{
1462
0
  struct Curl_addrinfo *a;
1463
0
  CURLcode result = CURLE_OK;
1464
0
#ifdef CURLRES_IPV6
1465
0
  struct dynbuf out[2];
1466
#else
1467
  struct dynbuf out[1];
1468
#endif
1469
0
  DEBUGASSERT(data);
1470
0
  DEBUGASSERT(dns);
1471
1472
0
  if(!data->set.verbose ||
1473
     /* ignore no name or numerical IP addresses */
1474
0
     !dns->hostname[0] || Curl_host_is_ipnum(dns->hostname))
1475
0
    return;
1476
1477
0
  a = dns->addr;
1478
1479
0
  infof(data, "Host %s:%d was resolved.",
1480
0
        (dns->hostname[0] ? dns->hostname : "(none)"), dns->hostport);
1481
1482
0
  curlx_dyn_init(&out[0], 1024);
1483
0
#ifdef CURLRES_IPV6
1484
0
  curlx_dyn_init(&out[1], 1024);
1485
0
#endif
1486
1487
0
  while(a) {
1488
0
    if(
1489
0
#ifdef CURLRES_IPV6
1490
0
       a->ai_family == PF_INET6 ||
1491
0
#endif
1492
0
       a->ai_family == PF_INET) {
1493
0
      char buf[MAX_IPADR_LEN];
1494
0
      struct dynbuf *d = &out[(a->ai_family != PF_INET)];
1495
0
      Curl_printable_address(a, buf, sizeof(buf));
1496
0
      if(curlx_dyn_len(d))
1497
0
        result = curlx_dyn_addn(d, ", ", 2);
1498
0
      if(!result)
1499
0
        result = curlx_dyn_add(d, buf);
1500
0
      if(result) {
1501
0
        infof(data, "too many IP, cannot show");
1502
0
        goto fail;
1503
0
      }
1504
0
    }
1505
0
    a = a->ai_next;
1506
0
  }
1507
1508
0
#ifdef CURLRES_IPV6
1509
0
  infof(data, "IPv6: %s",
1510
0
        (curlx_dyn_len(&out[1]) ? curlx_dyn_ptr(&out[1]) : "(none)"));
1511
0
#endif
1512
0
  infof(data, "IPv4: %s",
1513
0
        (curlx_dyn_len(&out[0]) ? curlx_dyn_ptr(&out[0]) : "(none)"));
1514
1515
0
fail:
1516
0
  curlx_dyn_free(&out[0]);
1517
0
#ifdef CURLRES_IPV6
1518
0
  curlx_dyn_free(&out[1]);
1519
0
#endif
1520
0
}
1521
#endif
1522
1523
#ifdef USE_CURL_ASYNC
1524
CURLcode Curl_resolv_check(struct Curl_easy *data,
1525
                           struct Curl_dns_entry **dns)
1526
0
{
1527
0
  CURLcode result;
1528
1529
  /* If async resolving is ongoing, this must be set */
1530
0
  if(!data->state.async.hostname)
1531
0
    return CURLE_FAILED_INIT;
1532
1533
  /* check if we have the name resolved by now (from someone else) */
1534
0
  *dns = Curl_dnscache_get(data, data->state.async.hostname,
1535
0
                           data->state.async.port,
1536
0
                           data->state.async.ip_version);
1537
0
  if(*dns) {
1538
    /* Tell a possibly async resolver we no longer need the results. */
1539
0
    infof(data, "Hostname '%s' was found in DNS cache",
1540
0
          data->state.async.hostname);
1541
0
    Curl_async_shutdown(data);
1542
0
    data->state.async.dns = *dns;
1543
0
    data->state.async.done = TRUE;
1544
0
    return CURLE_OK;
1545
0
  }
1546
1547
0
#ifndef CURL_DISABLE_DOH
1548
0
  if(data->conn->bits.doh) {
1549
0
    result = Curl_doh_is_resolved(data, dns);
1550
0
    if(result)
1551
0
      Curl_resolver_error(data, NULL);
1552
0
  }
1553
0
  else
1554
0
#endif
1555
0
  result = Curl_async_is_resolved(data, dns);
1556
0
  if(*dns)
1557
0
    show_resolve_info(data, *dns);
1558
0
  if((result == CURLE_COULDNT_RESOLVE_HOST) ||
1559
0
     (result == CURLE_COULDNT_RESOLVE_PROXY))
1560
0
    store_negative_resolve(data, data->state.async.hostname,
1561
0
                           data->state.async.port);
1562
0
  return result;
1563
0
}
1564
#endif
1565
1566
CURLcode Curl_resolv_pollset(struct Curl_easy *data,
1567
                             struct easy_pollset *ps)
1568
0
{
1569
0
#ifdef CURLRES_ASYNCH
1570
0
#ifndef CURL_DISABLE_DOH
1571
0
  if(data->conn->bits.doh)
1572
    /* nothing to wait for during DoH resolve, those handles have their own
1573
       sockets */
1574
0
    return CURLE_OK;
1575
0
#endif
1576
0
  return Curl_async_pollset(data, ps);
1577
#else
1578
  (void)data;
1579
  (void)ps;
1580
  return CURLE_OK;
1581
#endif
1582
0
}
1583
1584
/* Call this function after Curl_connect() has returned async=TRUE and
1585
   then a successful name resolve has been received.
1586
1587
   Note: this function disconnects and frees the conn data in case of
1588
   resolve failure */
1589
CURLcode Curl_once_resolved(struct Curl_easy *data,
1590
                            struct Curl_dns_entry *dns,
1591
                            bool *protocol_done)
1592
0
{
1593
0
  CURLcode result;
1594
0
  struct connectdata *conn = data->conn;
1595
1596
0
#ifdef USE_CURL_ASYNC
1597
0
  if(data->state.async.dns) {
1598
0
    DEBUGASSERT(data->state.async.dns == dns);
1599
0
    data->state.async.dns = NULL;
1600
0
  }
1601
0
#endif
1602
1603
0
  result = Curl_setup_conn(data, dns, protocol_done);
1604
1605
0
  if(result) {
1606
0
    Curl_detach_connection(data);
1607
0
    Curl_conn_terminate(data, conn, TRUE);
1608
0
  }
1609
0
  return result;
1610
0
}
1611
1612
/*
1613
 * Curl_resolver_error() calls failf() with the appropriate message after a
1614
 * resolve error
1615
 */
1616
1617
#ifdef USE_CURL_ASYNC
1618
CURLcode Curl_resolver_error(struct Curl_easy *data, const char *detail)
1619
0
{
1620
0
  struct connectdata *conn = data->conn;
1621
0
  const char *host_or_proxy = "host";
1622
0
  const char *name = conn->host.dispname;
1623
0
  CURLcode result = CURLE_COULDNT_RESOLVE_HOST;
1624
1625
0
#ifndef CURL_DISABLE_PROXY
1626
0
  if(conn->bits.proxy) {
1627
0
    host_or_proxy = "proxy";
1628
0
    result = CURLE_COULDNT_RESOLVE_PROXY;
1629
0
    name = conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
1630
0
      conn->http_proxy.host.dispname;
1631
0
  }
1632
0
#endif
1633
1634
0
  failf(data, "Could not resolve %s: %s%s%s%s", host_or_proxy, name,
1635
0
        detail ? " (" : "", detail ? detail : "", detail ? ")" : "");
1636
0
  return result;
1637
0
}
1638
#endif /* USE_CURL_ASYNC */