curl-sys 0.4.90+curl-8.21.0

Native bindings to the libcurl library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 * SPDX-License-Identifier: curl
 *
 ***************************************************************************/
#include "curl_setup.h"

#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_IN6_H
#include <netinet/in6.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif

#include "urldata.h"
#include "curl_addrinfo.h"
#include "curl_share.h"
#include "curl_trc.h"
#include "dnscache.h"
#include "hash.h"
#include "hostip.h"
#include "httpsrr.h"
#include "progress.h"
#include "rand.h"
#include "strcase.h"
#include "curlx/inet_ntop.h"
#include "curlx/inet_pton.h"
#include "curlx/strcopy.h"
#include "curlx/strparse.h"

#define MAX_HOSTCACHE_LEN (255 + 7) /* max FQDN + colon + port number + zero */

#define MAX_DNS_CACHE_SIZE 29999

static void dnscache_entry_free(struct Curl_dns_entry *dns)
{
  Curl_freeaddrinfo(dns->addr);
#ifdef USE_HTTPSRR
  if(dns->hinfo) {
    Curl_httpsrr_cleanup(dns->hinfo);
    curlx_free(dns->hinfo);
  }
#endif
  curlx_free(dns);
}

/*
 * Create a hostcache id string for the provided host + port, to be used by
 * the DNS caching. Without alloc. Return length of the id string.
 */
static size_t create_dnscache_id(const char *name,
                                 size_t nlen, /* 0 or actual name length */
                                 uint16_t port, char *ptr, size_t buflen)
{
  size_t len = nlen ? nlen : strlen(name);
  DEBUGASSERT(buflen >= MAX_HOSTCACHE_LEN);
  if(len > (buflen - 7))
    len = buflen - 7;
  /* store and lower case the name */
  Curl_strntolower(ptr, name, len);
  return curl_msnprintf(&ptr[len], 7, ":%u", port) + len;
}

struct dnscache_prune_data {
  struct curltime now;
  timediff_t oldest_ms; /* oldest time in cache not pruned. */
  timediff_t max_age_ms;
};

/*
 * This function is set as a callback to be called for every entry in the DNS
 * cache when we want to prune old unused entries.
 *
 * Returning non-zero means remove the entry, return 0 to keep it in the
 * cache.
 */
static int dnscache_entry_is_stale(void *datap, void *hc)
{
  struct dnscache_prune_data *prune = (struct dnscache_prune_data *)datap;
  struct Curl_dns_entry *dns = (struct Curl_dns_entry *)hc;

  if(dns->timestamp.tv_sec || dns->timestamp.tv_usec) {
    /* get age in milliseconds */
    timediff_t age = curlx_ptimediff_ms(&prune->now, &dns->timestamp);
    if(!dns->addr)
      age *= 2; /* negative entries age twice as fast */
    if(age >= prune->max_age_ms)
      return TRUE;
    if(age > prune->oldest_ms)
      prune->oldest_ms = age;
  }
  return FALSE;
}

/*
 * Prune the DNS cache. This assumes that a lock has already been taken.
 * Returns the 'age' of the oldest still kept entry - in milliseconds.
 */
static timediff_t dnscache_prune(struct Curl_hash *hostcache,
                                 timediff_t cache_timeout_ms,
                                 struct curltime now)
{
  struct dnscache_prune_data user;

  user.max_age_ms = cache_timeout_ms;
  user.now = now;
  user.oldest_ms = 0;

  Curl_hash_clean_with_criterium(hostcache,
                                 (void *)&user,
                                 dnscache_entry_is_stale);

  return user.oldest_ms;
}

static struct Curl_dnscache *dnscache_get(struct Curl_easy *data)
{
  if(data->share && data->share->specifier & (1 << CURL_LOCK_DATA_DNS))
    return &data->share->dnscache;
  if(data->multi)
    return &data->multi->dnscache;
  return NULL;
}

static void dnscache_lock(struct Curl_easy *data,
                          struct Curl_dnscache *dnscache)
{
  if(data->share && dnscache == &data->share->dnscache)
    Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
}

static void dnscache_unlock(struct Curl_easy *data,
                            struct Curl_dnscache *dnscache)
{
  if(data->share && dnscache == &data->share->dnscache)
    Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
}

/*
 * Library-wide function for pruning the DNS cache. This function takes and
 * returns the appropriate locks.
 */
void Curl_dnscache_prune(struct Curl_easy *data)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  /* the timeout may be set -1 (forever) */
  timediff_t timeout_ms = data->set.dns_cache_timeout_ms;

  if(!dnscache || (timeout_ms == -1))
    /* NULL hostcache means we cannot do it */
    return;

  dnscache_lock(data, dnscache);

  do {
    /* Remove outdated and unused entries from the hostcache */
    timediff_t oldest_ms =
      dnscache_prune(&dnscache->entries, timeout_ms, *Curl_pgrs_now(data));

    if(Curl_hash_count(&dnscache->entries) > MAX_DNS_CACHE_SIZE)
      /* prune the ones over half this age */
      timeout_ms = oldest_ms / 2;
    else
      break;

    /* if the cache size is still too big, use the oldest age as new prune
       limit */
  } while(timeout_ms);

  dnscache_unlock(data, dnscache);
}

void Curl_dnscache_clear(struct Curl_easy *data)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  if(dnscache) {
    dnscache_lock(data, dnscache);
    Curl_hash_clean(&dnscache->entries);
    dnscache_unlock(data, dnscache);
  }
}

/* lookup address, returns entry if found and not stale */
static CURLcode fetch_addr(struct Curl_easy *data,
                           struct Curl_dnscache *dnscache,
                           uint8_t dns_queries,
                           const char *hostname,
                           uint16_t port,
                           struct Curl_dns_entry **pdns)
{
  struct Curl_dns_entry *dns = NULL;
  char entry_id[MAX_HOSTCACHE_LEN];
  size_t entry_len;
  CURLcode result = CURLE_OK;

  *pdns = NULL;
  if(!dnscache)
    return CURLE_OK;

  /* Create an entry id, based upon the hostname and port */
  entry_len = create_dnscache_id(hostname, 0, port,
                                 entry_id, sizeof(entry_id));

  /* See if it is already in our dns cache */
  dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);

  /* No entry found in cache, check if we might have a wildcard entry */
  if(!dns && data->state.wildcard_resolve) {
    entry_len = create_dnscache_id("*", 1, port, entry_id, sizeof(entry_id));

    /* See if it is already in our dns cache */
    dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);
  }

  if(dns && (data->set.dns_cache_timeout_ms != -1)) {
    /* See whether the returned entry is stale. Done before we release lock */
    struct dnscache_prune_data user;

    user.now = *Curl_pgrs_now(data);
    user.max_age_ms = data->set.dns_cache_timeout_ms;
    user.oldest_ms = 0;

    if(dnscache_entry_is_stale(&user, dns)) {
      infof(data, "Hostname in DNS cache was stale, zapped");
      dns = NULL; /* the memory deallocation is being handled by the hash */
      Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
    }
  }

  if(dns) {
    if((dns->dns_queries & dns_queries) != dns_queries) {
      /* The entry does not cover all wanted DNS queries, a miss. */
      dns = NULL;
    }
    else if(!(dns->dns_responses & dns_queries)) {
      /* The entry has no responses for the wanted DNS queries. */
      CURL_TRC_DNS(data, "cache entry does not have type=%s addresses",
                   Curl_resolv_query_str(dns_queries));
      dns = NULL;
      result = CURLE_COULDNT_RESOLVE_HOST;
    }
  }

  if(dns && !dns->addr) { /* negative entry */
    dns = NULL;
    result = CURLE_COULDNT_RESOLVE_HOST;
  }
  *pdns = dns;
  return result;
}

/*
 * Curl_dnscache_get() fetches a 'Curl_dns_entry' already in the DNS cache.
 *
 * Curl_resolv() checks initially and multi_runsingle() checks each time
 * it discovers the handle in the state WAITRESOLVE whether the hostname
 * has already been resolved and the address has already been stored in
 * the DNS cache. This short circuits waiting for a lot of pending
 * lookups for the same hostname requested by different handles.
 *
 * Returns the Curl_dns_entry entry pointer or NULL if not in the cache.
 *
 * The returned data *MUST* be "released" with Curl_dns_entry_unlink() after
 * use, or we will leak memory!
 */
CURLcode Curl_dnscache_get(struct Curl_easy *data,
                           uint8_t dns_queries,
                           const char *hostname,
                           uint16_t port,
                           struct Curl_dns_entry **pentry)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  struct Curl_dns_entry *dns = NULL;
  CURLcode result = CURLE_OK;

  dnscache_lock(data, dnscache);
  result = fetch_addr(data, dnscache, dns_queries, hostname, port, &dns);
  if(!result && dns)
    dns->refcount++; /* we pass out a reference */
  else if(result) {
    DEBUGASSERT(!dns);
    dns = NULL;
  }
  dnscache_unlock(data, dnscache);

  *pentry = dns;
  return result;
}

#ifndef CURL_DISABLE_SHUFFLE_DNS
/*
 * Return # of addresses in a Curl_addrinfo struct
 */
static int num_addresses(const struct Curl_addrinfo *addr)
{
  int i = 0;
  while(addr) {
    addr = addr->ai_next;
    i++;
  }
  return i;
}

/*
 * dns_shuffle_addr() shuffles the order of addresses in a 'Curl_addrinfo'
 * struct by re-linking its linked list.
 *
 * The addr argument should be the address of a pointer to the head node of a
 * `Curl_addrinfo` list and it will be modified to point to the new head after
 * shuffling.
 *
 * Not declared static only to make it easy to use in a unit test!
 *
 * @unittest 1608
 */
UNITTEST CURLcode dns_shuffle_addr(struct Curl_easy *data,
                                   struct Curl_addrinfo **addr);
UNITTEST CURLcode dns_shuffle_addr(struct Curl_easy *data,
                                   struct Curl_addrinfo **addr)
{
  CURLcode result = CURLE_OK;
  const int num_addrs = num_addresses(*addr);

  if(num_addrs > 1) {
    struct Curl_addrinfo **nodes;
    CURL_TRC_DNS(data, "Shuffling %d addresses", num_addrs);

    nodes = curlx_malloc(num_addrs * sizeof(*nodes));
    if(nodes) {
      int i;
      unsigned int *rnd;
      const size_t rnd_size = num_addrs * sizeof(*rnd);

      /* build a plain array of Curl_addrinfo pointers */
      nodes[0] = *addr;
      for(i = 1; i < num_addrs; i++) {
        nodes[i] = nodes[i - 1]->ai_next;
      }

      rnd = curlx_malloc(rnd_size);
      if(rnd) {
        /* Fisher-Yates shuffle */
        if(Curl_rand(data, (unsigned char *)rnd, rnd_size) == CURLE_OK) {
          struct Curl_addrinfo *swap_tmp;
          for(i = num_addrs - 1; i > 0; i--) {
            swap_tmp = nodes[rnd[i] % (unsigned int)(i + 1)];
            nodes[rnd[i] % (unsigned int)(i + 1)] = nodes[i];
            nodes[i] = swap_tmp;
          }

          /* relink list in the new order */
          for(i = 1; i < num_addrs; i++) {
            nodes[i - 1]->ai_next = nodes[i];
          }

          nodes[num_addrs - 1]->ai_next = NULL;
          *addr = nodes[0];
        }
        curlx_free(rnd);
      }
      else
        result = CURLE_OUT_OF_MEMORY;
      curlx_free(nodes);
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }
  return result;
}
#endif

static bool dnscache_ai_has_family(struct Curl_addrinfo *ai,
                                   int ai_family)
{
  for(; ai; ai = ai->ai_next) {
    if(ai->ai_family == ai_family)
      return TRUE;
  }
  return FALSE;
}

static struct Curl_dns_entry *dnscache_entry_create(
  struct Curl_easy *data,
  uint8_t dns_queries,
  struct Curl_addrinfo **paddr1,
  struct Curl_addrinfo **paddr2,
  const char *hostname,
  size_t hostlen,
  uint16_t port,
  bool permanent)
{
  struct Curl_dns_entry *dns = NULL;

  /* Create a new cache entry, struct already has the hostname NUL */
  dns = curlx_calloc(1, sizeof(struct Curl_dns_entry) + hostlen);
  if(!dns)
    goto out;

  dns->refcount = 1; /* the cache has the first reference */
  dns->dns_queries = dns_queries;
  dns->port = port;
  if(hostlen)
    memcpy(dns->hostname, hostname, hostlen);

  if(permanent) {
    dns->timestamp.tv_sec = 0; /* an entry that never goes stale */
    dns->timestamp.tv_usec = 0; /* an entry that never goes stale */
  }
  else {
    dns->timestamp = *Curl_pgrs_now(data);
  }

  /* Take the given address lists into the entry */
  if(paddr1 && *paddr1) {
    dns->addr = *paddr1;
    *paddr1 = NULL;
  }
  if(paddr2 && *paddr2) {
    struct Curl_addrinfo **phead = &dns->addr;
    while(*phead)
      phead = &(*phead)->ai_next;
    *phead = *paddr2;
    *paddr2 = NULL;
  }

  if((dns_queries & CURL_DNSQ_A) &&
     dnscache_ai_has_family(dns->addr, PF_INET))
    dns->dns_responses |= CURL_DNSQ_A;

#ifdef USE_IPV6
  if((dns_queries & CURL_DNSQ_AAAA) &&
     dnscache_ai_has_family(dns->addr, PF_INET6))
    dns->dns_responses |= CURL_DNSQ_AAAA;
#endif /* USE_IPV6 */

#ifndef CURL_DISABLE_SHUFFLE_DNS
  /* shuffle addresses if requested */
  if(data->set.dns_shuffle_addresses && dns->addr) {
    CURLcode result = dns_shuffle_addr(data, &dns->addr);
    if(result) {
      /* free without lock, we are the sole owner */
      dnscache_entry_free(dns);
      dns = NULL;
      goto out;
    }
  }
#else
  (void)data;
#endif

out:
  if(paddr1 && *paddr1) {
    Curl_freeaddrinfo(*paddr1);
    *paddr1 = NULL;
  }
  if(paddr2 && *paddr2) {
    Curl_freeaddrinfo(*paddr2);
    *paddr2 = NULL;
  }
  return dns;
}

struct Curl_dns_entry *Curl_dnscache_mk_entry(struct Curl_easy *data,
                                              uint8_t dns_queries,
                                              struct Curl_addrinfo **paddr,
                                              const char *hostname,
                                              uint16_t port)
{
  return dnscache_entry_create(data, dns_queries, paddr, NULL, hostname,
                               hostname ? strlen(hostname) : 0,
                               port, FALSE);
}

struct Curl_dns_entry *Curl_dnscache_mk_entry2(struct Curl_easy *data,
                                               uint8_t dns_queries,
                                               struct Curl_addrinfo **paddr1,
                                               struct Curl_addrinfo **paddr2,
                                               const char *hostname,
                                               uint16_t port)
{
  return dnscache_entry_create(data, dns_queries, paddr1, paddr2, hostname,
                               hostname ? strlen(hostname) : 0,
                               port, FALSE);
}

#ifdef USE_HTTPSRR
void Curl_dns_entry_set_https_rr(struct Curl_dns_entry *dns,
                                 struct Curl_https_rrinfo *hinfo)
{
  /* only do this when this is the only reference */
  DEBUGASSERT(dns->refcount == 1);
  /* it should have been in the queries */
  DEBUGASSERT(dns->dns_queries & CURL_DNSQ_HTTPS);
  if(dns->hinfo) {
    Curl_httpsrr_cleanup(dns->hinfo);
    curlx_free(dns->hinfo);
  }
  dns->hinfo = hinfo;
  dns->dns_responses |= CURL_DNSQ_HTTPS;
}
#endif /* USE_HTTPSRR */

static struct Curl_dns_entry *dnscache_add_addr(struct Curl_easy *data,
                                                struct Curl_dnscache *dnscache,
                                                uint8_t dns_queries,
                                                struct Curl_addrinfo **paddr,
                                                const char *hostname,
                                                size_t hlen,
                                                uint16_t port,
                                                bool permanent)
{
  char entry_id[MAX_HOSTCACHE_LEN];
  size_t entry_len;
  struct Curl_dns_entry *dns;
  struct Curl_dns_entry *dns2;

  dns = dnscache_entry_create(data, dns_queries, paddr, NULL,
                              hostname, hlen, port, permanent);
  if(!dns)
    return NULL;

  /* Create an entry id, based upon the hostname and port */
  entry_len = create_dnscache_id(hostname, hlen, port,
                                 entry_id, sizeof(entry_id));

  /* Store the resolved data in our DNS cache. */
  dns2 = Curl_hash_add(&dnscache->entries, entry_id, entry_len + 1,
                       (void *)dns);
  if(!dns2) {
    dnscache_entry_free(dns);
    return NULL;
  }

  dns = dns2;
  dns->refcount++;         /* mark entry as in-use */
  return dns;
}

CURLcode Curl_dnscache_add(struct Curl_easy *data,
                           struct Curl_dns_entry *entry)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  char id[MAX_HOSTCACHE_LEN];
  size_t idlen;

  if(!dnscache)
    return CURLE_FAILED_INIT;
  /* Create an entry id, based upon the hostname and port */
  idlen = create_dnscache_id(entry->hostname, 0, entry->port, id, sizeof(id));

  /* Store the resolved data in our DNS cache and up ref count */
  dnscache_lock(data, dnscache);
  if(!Curl_hash_add(&dnscache->entries, id, idlen + 1, (void *)entry)) {
    dnscache_unlock(data, dnscache);
    return CURLE_OUT_OF_MEMORY;
  }
  entry->refcount++;
  dnscache_unlock(data, dnscache);
  return CURLE_OK;
}

CURLcode Curl_dnscache_add_negative(struct Curl_easy *data,
                                    uint8_t dns_queries,
                                    const char *host,
                                    uint16_t port)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  struct Curl_dns_entry *dns;
  DEBUGASSERT(dnscache);
  if(!dnscache)
    return CURLE_FAILED_INIT;

  dnscache_lock(data, dnscache);

  /* put this new host in the cache */
  dns = dnscache_add_addr(data, dnscache, dns_queries, NULL,
                          host, strlen(host), port, FALSE);
  if(dns) {
    /* release the returned reference; the cache itself will keep the
     * entry alive: */
    dns->refcount--;
    dnscache_unlock(data, dnscache);
    CURL_TRC_DNS(data, "cache negative name resolve for %s:%d type=%s",
                 host, port, Curl_resolv_query_str(dns_queries));
    return CURLE_OK;
  }
  dnscache_unlock(data, dnscache);
  return CURLE_OUT_OF_MEMORY;
}

/*
 * Curl_dns_entry_unlink() releases a reference to the given cached DNS entry.
 * When the reference count reaches 0, the entry is destroyed. It is important
 * that only one unlink is made for each Curl_resolv() call.
 *
 * May be called with 'data' == NULL for global cache.
 */
void Curl_dns_entry_unlink(struct Curl_easy *data,
                           struct Curl_dns_entry **pdns)
{
  if(*pdns) {
    struct Curl_dnscache *dnscache = dnscache_get(data);
    struct Curl_dns_entry *dns = *pdns;
    *pdns = NULL;
    dnscache_lock(data, dnscache);
    dns->refcount--;
    if(dns->refcount == 0)
      dnscache_entry_free(dns);
    dnscache_unlock(data, dnscache);
  }
}

static void dnscache_entry_dtor(void *entry)
{
  struct Curl_dns_entry *dns = (struct Curl_dns_entry *)entry;
  DEBUGASSERT(dns && (dns->refcount > 0));
  dns->refcount--;
  if(dns->refcount == 0)
    dnscache_entry_free(dns);
}

/*
 * Curl_dnscache_init() inits a new DNS cache.
 */
void Curl_dnscache_init(struct Curl_dnscache *dns, size_t size)
{
  Curl_hash_init(&dns->entries, size, Curl_hash_str, curlx_str_key_compare,
                 dnscache_entry_dtor);
}

void Curl_dnscache_destroy(struct Curl_dnscache *dns)
{
  Curl_hash_destroy(&dns->entries);
}

CURLcode Curl_loadhostpairs(struct Curl_easy *data)
{
  struct Curl_dnscache *dnscache = dnscache_get(data);
  struct curl_slist *hostp;

  if(!dnscache)
    return CURLE_FAILED_INIT;

  /* Default is no wildcard found */
  data->state.wildcard_resolve = FALSE;

  for(hostp = data->state.resolve; hostp; hostp = hostp->next) {
    char entry_id[MAX_HOSTCACHE_LEN];
    const char *host = hostp->data;
    struct Curl_str source;
    if(!host)
      continue;
    if(*host == '-') {
      curl_off_t num = 0;
      size_t entry_len;
      host++;
      if(!curlx_str_single(&host, '[')) {
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
           curlx_str_single(&host, ']') ||
           curlx_str_single(&host, ':'))
          continue;
      }
      else {
        if(curlx_str_until(&host, &source, 4096, ':') ||
           curlx_str_single(&host, ':')) {
          continue;
        }
      }

      if(!curlx_str_number(&host, &num, 0xffff)) {
        /* Create an entry id, based upon the hostname and port */
        entry_len = create_dnscache_id(curlx_str(&source),
                                       curlx_strlen(&source), (uint16_t)num,
                                       entry_id, sizeof(entry_id));
        dnscache_lock(data, dnscache);
        /* delete entry, ignore if it did not exist */
        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
        dnscache_unlock(data, dnscache);
      }
    }
    else {
      struct Curl_dns_entry *dns;
      struct Curl_addrinfo *head = NULL, *tail = NULL;
      size_t entry_len;
      char address[64];
      curl_off_t tmpofft = 0;
      uint16_t port = 0;
      bool permanent = TRUE;
      bool error = TRUE;
      VERBOSE(const char *addresses = NULL);

      if(*host == '+') {
        host++;
        permanent = FALSE;
      }
      if(!curlx_str_single(&host, '[')) {
        if(curlx_str_until(&host, &source, MAX_IPADR_LEN, ']') ||
           curlx_str_single(&host, ']'))
          continue;
      }
      else {
        if(curlx_str_until(&host, &source, 4096, ':'))
          continue;
      }
      if(curlx_str_single(&host, ':') ||
         curlx_str_number(&host, &tmpofft, 0xffff) ||
         curlx_str_single(&host, ':'))
        goto err;
      port = (uint16_t)tmpofft;

      VERBOSE(addresses = host);

      /* start the address section */
      while(*host) {
        struct Curl_str target;
        struct Curl_addrinfo *ai;
        CURLcode result;

        if(!curlx_str_single(&host, '[')) {
          if(curlx_str_until(&host, &target, MAX_IPADR_LEN, ']') ||
             curlx_str_single(&host, ']'))
            goto err;
        }
        else {
          if(curlx_str_until(&host, &target, 4096, ',')) {
            if(curlx_str_single(&host, ','))
              goto err;
            /* survive nothing but a comma */
            continue;
          }
        }
#ifndef USE_IPV6
        if(memchr(curlx_str(&target), ':', curlx_strlen(&target))) {
          infof(data, "Ignoring resolve address '%.*s', missing IPv6 support.",
                (int)curlx_strlen(&target), curlx_str(&target));
          if(curlx_str_single(&host, ','))
            goto err;
          continue;
        }
#endif

        if(curlx_strlen(&target) >= sizeof(address))
          goto err;

        memcpy(address, curlx_str(&target), curlx_strlen(&target));
        address[curlx_strlen(&target)] = '\0';

        result = Curl_str2addr(address, port, &ai);
        if(result) {
          infof(data, "Resolve IP address '%s' found is illegal", address);
          goto err;
        }

        if(tail) {
          tail->ai_next = ai;
          tail = tail->ai_next;
        }
        else {
          head = tail = ai;
        }
        if(curlx_str_single(&host, ','))
          break;
      }

      if(!head)
        goto err;

      error = FALSE;
err:
      if(error) {
        failf(data, "Could not parse CURLOPT_RESOLVE entry '%s'", hostp->data);
        Curl_freeaddrinfo(head);
        return CURLE_SETOPT_OPTION_SYNTAX;
      }

      /* Create an entry id, based upon the hostname and port */
      entry_len = create_dnscache_id(curlx_str(&source), curlx_strlen(&source),
                                     port, entry_id, sizeof(entry_id));

      dnscache_lock(data, dnscache);

      /* See if it is already in our dns cache */
      dns = Curl_hash_pick(&dnscache->entries, entry_id, entry_len + 1);

      if(dns) {
        infof(data, "RESOLVE %.*s:%u - old addresses discarded",
              (int)curlx_strlen(&source),
              curlx_str(&source), port);
        /* delete old entry, there are two reasons for this
         1. old entry may have different addresses.
         2. even if entry with correct addresses is already in the cache,
            but if it is close to expire, then by the time next http
            request is made, it can get expired and pruned because old
            entry is not necessarily marked as permanent.
         3. when adding a non-permanent entry, we want it to remove and
            replace an existing permanent entry.
         4. when adding a non-permanent entry, we want it to get a "fresh"
            timeout that starts _now_. */

        Curl_hash_delete(&dnscache->entries, entry_id, entry_len + 1);
      }

      /* put this new host in the cache, an override for ALL dns queries */
      dns = dnscache_add_addr(data, dnscache, CURL_DNSQ_ALL,
                              &head, curlx_str(&source),
                              curlx_strlen(&source), port, permanent);
      if(dns)
        /* release the returned reference; the cache itself will keep the
         * entry alive: */
        dns->refcount--;

      dnscache_unlock(data, dnscache);

      if(!dns)
        return CURLE_OUT_OF_MEMORY;

      infof(data, "Added %.*s:%u:%s to DNS cache%s",
            (int)curlx_strlen(&source), curlx_str(&source), port, addresses,
            permanent ? "" : " (non-permanent)");

      /* Wildcard hostname */
      if(curlx_str_casecompare(&source, "*")) {
        infof(data, "RESOLVE *:%u using wildcard", port);
        data->state.wildcard_resolve = TRUE;
      }
    }
  }
  data->state.resolve = NULL; /* dealt with now */

  return CURLE_OK;
}