Coverage Report

Created: 2026-04-29 07:01

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